Adds the music library artist test suite

This commit is contained in:
BinaryAlley committed 2026-09-27 23:04:50 +03:00
1 parent 5d3e430dd1
commit e73b3997bc
77 files changed
+20974 -15

No files matched your search

@@ -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;
/// <summary>
/// Fixture class for the <see cref="ArtistLiteRow"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtistLiteRowFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="ArtistLiteRow"/>.
/// </summary>
/// <param name="id">Optional. The Id of the artist.</param>
/// <param name="name">Optional. The name of the artist.</param>
/// <returns>The created <see cref="ArtistLiteRow"/>.</returns>
public ArtistLiteRow Create(
Guid? id = null,
string? name = null)
{
return new ArtistLiteRow
{
Id = id ?? _faker.Random.Guid(),
Name = name ?? _faker.Name.FullName()
};
}
/// <summary>
/// Creates a list of <see cref="ArtistLiteRow"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ArtistLiteRow"/> instances.</returns>
public List<ArtistLiteRow> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -24,8 +24,12 @@ public class ArtistEntityFixture
/// <param name="id">Optional. The Id of the artist.</param>
/// <param name="libraryId">Optional. The Id of the media library that owns the artist.</param>
/// <param name="name">Optional. The name of the artist.</param>
/// <param name="website">Optional. The website of the artist.</param>
/// <param name="musicBrainzArtistId">Optional. The MusicBrainz identifier of the artist.</param>
/// <param name="albums">Optional. The albums of the artist.</param>
/// <param name="includeAlbums">Whether the artist should own a generated album, or no album at all.</param>
/// <param name="includeWebsite">Whether the website should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzArtistId">Whether the MusicBrainz identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContributors">Whether the artist should own a generated media contributor, or none at all.</param>
/// <param name="includeMetadata">Whether the owned metadata collections of the generated album should be included, or forced to empty collections.</param>
/// <returns>The created <see cref="ArtistEntity"/>.</returns>
@@ -33,8 +37,12 @@ public class ArtistEntityFixture
Guid? id = null,
Guid? libraryId = null,
string? name = null,
string? website = null,
Guid? musicBrainzArtistId = null,
List<AlbumEntity>? 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())
@@ -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;
/// <summary>
/// Fixture class for the <see cref="AddArtistCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddArtistCommandFixture
{
private readonly Faker _faker = new();
private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
/// <summary>
/// Creates a random valid command to add an artist.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the artist belongs to, taken from the route.</param>
/// <param name="name">Optional. The name of the artist.</param>
/// <param name="website">Optional. The website of the artist.</param>
/// <param name="musicBrainzArtistId">Optional. The MusicBrainz identifier of the artist.</param>
/// <param name="contributors">Optional. The media contributors that make up the artist.</param>
/// <param name="albums">Optional. The albums of the artist, each with its own tracks.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeWebsite">Whether the website should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzArtistId">Whether the MusicBrainz identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContributors">Whether the contributors should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbums">Whether the albums should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created command to add an artist.</returns>
public AddArtistCommand Create(
string? libraryId = null,
string? name = null,
string? website = null,
Guid? musicBrainzArtistId = null,
List<MediaContributorReferenceDto>? contributors = null,
List<AddAlbumCommand>? 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);
}
/// <summary>
/// Creates a list of <see cref="AddArtistCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<AddArtistCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Generates the albums of the artist, tied to the artist's library identifier.
/// </summary>
/// <param name="libraryId">The Id of the media library the albums belong to.</param>
/// <returns>The generated albums.</returns>
private List<AddAlbumCommand> GenerateAlbums(string? libraryId)
{
return [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _addAlbumCommandFixture.Create(libraryId: libraryId))];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="DeleteArtistCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteArtistCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="DeleteArtistCommand"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the artist belongs to, taken from the route.</param>
/// <param name="artistId">Optional. The Id of the artist to delete, taken from the route.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="DeleteArtistCommand"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="DeleteArtistCommand"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="DeleteArtistCommand"/> instances.</returns>
public List<DeleteArtistCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="UpdateArtistCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistCommandFixture
{
private readonly Faker _faker = new();
private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
/// <summary>
/// Creates a random valid command to update an artist.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the artist belongs to, taken from the route.</param>
/// <param name="artistId">Optional. The Id of the artist, taken from the route.</param>
/// <param name="name">Optional. The name of the artist.</param>
/// <param name="website">Optional. The website of the artist.</param>
/// <param name="musicBrainzArtistId">Optional. The MusicBrainz identifier of the artist.</param>
/// <param name="contributors">Optional. The media contributors that make up the artist.</param>
/// <param name="albums">Optional. The albums of the artist, each with its own tracks.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeWebsite">Whether the website should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzArtistId">Whether the MusicBrainz identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContributors">Whether the contributors should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbums">Whether the albums should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created command to update an artist.</returns>
public UpdateArtistCommand Create(
string? libraryId = null,
string? artistId = null,
string? name = null,
string? website = null,
Guid? musicBrainzArtistId = null,
List<MediaContributorReferenceDto>? contributors = null,
List<AddAlbumCommand>? 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);
}
/// <summary>
/// Creates a list of <see cref="UpdateArtistCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<UpdateArtistCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Generates the albums of the artist, tied to the artist's library identifier.
/// </summary>
/// <param name="libraryId">The Id of the media library the albums belong to.</param>
/// <returns>The generated albums.</returns>
private List<AddAlbumCommand> GenerateAlbums(string? libraryId)
{
return [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _addAlbumCommandFixture.Create(libraryId: libraryId))];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetArtistQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistQueryFixture
{
/// <summary>
/// Creates a random valid <see cref="GetArtistQuery"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the artist belongs to, taken from the route.</param>
/// <param name="artistId">Optional. The Id of the artist to get, taken from the route.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetArtistQuery"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="GetArtistQuery"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetArtistQuery"/> instances.</returns>
public List<GetArtistQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetArtistAlbumsQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistAlbumsQueryFixture
{
/// <summary>
/// Creates a random valid <see cref="GetArtistAlbumsQuery"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the artist belongs to, taken from the route.</param>
/// <param name="artistId">Optional. The Id of the artist whose albums are retrieved, taken from the route.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetArtistAlbumsQuery"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="GetArtistAlbumsQuery"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetArtistAlbumsQuery"/> instances.</returns>
public List<GetArtistAlbumsQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetArtistAlbumsLiteQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistAlbumsLiteQueryFixture
{
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
/// <summary>
/// Creates a random valid <see cref="GetArtistAlbumsLiteQuery"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the artist belongs to, taken from the route.</param>
/// <param name="artistId">Optional. The Id of the artist whose albums are retrieved, taken from the route.</param>
/// <param name="paginationData">Optional. The pagination data of the query.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePaginationData">Whether the pagination data should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetArtistAlbumsLiteQuery"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="GetArtistAlbumsLiteQuery"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetArtistAlbumsLiteQuery"/> instances.</returns>
public List<GetArtistAlbumsLiteQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetArtistsQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsQueryFixture
{
private readonly Faker _faker = new();
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
/// <summary>
/// Creates a random valid <see cref="GetArtistsQuery"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose artists are retrieved, taken from the route.</param>
/// <param name="paginationData">Optional. The pagination data of the query.</param>
/// <param name="searchTerm">Optional. The search term used to filter the artists by name.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePaginationData">Whether the pagination data should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSearchTerm">Whether the search term should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetArtistsQuery"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="GetArtistsQuery"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetArtistsQuery"/> instances.</returns>
public List<GetArtistsQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetArtistsLiteQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsLiteQueryFixture
{
private readonly Faker _faker = new();
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
/// <summary>
/// Creates a random valid <see cref="GetArtistsLiteQuery"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose artists are retrieved, taken from the route.</param>
/// <param name="paginationData">Optional. The pagination data of the query.</param>
/// <param name="searchTerm">Optional. The search term used to filter the artists by name.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePaginationData">Whether the pagination data should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSearchTerm">Whether the search term should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetArtistsLiteQuery"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="GetArtistsLiteQuery"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetArtistsLiteQuery"/> instances.</returns>
public List<GetArtistsLiteQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="AddArtistRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddArtistRequestFixture
{
private readonly Faker _faker = new();
private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
/// <summary>
/// Creates a random valid request to add an artist.
/// </summary>
/// <param name="name">Optional. The name of the artist.</param>
/// <param name="website">Optional. The website of the artist.</param>
/// <param name="musicBrainzArtistId">Optional. The MusicBrainz identifier of the artist.</param>
/// <param name="contributors">Optional. The media contributors that make up the artist.</param>
/// <param name="albums">Optional. The albums of the artist.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeWebsite">Whether the website should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzArtistId">Whether the MusicBrainz artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContributors">Whether the contributors list should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbums">Whether the albums list should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created request to add an artist.</returns>
public AddArtistRequest Create(
string? name = null,
string? website = null,
Guid? musicBrainzArtistId = null,
List<MediaContributorReferenceDto>? contributors = null,
List<AddAlbumRequest>? 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);
}
/// <summary>
/// Creates a list of <see cref="AddArtistRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<AddArtistRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetArtistAlbumsLiteRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistAlbumsLiteRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid request to get the lightweight read models of the albums of an artist.
/// </summary>
/// <param name="currentPage">Optional. The page of results to retrieve.</param>
/// <param name="perPage">Optional. The maximum number of albums to retrieve per page.</param>
/// <param name="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePerPage">Whether the per page count should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created request to get the lightweight read models of the albums of an artist.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="GetArtistAlbumsLiteRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetArtistAlbumsLiteRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetArtistsLiteRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsLiteRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid request to get the lightweight read models of the artists of a media library.
/// </summary>
/// <param name="currentPage">Optional. The page of results to retrieve.</param>
/// <param name="perPage">Optional. The maximum number of artists to retrieve per page.</param>
/// <param name="searchTerm">Optional. The search term used to filter the artists by name.</param>
/// <param name="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePerPage">Whether the per page count should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSearchTerm">Whether the search term should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created request to get the lightweight read models of the artists of a media library.</returns>
public GetArtistsLiteRequest Create(
int? currentPage = null,
int? perPage = null,
string? searchTerm = null,
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);
}
/// <summary>
/// Creates a list of <see cref="GetArtistsLiteRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetArtistsLiteRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetArtistsRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid request to get the artists of a media library.
/// </summary>
/// <param name="currentPage">Optional. The page of results to retrieve.</param>
/// <param name="perPage">Optional. The maximum number of artists to retrieve per page.</param>
/// <param name="searchTerm">Optional. The search term used to filter the artists by name.</param>
/// <param name="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePerPage">Whether the per page count should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSearchTerm">Whether the search term should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created request to get the artists of a media library.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="GetArtistsRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetArtistsRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="UpdateArtistAlbumRequest"/> record.
/// </summary>
[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();
/// <summary>
/// Creates a random valid request to update an album of an artist.
/// </summary>
/// <param name="albumId">Optional. The Id of the album, when the album already exists.</param>
/// <param name="metadata">Optional. The album metadata of the album.</param>
/// <param name="mediaFormat">Optional. The physical or digital medium of the album.</param>
/// <param name="barcode">Optional. The barcode of the album.</param>
/// <param name="catalogNumber">Optional. The catalog number of the album.</param>
/// <param name="musicBrainzReleaseId">Optional. The MusicBrainz identifier of the release.</param>
/// <param name="musicBrainzReleaseGroupId">Optional. The MusicBrainz identifier of the release group.</param>
/// <param name="musicBrainzReleaseArtistId">Optional. The MusicBrainz identifier of the release artist.</param>
/// <param name="contributors">Optional. The media contributors that performed on the album.</param>
/// <param name="ratings">Optional. The ratings of the album.</param>
/// <param name="tracks">Optional. The tracks of the album.</param>
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMetadata">Whether the metadata should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMediaFormat">Whether the media format should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBarcode">Whether the barcode should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeCatalogNumber">Whether the catalog number should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzReleaseId">Whether the MusicBrainz release Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzReleaseGroupId">Whether the MusicBrainz release group Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzReleaseArtistId">Whether the MusicBrainz release artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContributors">Whether the contributors list should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeRatings">Whether the ratings list should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTracks">Whether the tracks list should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created request to update an album of an artist.</returns>
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<MediaContributorReferenceDto>? contributors = null,
List<AudioRatingDto>? ratings = null,
List<UpdateArtistTrackRequest>? 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<MusicMediaFormat>()) : 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);
}
/// <summary>
/// Creates a list of <see cref="UpdateArtistAlbumRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<UpdateArtistAlbumRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="UpdateArtistRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistRequestFixture
{
private readonly Faker _faker = new();
private readonly UpdateArtistAlbumRequestFixture _updateArtistAlbumRequestFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
/// <summary>
/// Creates a random valid request to update an artist.
/// </summary>
/// <param name="name">Optional. The name of the artist.</param>
/// <param name="website">Optional. The website of the artist.</param>
/// <param name="musicBrainzArtistId">Optional. The MusicBrainz identifier of the artist.</param>
/// <param name="contributors">Optional. The media contributors that make up the artist.</param>
/// <param name="albums">Optional. The albums of the artist.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeWebsite">Whether the website should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzArtistId">Whether the MusicBrainz artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContributors">Whether the contributors list should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbums">Whether the albums list should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created request to update an artist.</returns>
public UpdateArtistRequest Create(
string? name = null,
string? website = null,
Guid? musicBrainzArtistId = null,
List<MediaContributorReferenceDto>? contributors = null,
List<UpdateArtistAlbumRequest>? 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);
}
/// <summary>
/// Creates a list of <see cref="UpdateArtistRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<UpdateArtistRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -55,7 +55,16 @@ public class UpdateArtistTrackRequestFixture
/// <param name="includePath">Whether the path should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMetadata">Whether the metadata should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTrackNumber">Whether the track number should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeOptionalProperties">Whether the optional properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
/// <param name="includeDiscNumber">Whether the disc number should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeScript">Whether the script should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeKey">Whether the musical key should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBpm">Whether the tempo should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeWork">Whether the work should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzRecordingId">Whether the MusicBrainz recording Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzTrackId">Whether the MusicBrainz track Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzWorkId">Whether the MusicBrainz work Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMoods">Whether the moods should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeIsrcs">Whether the ISRC codes should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContributors">Whether the contributors list should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeRatings">Whether the ratings list should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created request to update a track of an album of an artist.</returns>
@@ -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<MusicKey>()) : 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<MusicKey>()) : 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);
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="ArtistLiteResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtistLiteResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="ArtistLiteResponse"/>.
/// </summary>
/// <param name="id">Optional. The Id of the artist.</param>
/// <param name="name">Optional. The name of the artist.</param>
/// <returns>The created <see cref="ArtistLiteResponse"/>.</returns>
public ArtistLiteResponse Create(
Guid? id = null,
string? name = null)
{
return new ArtistLiteResponse(
id ?? Guid.NewGuid(),
name ?? _faker.Name.FullName());
}
/// <summary>
/// Creates a list of <see cref="ArtistLiteResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<ArtistLiteResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="ArtistResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtistResponseFixture
{
private readonly Faker _faker = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly AlbumResponseFixture _albumResponseFixture = new();
/// <summary>
/// Creates a random valid <see cref="ArtistResponse"/>.
/// </summary>
/// <param name="id">Optional. The Id of the artist.</param>
/// <param name="libraryId">Optional. The Id of the media library the artist belongs to.</param>
/// <param name="name">Optional. The name of the artist.</param>
/// <param name="website">Optional. The website of the artist.</param>
/// <param name="musicBrainzArtistId">Optional. The MusicBrainz identifier of the artist.</param>
/// <param name="contributors">Optional. The list of contributor references of the artist.</param>
/// <param name="albums">Optional. The list of albums of the artist.</param>
/// <param name="createdOnUtc">Optional. The date and time when the artist was created.</param>
/// <param name="updatedOnUtc">Optional. The date and time when the artist was updated.</param>
/// <param name="includeWebsite">Whether the website should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzArtistId">Whether the MusicBrainz artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeUpdatedOnUtc">Whether the update date should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContributors">Whether the contributors should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbums">Whether the albums should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="ArtistResponse"/>.</returns>
public ArtistResponse Create(
Guid? id = null,
Guid? libraryId = null,
string? name = null,
string? website = null,
Guid? musicBrainzArtistId = null,
List<MediaContributorReferenceDto>? contributors = null,
List<AlbumResponse>? 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);
}
/// <summary>
/// Creates a list of <see cref="ArtistResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<ArtistResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="AddArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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();
/// <summary>
/// Initializes a new instance of the <see cref="AddArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddArtistEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task 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<ArtistResponse>(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);
}
/// <summary>
/// Seeds a music library of type music, owned by <paramref name="userId"/>, whose single content location is the temp path.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
}
/// <summary>
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="statusCode">The expected HTTP status code.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedType">The expected problem type URI.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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()!);
}
/// <summary>
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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());
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="DeleteArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DeleteArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteArtistEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task 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<LuminaDbContext>();
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");
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist of that library.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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");
}
/// <summary>
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="statusCode">The expected HTTP status code.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedType">The expected problem type URI.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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()!);
}
/// <summary>
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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());
}
/// <summary>
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="GetArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetArtistEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task 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<ArtistResponse>(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<LuminaDbContext>();
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");
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist of that library.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="artistName">The name of the seeded artist.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId, string artistName)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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");
}
/// <summary>
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="statusCode">The expected HTTP status code.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedType">The expected problem type URI.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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()!);
}
/// <summary>
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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());
}
/// <summary>
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="GetArtistAlbumsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistAlbumsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetArtistAlbumsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task 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<AlbumResponse>? albums = await response.Content.ReadFromJsonAsync<List<AlbumResponse>>(_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<AlbumResponse>? albums = await response.Content.ReadFromJsonAsync<List<AlbumResponse>>(_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");
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds an artist belonging to the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <returns>The Id of the seeded artist.</returns>
private async Task<Guid> SeedArtistAsync(Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid artistId = Guid.NewGuid();
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
return artistId;
}
/// <summary>
/// Seeds an album belonging to the artist identified by <paramref name="artistId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="title">The title of the album.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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();
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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");
}
/// <summary>
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="statusCode">The expected HTTP status code.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedType">The expected problem type URI.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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()!);
}
/// <summary>
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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());
}
/// <summary>
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="GetArtistAlbumsLiteEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistAlbumsLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsLiteEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetArtistAlbumsLiteEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task 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<AlbumLiteResponse>? albums = await response.Content.ReadFromJsonAsync<PaginatedResponse<AlbumLiteResponse>>(_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<AlbumLiteResponse>? albums = await response.Content.ReadFromJsonAsync<PaginatedResponse<AlbumLiteResponse>>(_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");
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds an artist belonging to the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <returns>The Id of the seeded artist.</returns>
private async Task<Guid> SeedArtistAsync(Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid artistId = Guid.NewGuid();
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
return artistId;
}
/// <summary>
/// Seeds an album belonging to the artist identified by <paramref name="artistId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="title">The title of the album.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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();
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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");
}
/// <summary>
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="statusCode">The expected HTTP status code.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedType">The expected problem type URI.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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()!);
}
/// <summary>
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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());
}
/// <summary>
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="GetArtistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetArtistsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task 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<ArtistResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistResponse>>(_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<ArtistResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistResponse>>(_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<ArtistResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistResponse>>(_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<ArtistResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistResponse>>(_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");
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds an artist belonging to the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="name">The name of the artist.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtistAsync(Guid libraryId, string name)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Artists.Add(_artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="statusCode">The expected HTTP status code.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedType">The expected problem type URI.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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()!);
}
/// <summary>
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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());
}
/// <summary>
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="GetArtistsLiteEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsLiteEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetArtistsLiteEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task 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<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_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<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
Assert.NotNull(paginatedArtists);
Assert.Empty(paginatedArtists!.Data);
Assert.Equal(0, paginatedArtists.Count);
}
[Fact]
public async Task GetArtistsLite_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");
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds an artist belonging to the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="name">The name of the artist.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtistAsync(Guid libraryId, string name)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Artists.Add(_artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="statusCode">The expected HTTP status code.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedType">The expected problem type URI.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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()!);
}
/// <summary>
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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());
}
/// <summary>
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="UpdateArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateArtistEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task 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<ArtistResponse>(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<LuminaDbContext>();
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");
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds an artist that owns a single album, both belonging to <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <returns>The Ids of the seeded artist and album.</returns>
private async Task<(Guid artistId, Guid albumId)> SeedArtistWithAlbumAsync(Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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");
}
/// <summary>
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="statusCode">The expected HTTP status code.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedType">The expected problem type URI.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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()!);
}
/// <summary>
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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());
}
/// <summary>
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="AddArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddArtistEndpointTests : IClassFixture<LuminaApiFactory>, 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<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="AddArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<LuminaDbContext>();
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="DeleteArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteArtistEndpointTests : IClassFixture<LuminaApiFactory>, 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<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<LuminaDbContext>();
Assert.NotNull(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId));
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist of that library.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="GetArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistEndpointTests : IClassFixture<LuminaApiFactory>, 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<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist of that library.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="GetArtistAlbumsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistAlbumsEndpointTests : IClassFixture<LuminaApiFactory>, 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<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist of that library.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="GetArtistAlbumsLiteEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistAlbumsLiteEndpointTests : IClassFixture<LuminaApiFactory>, 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<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsLiteEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist of that library.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="GetArtistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsEndpointTests : IClassFixture<LuminaApiFactory>, 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<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<LuminaDbContext>();
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds an artist belonging to the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="name">The name of the artist.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtistAsync(Guid libraryId, string name)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Artists.Add(_artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="GetArtistsLiteEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsLiteEndpointTests : IClassFixture<LuminaApiFactory>, 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<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsLiteEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<LuminaDbContext>();
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds an artist belonging to the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="name">The name of the artist.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtistAsync(Guid libraryId, string name)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Artists.Add(_artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="UpdateArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistEndpointTests : IClassFixture<LuminaApiFactory>, 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<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<LuminaDbContext>();
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<LuminaDbContext>();
ArtistEntity? storedArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId);
Assert.NotNull(storedArtist);
Assert.Equal("Queen", storedArtist.Name);
}
/// <summary>
/// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload.
/// </summary>
/// <param name="response">The HTTP response to assert.</param>
/// <param name="injectedPayload">The injected payload that must never be echoed back.</param>
/// <param name="expectedErrorCode">The validation error code expected in the response.</param>
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);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist that owns one album.
/// </summary>
/// <param name="libraryId">The Id of the media library to seed.</param>
/// <param name="userId">The Id of the user that owns the media library.</param>
/// <returns>The Ids of the seeded artist and of its album.</returns>
private async Task<(Guid artistId, Guid albumId)> SeedArtistAsync(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="AddArtistCommandMapping"/> class.
/// </summary>
[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<Artist> 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<Artist> 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<Artist> 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<Artist> 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<Artist> result = command.ToDomainEntity(Guid.NewGuid());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="AddArtistRequestMapping"/> class.
/// </summary>
[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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="ArtistEntityMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtistEntityMappingTests
{
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly PaginatedResultDtoFixture<ArtistEntity> _paginatedResultDtoFixture = new();
[Fact]
public void ToDomainEntity_WhenMappingValidArtistEntity_ShouldMapAllPropertiesCorrectly()
{
// Arrange
ArtistEntity entity = _artistEntityFixture.Create();
// Act
Result<Artist> 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<Artist> 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<Artist> 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<ArtistEntity> entities = _artistEntityFixture.CreateMany(2);
// Act
IReadOnlyList<ArtistResponse> 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<ArtistEntity> entities = _artistEntityFixture.CreateMany(2);
PaginatedResultDto<ArtistEntity> paginatedEntities = _paginatedResultDtoFixture.Create(
data: entities,
currentPage: 1,
perPage: 10,
count: 2,
numberOfPages: 1);
// Act
PaginatedResponse<ArtistResponse> 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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="ArtistLiteRowMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtistLiteRowMappingTests
{
private readonly ArtistLiteRowFixture _artistLiteRowFixture = new();
private readonly PaginatedResultDtoFixture<ArtistLiteRow> _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<ArtistLiteRow> readModels = _artistLiteRowFixture.CreateMany(2);
// Act
IReadOnlyList<ArtistLiteResponse> 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<ArtistLiteRow> readModels = _artistLiteRowFixture.CreateMany(2);
PaginatedResultDto<ArtistLiteRow> paginatedReadModels = _paginatedResultDtoFixture.Create(
data: readModels,
currentPage: 1,
perPage: 10,
count: 2,
numberOfPages: 1);
// Act
PaginatedResponse<ArtistLiteResponse> 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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="ArtistMapping"/> class.
/// </summary>
[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<MusicMediaFormat>.None(),
barcode: Optional<Barcode>.None(),
catalogNumber: Optional<string>.None(),
musicBrainzReleaseId: Optional<MusicBrainzId>.None(),
musicBrainzReleaseGroupId: Optional<MusicBrainzId>.None(),
musicBrainzReleaseArtistId: Optional<MusicBrainzId>.None());
Artist artist = _artistFixture.Create(
website: Optional<string>.None(),
musicBrainzArtistId: Optional<MusicBrainzId>.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<string>.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<MusicBrainzId>.Some(musicBrainzArtistId));
// Act
ArtistEntity result = artist.ToRepositoryEntity();
// Assert
Assert.Equal(musicBrainzArtistId.Value, result.MusicBrainzArtistId);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistAlbumsLiteRequestMapping"/> class.
/// </summary>
[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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistsLiteRequestMapping"/> class.
/// </summary>
[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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistsRequestMapping"/> class.
/// </summary>
[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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="UpdateArtistAlbumRequestMapping"/> class.
/// </summary>
[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<UpdateArtistAlbumRequest> requests = _updateArtistAlbumRequestFixture.CreateMany(3);
// Act
List<AddAlbumCommand> 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);
}
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="UpdateArtistCommandMapping"/> class.
/// </summary>
[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<Artist> 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<Artist> 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<Artist> 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<Artist> 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<Artist> 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<Artist> 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<Artist> 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<Artist> result = command.ToDomainEntity(artist);
// Assert
Assert.False(result.IsFailure);
Album updatedAlbum = result.Value.Albums.First(album => album.Id.Value == albumId);
Assert.Empty(updatedAlbum.Tracks);
}
/// <summary>
/// Creates a domain artist that owns a single album, which in turn owns a single track, all belonging to <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <returns>The created domain artist, together with the Ids of its album and track.</returns>
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<Artist> artistResult = artistEntity.ToDomainEntity();
return (artistResult.Value, albumId, trackId);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="UpdateArtistRequestMapping"/> class.
/// </summary>
[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);
}
}
@@ -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
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="AddArtistCommandHandler"/> class.
/// </summary>
[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<AddArtistCommand> _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();
/// <summary>
/// Initializes a new instance of the <see cref="AddArtistCommandHandlerTests"/> class.
/// </summary>
public AddArtistCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<AddArtistCommand>>();
_mockPathService = Substitute.For<IPathService>();
_userId = Guid.NewGuid();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
// Default stub: saving changes succeeds.
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Default stubs: the validator passes, the current user is authenticated and the library ownership policy allows access.
_mockValidator.Validate(Arg.Any<AddArtistCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
// Default stubs: the library exists and the track paths are inside its content locations.
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>())
.Returns(true);
// Default stub: every referenced media contributor already exists.
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
IReadOnlyCollection<Guid> contributorIds = callInfo.Arg<IReadOnlyCollection<Guid>>();
return Result.From<IReadOnlyList<MediaContributorEntity>>([.. 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<ArtistEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Result.From<ArtistEntity?>(_artistEntityFixture.Create(id: callInfo.Arg<Guid>(), 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<AddArtistCommand>())
.Returns([Errors.Music.ArtistNameCannotBeEmpty]);
// Act
Result<ArtistResponse> 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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().InsertAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
AddArtistCommand command = _addArtistCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ArtistResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError()
{
// Arrange
AddArtistCommand command = _addArtistCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<ArtistResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutPersisting()
{
// Arrange
AddArtistCommand command = _addArtistCommandFixture.Create();
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
{
// Arrange
AddArtistCommand command = _addArtistCommandFixture.Create();
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(null));
// Act
Result<ArtistResponse> 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<CancellationToken>());
}
[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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(contentLocations: ["/music"])));
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>())
.Returns(false);
// Act
Result<ArtistResponse> 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<string>(), Arg.Any<string>());
await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenContributorRepositoryFails_ShouldReturnFailureResultWithoutPersisting()
{
// Arrange
AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]);
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<ArtistResponse> 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<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnMediaContributorNotFoundError()
{
// Arrange
AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]);
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([]));
// Act
Result<ArtistResponse> 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<CancellationToken>());
}
[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<ArtistResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting()
{
// Arrange
AddArtistCommand command = _addArtistCommandFixture.Create(name: string.Empty);
// Act
Result<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistRepositoryInsertFails_ShouldReturnFailureResultWithoutSavingChanges()
{
// Arrange
AddArtistCommand command = _addArtistCommandFixture.Create();
_mockArtistRepository.InsertAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReadingTheArtist()
{
// Arrange
AddArtistCommand command = _addArtistCommandFixture.Create();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<ArtistResponse> 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<CancellationToken>());
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPersistedArtistCannotBeRead_ShouldReturnFailureResult()
{
// Arrange
AddArtistCommand command = _addArtistCommandFixture.Create();
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<ArtistResponse> 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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<ArtistEntity?>(null));
// Act
Result<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
insertedArtist = callInfo.Arg<ArtistEntity>();
return Result.Created;
});
ArtistEntity? persistedArtist = null;
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
persistedArtist = _artistEntityFixture.Create(id: callInfo.Arg<Guid>(), includeAlbums: false, includeContributors: false);
return Result.From<ArtistEntity?>(persistedArtist);
});
// Act
Result<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="DeleteArtistCommandHandler"/> class.
/// </summary>
[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<DeleteArtistCommand> _mockValidator;
private readonly DeleteArtistCommandHandler _sut;
private readonly Guid _userId;
private readonly DeleteArtistCommandFixture _deleteArtistCommandFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DeleteArtistCommandHandlerTests"/> class.
/// </summary>
public DeleteArtistCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<DeleteArtistCommand>>();
_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<DeleteArtistCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
_mockArtistRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
// Act
Result<Deleted> 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<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
{
// Arrange
DeleteArtistCommand command = _deleteArtistCommandFixture.Create();
_mockValidator.Validate(Arg.Any<DeleteArtistCommand>())
.Returns([DomainErrors.Music.ArtistIdCannotBeEmpty]);
// Act
Result<Deleted> 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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
DeleteArtistCommand command = _deleteArtistCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Deleted> 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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutDeleting()
{
// Arrange
DeleteArtistCommand command = _deleteArtistCommandFixture.Create();
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> 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<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError()
{
// Arrange
DeleteArtistCommand command = _deleteArtistCommandFixture.Create();
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<ArtistEntity?>(null));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
// Act
Result<Deleted> 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<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> 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<Guid>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(null));
// Act
Result<Deleted> 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<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockArtistRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> 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<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> 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<CancellationToken>());
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="DeleteArtistCommandValidator"/> class.
/// </summary>
[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<Error> 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<Error> 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<Error> 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<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
DeleteArtistCommand command = _deleteArtistCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="UpdateArtistCommandHandler"/> class.
/// </summary>
[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<UpdateArtistCommand> _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();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCommandHandlerTests"/> class.
/// </summary>
public UpdateArtistCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<UpdateArtistCommand>>();
_mockPathService = Substitute.For<IPathService>();
_userId = Guid.NewGuid();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
// Default stub: saving changes succeeds.
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Default stubs: the validator passes, the current user is authenticated and the library ownership policy allows access.
_mockValidator.Validate(Arg.Any<UpdateArtistCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
// Default stubs: the library exists and the track paths are inside its content locations.
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>())
.Returns(true);
// Default stub: every referenced media contributor already exists.
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
IReadOnlyCollection<Guid> contributorIds = callInfo.Arg<IReadOnlyCollection<Guid>>();
return Result.From<IReadOnlyList<MediaContributorEntity>>([.. contributorIds.Select(contributorId => _mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()))]);
});
// Default stub: updating the artist aggregate succeeds.
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
.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<UpdateArtistCommand>()).Returns([Errors.Music.ArtistNameCannotBeEmpty]);
// Act
Result<ArtistResponse> 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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
UpdateArtistCommand command = _updateArtistCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ArtistResponse> 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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutPersisting()
{
// Arrange
UpdateArtistCommand command = _updateArtistCommandFixture.Create();
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<ArtistResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError()
{
// Arrange
UpdateArtistCommand command = _updateArtistCommandFixture.Create();
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<ArtistEntity?>(null));
// Act
Result<ArtistResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[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<ArtistResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
}
[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<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<ArtistResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>());
}
[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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(null));
// Act
Result<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>());
}
[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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(contentLocations: ["/music"])));
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(false);
// Act
Result<ArtistResponse> 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<string>(), Arg.Any<string>());
await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
}
[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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>());
}
[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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([]));
// Act
Result<ArtistResponse> 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<CancellationToken>());
}
[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<ArtistResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<ArtistEntity>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<ArtistResponse> 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<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<ArtistResponse> 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<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
updatedArtist = callInfo.Arg<ArtistEntity>();
return Result.Updated;
});
StubArtistReads(existingArtist, persistedArtist);
// Act
Result<ArtistResponse> 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<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
/// <summary>
/// Creates an existing artist that owns a single album, which belongs to the provided library.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="artistId">The Id of the artist.</param>
/// <param name="albumId">The Id of the album the artist owns.</param>
/// <returns>The created artist entity.</returns>
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);
}
/// <summary>
/// Stubs the artist repository so that the initial artist read, and optionally the persisted artist read, return the provided entities.
/// </summary>
/// <param name="artist">The artist returned by the initial read.</param>
/// <param name="persistedArtist">Optional. The artist returned by the persisted read. When not provided, <paramref name="artist"/> is returned again.</param>
/// <param name="error">Optional. The error returned by the persisted read, when it must fail.</param>
/// <param name="hasPersistedArtist">Whether the persisted read returns a value, which can be <see langword="null"/>.</param>
private void StubArtistReads(ArtistEntity artist, ArtistEntity? persistedArtist = null, Error? error = null, bool hasPersistedArtist = false)
{
Queue<Result<ArtistEntity?>> readResults = new();
readResults.Enqueue(Result.From<ArtistEntity?>(artist));
if (error is not null)
readResults.Enqueue(error);
else if (hasPersistedArtist)
readResults.Enqueue(Result.From(persistedArtist));
else
readResults.Enqueue(Result.From<ArtistEntity?>(persistedArtist ?? artist));
_mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(_ => readResults.Dequeue());
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetArtistQuery> _mockValidator;
private readonly GetArtistQueryHandler _sut;
private readonly Guid _userId;
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly GetArtistQueryFixture _getArtistQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistQueryHandlerTests"/> class.
/// </summary>
public GetArtistQueryHandlerTests()
{
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetArtistQuery>>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetArtistQuery>()).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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString());
// Act
Result<ArtistResponse> 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<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutEvaluatingThePolicy()
{
// Arrange
GetArtistQuery query = _getArtistQueryFixture.Create();
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<ArtistResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError()
{
// Arrange
GetArtistQuery query = _getArtistQueryFixture.Create();
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<ArtistEntity?>(null));
// Act
Result<ArtistResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
// Act
Result<ArtistResponse> 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<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<ArtistResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetArtistQuery query = _getArtistQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ArtistResponse> 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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
{
// Arrange
GetArtistQuery query = _getArtistQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetArtistQuery>()).Returns([Errors.Music.ArtistIdCannotBeEmpty]);
// Act
Result<ArtistResponse> 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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistQueryValidator"/> class.
/// </summary>
[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<Error> 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<Error> 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<Error> 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<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
GetArtistQuery query = _getArtistQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistAlbumsQueryHandler"/> class.
/// </summary>
[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<GetArtistAlbumsQuery> _mockValidator;
private readonly GetArtistAlbumsQueryHandler _sut;
private readonly Guid _userId;
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly GetArtistAlbumsQueryFixture _getArtistAlbumsQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsQueryHandlerTests"/> class.
/// </summary>
public GetArtistAlbumsQueryHandlerTests()
{
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetArtistAlbumsQuery>>();
_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<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetArtistAlbumsQuery>()).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<AlbumEntity> albums = _albumEntityFixture.CreateMany(2);
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>(albums));
GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString());
// Act
Result<IReadOnlyList<AlbumResponse>> 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<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutReadingAlbums()
{
// Arrange
GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create();
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<IReadOnlyList<AlbumResponse>> 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<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError()
{
// Arrange
GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create();
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<ArtistEntity?>(null));
// Act
Result<IReadOnlyList<AlbumResponse>> 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<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
// Act
Result<IReadOnlyList<AlbumResponse>> 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<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<IReadOnlyList<AlbumResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<IReadOnlyList<AlbumResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IReadOnlyList<AlbumResponse>> 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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
{
// Arrange
GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetArtistAlbumsQuery>()).Returns([Errors.Music.ArtistIdCannotBeEmpty]);
// Act
Result<IReadOnlyList<AlbumResponse>> 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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistAlbumsQueryValidator"/> class.
/// </summary>
[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<Error> 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<Error> 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<Error> 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<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistAlbumsLiteQueryHandler"/> class.
/// </summary>
[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<GetArtistAlbumsLiteQuery> _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<AlbumLiteRow> _paginatedResultDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsLiteQueryHandlerTests"/> class.
/// </summary>
public GetArtistAlbumsLiteQueryHandlerTests()
{
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetArtistAlbumsLiteQuery>>();
_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<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetArtistAlbumsLiteQuery>()).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<AlbumLiteRow> albumLiteRows = _albumLiteRowFixture.CreateMany(2);
PaginatedResultDto<AlbumLiteRow> paginatedAlbums = _paginatedResultDtoFixture.Create(data: albumLiteRows, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1);
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockAlbumRepository.GetAlbumsLiteByArtistIdAsync(artistId, Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedAlbums));
GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString());
// Act
Result<PaginatedResponse<AlbumLiteResponse>> 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<AlbumLiteRow> paginatedAlbums = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockAlbumRepository.GetAlbumsLiteByArtistIdAsync(Arg.Any<Guid>(), Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>())
.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<PaginationDataDto>(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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<PaginatedResponse<AlbumLiteResponse>> 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<Guid>(), Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError()
{
// Arrange
GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create();
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<ArtistEntity?>(null));
// Act
Result<PaginatedResponse<AlbumLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
// Act
Result<PaginatedResponse<AlbumLiteResponse>> 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<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetAlbumsLiteByArtistIdAsync(Arg.Any<Guid>(), Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<PaginatedResponse<AlbumLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetAlbumsLiteByArtistIdAsync(Arg.Any<Guid>(), Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockAlbumRepository.GetAlbumsLiteByArtistIdAsync(artistId, Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<PaginatedResponse<AlbumLiteResponse>> 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<PaginatedResponse<AlbumLiteResponse>> 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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
{
// Arrange
GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetArtistAlbumsLiteQuery>()).Returns([Errors.Music.ArtistIdCannotBeEmpty]);
// Act
Result<PaginatedResponse<AlbumLiteResponse>> 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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetAlbumsLiteByArtistIdAsync(Arg.Any<Guid>(), Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>());
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistAlbumsLiteQueryValidator"/> class.
/// </summary>
[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<Error> 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<Error> 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<Error> 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<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistsQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetArtistsQuery> _mockValidator;
private readonly GetArtistsQueryHandler _sut;
private readonly Guid _userId;
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly GetArtistsQueryFixture _getArtistsQueryFixture = new();
private readonly PaginatedResultDtoFixture<ArtistEntity> _paginatedResultDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsQueryHandlerTests"/> class.
/// </summary>
public GetArtistsQueryHandlerTests()
{
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetArtistsQuery>>();
_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<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetArtistsQuery>()).Returns([]);
_sut = new GetArtistsQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenPolicyAllowsAccess_ShouldReturnMappedPaginatedResponses()
{
// Arrange
GetArtistsQuery query = _getArtistsQueryFixture.Create();
List<ArtistEntity> artistEntities = _artistEntityFixture.CreateMany(2);
PaginatedResultDto<ArtistEntity> paginatedArtists = _paginatedResultDtoFixture.Create(data: artistEntities, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1);
_mockArtistRepository.GetAllAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedArtists));
// Act
Result<PaginatedResponse<ArtistResponse>> 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<ArtistEntity> paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
_mockArtistRepository.GetAllAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedArtists));
// Act
Result<PaginatedResponse<ArtistResponse>> 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<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.FilterMustIncludeLibraryId);
// Act
Result<PaginatedResponse<ArtistResponse>> 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<ArtistEntity> paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
_mockArtistRepository.GetAllAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedArtists));
// Act
await _sut.HandleAsync(query, cancellationToken);
// Assert
await _mockArtistRepository.Received(1).GetAllAsync(
Arg.Is<PaginationDataDto>(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && paginationData.PerPage == query.PaginationData.PerPage),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Is<LibraryFilterDto>(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<ArtistEntity> paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
_mockArtistRepository.GetAllAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedArtists));
// Act
await _sut.HandleAsync(query, CancellationToken.None);
// Assert
await _mockArtistRepository.Received(1).GetAllAsync(
Arg.Is<PaginationDataDto?>(paginationData => paginationData == null),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == libraryId && filter.SearchTerm == "Queen"),
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
GetArtistsQuery query = _getArtistsQueryFixture.Create(libraryId: libraryId.ToString());
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<PaginatedResponse<ArtistResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().GetAllAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetArtistsQuery query = _getArtistsQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<PaginatedResponse<ArtistResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().GetAllAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
{
// Arrange
GetArtistsQuery query = _getArtistsQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetArtistsQuery>()).Returns([Errors.Library.LibraryIdCannotBeEmpty]);
// Act
Result<PaginatedResponse<ArtistResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().GetAllAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistsQueryValidator"/> class.
/// </summary>
[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<Error> 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<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
GetArtistsQuery query = _getArtistsQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistsLiteQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsLiteQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetArtistsLiteQuery> _mockValidator;
private readonly GetArtistsLiteQueryHandler _sut;
private readonly Guid _userId;
private readonly ArtistLiteRowFixture _artistLiteRowFixture = new();
private readonly GetArtistsLiteQueryFixture _getArtistsLiteQueryFixture = new();
private readonly PaginatedResultDtoFixture<ArtistLiteRow> _paginatedResultDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsLiteQueryHandlerTests"/> class.
/// </summary>
public GetArtistsLiteQueryHandlerTests()
{
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetArtistsLiteQuery>>();
_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<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetArtistsLiteQuery>()).Returns([]);
_sut = new GetArtistsLiteQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenPolicyAllowsAccess_ShouldReturnMappedPaginatedResponses()
{
// Arrange
GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create();
List<ArtistLiteRow> artistLiteRows = _artistLiteRowFixture.CreateMany(2);
PaginatedResultDto<ArtistLiteRow> paginatedArtists = _paginatedResultDtoFixture.Create(data: artistLiteRows, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1);
_mockArtistRepository.GetAllLiteAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedArtists));
// Act
Result<PaginatedResponse<ArtistLiteResponse>> 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<ArtistLiteRow> paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
_mockArtistRepository.GetAllLiteAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedArtists));
// Act
Result<PaginatedResponse<ArtistLiteResponse>> 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<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.FilterMustIncludeLibraryId);
// Act
Result<PaginatedResponse<ArtistLiteResponse>> 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<ArtistLiteRow> paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
_mockArtistRepository.GetAllLiteAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedArtists));
// Act
await _sut.HandleAsync(query, cancellationToken);
// Assert
await _mockArtistRepository.Received(1).GetAllLiteAsync(
Arg.Is<PaginationDataDto>(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && paginationData.PerPage == query.PaginationData.PerPage),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Is<LibraryFilterDto>(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<ArtistLiteRow> paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
_mockArtistRepository.GetAllLiteAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedArtists));
// Act
await _sut.HandleAsync(query, CancellationToken.None);
// Assert
await _mockArtistRepository.Received(1).GetAllLiteAsync(
Arg.Is<PaginationDataDto?>(paginationData => paginationData == null),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == libraryId && filter.SearchTerm == "Queen"),
cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(libraryId: libraryId.ToString());
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<PaginatedResponse<ArtistLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().GetAllLiteAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<PaginatedResponse<ArtistLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().GetAllLiteAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
{
// Arrange
GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetArtistsLiteQuery>()).Returns([Errors.Library.LibraryIdCannotBeEmpty]);
// Act
Result<PaginatedResponse<ArtistLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().GetAllLiteAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), cancellationToken: Arg.Any<CancellationToken>());
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistsLiteQueryValidator"/> class.
/// </summary>
[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<Error> 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<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="ArtistConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtistConfigurationTests : IDisposable
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="ArtistConfigurationTests"/> class.
/// </summary>
public ArtistConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().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<IProperty> 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<IForeignKey> 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<IIndex> 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);
}
/// <summary>
/// Disposes the database context.
/// </summary>
public void Dispose()
{
_context.Dispose();
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="ArtistSearchSpecification"/> class.
/// </summary>
[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<ArtistEntity> 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<ArtistEntity> matchingArtists = artists.AsQueryable().Where(specification.ToExpression());
// Assert
Assert.Equal(2, matchingArtists.Count());
Assert.DoesNotContain(matchingArtists, artist => artist.Name == "Radiohead");
}
}
@@ -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<MusicMediaContributor> contributors = [_musicMediaContributorFixture.Create()];
Album album = _albumFixture.Create();
DateTime beforeCreate = DateTime.UtcNow;
// Act
Result<Artist> result = Artist.Create(
libraryId,
"Queen",
Optional<string>.Some("https://www.queenonline.com"),
Optional<MusicBrainzId>.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<string>.Some("https://www.queenonline.com"), artist.Website);
Assert.Equal(Optional<MusicBrainzId>.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<Artist> result = Artist.Create(
libraryId,
"Queen",
Optional<string>.None(),
Optional<MusicBrainzId>.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<Artist> result = Artist.Create(
_libraryIdFixture.Create(),
name!,
Optional<string>.None(),
Optional<MusicBrainzId>.None(),
[],
[_albumFixture.Create()]);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError);
}
[Fact]
public void Create_WhenAlbumsListIsEmpty_ShouldReturnArtistMustHaveAtLeastOneAlbumError()
{
// Act
Result<Artist> result = Artist.Create(
_libraryIdFixture.Create(),
"Queen",
Optional<string>.None(),
Optional<MusicBrainzId>.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<Artist> result = Artist.Create(
artistId,
libraryId,
"Queen",
Optional<string>.Some("https://www.queenonline.com"),
Optional<MusicBrainzId>.None(),
[],
[album],
createdOnUtc,
Optional<DateTime>.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<string>.Some("https://www.queenonline.com"), artist.Website);
Assert.Equal(createdOnUtc, artist.CreatedOnUtc);
Assert.Equal(Optional<DateTime>.Some(updatedOnUtc), artist.UpdatedOnUtc);
}
[Theory]
[InlineData(null)] // null name
[InlineData("")] // empty name
[InlineData(" ")] // whitespace name
public void CreateWithId_WhenNameIsNullOrWhitespace_ShouldReturnArtistNameCannotBeEmptyError(string? name)
{
// Act
Result<Artist> result = Artist.Create(
_artistIdFixture.Create(),
_libraryIdFixture.Create(),
name!,
Optional<string>.None(),
Optional<MusicBrainzId>.None(),
[],
[_albumFixture.Create()],
DateTime.UtcNow,
Optional<DateTime>.None());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError);
}
[Fact]
public void CreateWithId_WhenAlbumsListIsEmpty_ShouldReturnArtistMustHaveAtLeastOneAlbumError()
{
// Act
Result<Artist> result = Artist.Create(
_artistIdFixture.Create(),
_libraryIdFixture.Create(),
"Queen",
Optional<string>.None(),
Optional<MusicBrainzId>.None(),
[],
[],
DateTime.UtcNow,
Optional<DateTime>.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<Created> 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<Created> 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<Deleted> 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<Deleted> 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<Deleted> 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<Updated> result = artist.UpdateDetails(
"Queen",
Optional<string>.Some("https://www.queenonline.com"),
Optional<MusicBrainzId>.Some(musicBrainzArtistId));
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Queen", artist.Name);
Assert.Equal(Optional<string>.Some("https://www.queenonline.com"), artist.Website);
Assert.Equal(Optional<MusicBrainzId>.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<DateTime> originalUpdatedOnUtc = artist.UpdatedOnUtc;
// Act
Result<Updated> result = artist.UpdateDetails(" ", Optional<string>.None(), Optional<MusicBrainzId>.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<MusicMediaFormat> mediaFormat = Optional<MusicMediaFormat>.Some(MusicMediaFormat.CD);
Optional<Barcode> barcode = Optional<Barcode>.Some(_barcodeFixture.Create());
Optional<string> catalogNumber = Optional<string>.Some("CAT-123456");
Optional<MusicBrainzId> releaseId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
Optional<MusicBrainzId> releaseGroupId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
Optional<MusicBrainzId> releaseArtistId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
List<MusicMediaContributor> contributors = [_musicMediaContributorFixture.Create()];
List<AudioRating> ratings = [_audioRatingFixture.Create()];
DateTime beforeUpdate = DateTime.UtcNow;
// Act
Result<Updated> 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<DateTime> originalUpdatedOnUtc = artist.UpdatedOnUtc;
// Act
Result<Updated> result = artist.UpdateAlbum(
foreignAlbum,
_albumMetadataFixture.Create(),
Optional<MusicMediaFormat>.None(),
Optional<Barcode>.None(),
Optional<string>.None(),
Optional<MusicBrainzId>.None(),
Optional<MusicBrainzId>.None(),
Optional<MusicBrainzId>.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<int> discNumber = Optional<int>.Some(1);
Optional<string> script = Optional<string>.Some("Latin");
Optional<MusicKey> key = Optional<MusicKey>.Some(MusicKey.BMajor);
Optional<int> bpm = Optional<int>.Some(72);
Optional<string> work = Optional<string>.Some("Bohemian Rhapsody");
Optional<MusicBrainzId> recordingId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
Optional<MusicBrainzId> musicBrainzTrackId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
Optional<MusicBrainzId> workId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
List<Mood> moods = [_moodFixture.Create(name: "epic")];
List<Isrc> isrcs = [_isrcFixture.Create(value: "GBUM71029604")];
List<MusicMediaContributor> contributors = [_musicMediaContributorFixture.Create()];
List<AudioRating> ratings = [_audioRatingFixture.Create()];
DateTime beforeUpdate = DateTime.UtcNow;
// Act
Result<Updated> 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<DateTime> originalUpdatedOnUtc = artist.UpdatedOnUtc;
// Act
Result<Updated> result = artist.UpdateTrackInAlbum(
foreignAlbum,
track,
"C:\\Music\\queen\\bohemian-rhapsody.flac",
_audioMetadataFixture.Create(),
11,
Optional<int>.None(),
Optional<string>.None(),
Optional<MusicKey>.None(),
Optional<int>.None(),
Optional<string>.None(),
Optional<MusicBrainzId>.None(),
Optional<MusicBrainzId>.None(),
Optional<MusicBrainzId>.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<DateTime> originalUpdatedOnUtc = artist.UpdatedOnUtc;
// Act
Result<Updated> result = artist.UpdateTrackInAlbum(
album,
track,
"C:\\Music\\queen\\bohemian-rhapsody.flac",
_audioMetadataFixture.Create(),
11,
Optional<int>.None(),
Optional<string>.None(),
Optional<MusicKey>.None(),
Optional<int>.None(),
Optional<string>.None(),
Optional<MusicBrainzId>.None(),
Optional<MusicBrainzId>.None(),
Optional<MusicBrainzId>.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<Deleted> 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<Deleted> 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<Deleted> result = artist.RemoveTrackFromAlbum(album, track);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
Assert.Empty(album.Tracks);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="ArtistId"/> class.
/// </summary>
[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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="AddArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddArtistEndpointTests
{
private readonly ICommandHandler<AddArtistCommand, Result<ArtistResponse>> _mockHandler;
private readonly AddArtistEndpoint _sut;
private readonly AddArtistRequestFixture _addArtistRequestFixture = new();
private readonly ArtistResponseFixture _artistResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="AddArtistEndpointTests"/> class.
/// </summary>
public AddArtistEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<AddArtistCommand, Result<ArtistResponse>>>();
_sut = FastEndpoints.Factory.Create<AddArtistEndpoint>(_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<AddArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Created<ArtistResponse> createdResult = Assert.IsType<Created<ArtistResponse>>(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<AddArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(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<AddArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(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<AddArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(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<AddArtistCommand>(), Arg.Any<CancellationToken>())
.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<AddArtistCommand>(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<AddArtistCommand>(), Arg.Any<CancellationToken>())
.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<AddArtistCommand>(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<AddArtistCommand>(), Arg.Any<CancellationToken>())
.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<AddArtistCommand>(command => command.LibraryId == null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
AddArtistRequest request = _addArtistRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<AddArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_artistResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="DeleteArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteArtistEndpointTests
{
private readonly ICommandHandler<DeleteArtistCommand, Result<Deleted>> _mockHandler;
private readonly DeleteArtistEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteArtistEndpointTests"/> class.
/// </summary>
public DeleteArtistEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<DeleteArtistCommand, Result<Deleted>>>();
_sut = FastEndpoints.Factory.Create<DeleteArtistEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<DeleteArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<Deleted> okResult = Assert.IsType<Ok<Deleted>>(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<DeleteArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(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<DeleteArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(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<DeleteArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(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<DeleteArtistCommand>(), Arg.Any<CancellationToken>())
.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<DeleteArtistCommand>(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<DeleteArtistCommand>(), Arg.Any<CancellationToken>())
.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<DeleteArtistCommand>(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<DeleteArtistCommand>(), Arg.Any<CancellationToken>())
.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<DeleteArtistCommand>(command =>
command.LibraryId == null &&
command.ArtistId == null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<DeleteArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Deleted);
}, callInfo.Arg<CancellationToken>()));
ConfigureRouteValues();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Populates the route values read by the endpoint.
/// </summary>
private void ConfigureRouteValues()
{
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString();
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistEndpointTests
{
private readonly IQueryHandler<GetArtistQuery, Result<ArtistResponse>> _mockHandler;
private readonly GetArtistEndpoint _sut;
private readonly ArtistResponseFixture _artistResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistEndpointTests"/> class.
/// </summary>
public GetArtistEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetArtistQuery, Result<ArtistResponse>>>();
_sut = FastEndpoints.Factory.Create<GetArtistEndpoint>(_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<GetArtistQuery>(), Arg.Any<CancellationToken>())
.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<ArtistResponse> okResult = Assert.IsType<Ok<ArtistResponse>>(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<GetArtistQuery>(), Arg.Any<CancellationToken>())
.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<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(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<GetArtistQuery>(), Arg.Any<CancellationToken>())
.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<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(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<GetArtistQuery>(), Arg.Any<CancellationToken>())
.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<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(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<GetArtistQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistQuery>(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<GetArtistQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistQuery>(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<GetArtistQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistQuery>(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<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetArtistQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_artistResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistAlbumsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistAlbumsEndpointTests
{
private readonly IQueryHandler<GetArtistAlbumsQuery, Result<IReadOnlyList<AlbumResponse>>> _mockHandler;
private readonly GetArtistAlbumsEndpoint _sut;
private readonly AlbumResponseFixture _albumResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsEndpointTests"/> class.
/// </summary>
public GetArtistAlbumsEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetArtistAlbumsQuery, Result<IReadOnlyList<AlbumResponse>>>>();
_sut = FastEndpoints.Factory.Create<GetArtistAlbumsEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithAlbumResponses()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
IReadOnlyList<AlbumResponse> expectedResponse = _albumResponseFixture.CreateMany(2);
_mockHandler.HandleAsync(Arg.Any<GetArtistAlbumsQuery>(), Arg.Any<CancellationToken>())
.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<IReadOnlyList<AlbumResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<AlbumResponse>>>(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<GetArtistAlbumsQuery>(), Arg.Any<CancellationToken>())
.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<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(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<GetArtistAlbumsQuery>(), Arg.Any<CancellationToken>())
.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<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(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<GetArtistAlbumsQuery>(), Arg.Any<CancellationToken>())
.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<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(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<GetArtistAlbumsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From((IReadOnlyList<AlbumResponse>)_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<GetArtistAlbumsQuery>(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<GetArtistAlbumsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From((IReadOnlyList<AlbumResponse>)_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<GetArtistAlbumsQuery>(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<GetArtistAlbumsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From((IReadOnlyList<AlbumResponse>)_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<GetArtistAlbumsQuery>(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<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetArtistAlbumsQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From((IReadOnlyList<AlbumResponse>)_albumResponseFixture.CreateMany(1));
}, callInfo.Arg<CancellationToken>()));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistAlbumsLiteEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistAlbumsLiteEndpointTests
{
private readonly IQueryHandler<GetArtistAlbumsLiteQuery, Result<PaginatedResponse<AlbumLiteResponse>>> _mockHandler;
private readonly GetArtistAlbumsLiteEndpoint _sut;
private readonly GetArtistAlbumsLiteRequestFixture _getArtistAlbumsLiteRequestFixture = new();
private readonly AlbumLiteResponseFixture _albumLiteResponseFixture = new();
private readonly PaginatedResponseFixture<AlbumLiteResponse> _paginatedResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsLiteEndpointTests"/> class.
/// </summary>
public GetArtistAlbumsLiteEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetArtistAlbumsLiteQuery, Result<PaginatedResponse<AlbumLiteResponse>>>>();
_sut = FastEndpoints.Factory.Create<GetArtistAlbumsLiteEndpoint>(_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<AlbumLiteResponse> expectedResponse = CreatePaginatedResponse(albumCount: 2);
_mockHandler.HandleAsync(Arg.Any<GetArtistAlbumsLiteQuery>(), Arg.Any<CancellationToken>())
.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<PaginatedResponse<AlbumLiteResponse>> okResult = Assert.IsType<Ok<PaginatedResponse<AlbumLiteResponse>>>(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<GetArtistAlbumsLiteQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(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<GetArtistAlbumsLiteQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(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<GetArtistAlbumsLiteQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistAlbumsLiteQuery>(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<GetArtistAlbumsLiteQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistAlbumsLiteQuery>(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<GetArtistAlbumsLiteQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistAlbumsLiteQuery>(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<GetArtistAlbumsLiteQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistAlbumsLiteQuery>(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<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetArtistAlbumsLiteQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(CreatePaginatedResponse(albumCount: 0));
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Creates a <see cref="PaginatedResponse{AlbumLiteResponse}"/> with the specified number of albums.
/// </summary>
/// <param name="albumCount">The number of album responses to include in the data collection.</param>
/// <returns>A configured paginated response instance.</returns>
private PaginatedResponse<AlbumLiteResponse> CreatePaginatedResponse(int albumCount)
{
List<AlbumLiteResponse> 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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsEndpointTests
{
private readonly IQueryHandler<GetArtistsQuery, Result<PaginatedResponse<ArtistResponse>>> _mockHandler;
private readonly GetArtistsEndpoint _sut;
private readonly GetArtistsRequestFixture _getArtistsRequestFixture = new();
private readonly ArtistResponseFixture _artistResponseFixture = new();
private readonly PaginatedResponseFixture<ArtistResponse> _paginatedResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsEndpointTests"/> class.
/// </summary>
public GetArtistsEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetArtistsQuery, Result<PaginatedResponse<ArtistResponse>>>>();
_sut = FastEndpoints.Factory.Create<GetArtistsEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedArtistResponses()
{
// Arrange
Guid libraryId = Guid.NewGuid();
GetArtistsRequest request = _getArtistsRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
PaginatedResponse<ArtistResponse> expectedResponse = CreatePaginatedResponse(artistCount: 2);
_mockHandler.HandleAsync(Arg.Any<GetArtistsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<PaginatedResponse<ArtistResponse>> okResult = Assert.IsType<Ok<PaginatedResponse<ArtistResponse>>>(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<GetArtistsQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(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<GetArtistsQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(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<GetArtistsQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistsQuery>(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<GetArtistsQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistsQuery>(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<GetArtistsQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistsQuery>(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<GetArtistsQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistsQuery>(query => query.LibraryId == null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetArtistsRequest request = _getArtistsRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetArtistsQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(CreatePaginatedResponse(artistCount: 0));
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Creates a <see cref="PaginatedResponse{ArtistResponse}"/> with the specified number of artists.
/// </summary>
/// <param name="artistCount">The number of artist responses to include in the data collection.</param>
/// <returns>A configured paginated response instance.</returns>
private PaginatedResponse<ArtistResponse> CreatePaginatedResponse(int artistCount)
{
List<ArtistResponse> 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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetArtistsLiteEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsLiteEndpointTests
{
private readonly IQueryHandler<GetArtistsLiteQuery, Result<PaginatedResponse<ArtistLiteResponse>>> _mockHandler;
private readonly GetArtistsLiteEndpoint _sut;
private readonly GetArtistsLiteRequestFixture _getArtistsLiteRequestFixture = new();
private readonly ArtistLiteResponseFixture _artistLiteResponseFixture = new();
private readonly PaginatedResponseFixture<ArtistLiteResponse> _paginatedResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsLiteEndpointTests"/> class.
/// </summary>
public GetArtistsLiteEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetArtistsLiteQuery, Result<PaginatedResponse<ArtistLiteResponse>>>>();
_sut = FastEndpoints.Factory.Create<GetArtistsLiteEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedArtistLiteResponses()
{
// Arrange
Guid libraryId = Guid.NewGuid();
GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
PaginatedResponse<ArtistLiteResponse> expectedResponse = CreatePaginatedResponse(artistCount: 2);
_mockHandler.HandleAsync(Arg.Any<GetArtistsLiteQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<PaginatedResponse<ArtistLiteResponse>> okResult = Assert.IsType<Ok<PaginatedResponse<ArtistLiteResponse>>>(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<GetArtistsLiteQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(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<GetArtistsLiteQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(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<GetArtistsLiteQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistsLiteQuery>(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<GetArtistsLiteQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistsLiteQuery>(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<GetArtistsLiteQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistsLiteQuery>(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<GetArtistsLiteQuery>(), Arg.Any<CancellationToken>())
.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<GetArtistsLiteQuery>(query => query.LibraryId == null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetArtistsLiteQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(CreatePaginatedResponse(artistCount: 0));
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Creates a <see cref="PaginatedResponse{ArtistLiteResponse}"/> with the specified number of artists.
/// </summary>
/// <param name="artistCount">The number of artist responses to include in the data collection.</param>
/// <returns>A configured paginated response instance.</returns>
private PaginatedResponse<ArtistLiteResponse> CreatePaginatedResponse(int artistCount)
{
List<ArtistLiteResponse> 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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="UpdateArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistEndpointTests
{
private readonly ICommandHandler<UpdateArtistCommand, Result<ArtistResponse>> _mockHandler;
private readonly UpdateArtistEndpoint _sut;
private readonly UpdateArtistRequestFixture _updateArtistRequestFixture = new();
private readonly ArtistResponseFixture _artistResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistEndpointTests"/> class.
/// </summary>
public UpdateArtistEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<UpdateArtistCommand, Result<ArtistResponse>>>();
_sut = FastEndpoints.Factory.Create<UpdateArtistEndpoint>(_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<UpdateArtistCommand>(), Arg.Any<CancellationToken>())
.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<ArtistResponse> okResult = Assert.IsType<Ok<ArtistResponse>>(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<UpdateArtistCommand>(), Arg.Any<CancellationToken>())
.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<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(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<UpdateArtistCommand>(), Arg.Any<CancellationToken>())
.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<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(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<UpdateArtistCommand>(), Arg.Any<CancellationToken>())
.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<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(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<UpdateArtistCommand>(), Arg.Any<CancellationToken>())
.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<UpdateArtistCommand>(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<UpdateArtistCommand>(), Arg.Any<CancellationToken>())
.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<UpdateArtistCommand>(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<UpdateArtistCommand>(), Arg.Any<CancellationToken>())
.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<UpdateArtistCommand>(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<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<UpdateArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_artistResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}