mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds the music library album test suite
This commit is contained in:
1 parent
ffe79221fe
commit
5d3e430dd1
57 files changed
+16761
-24
No files matched your search
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AlbumLiteRow"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumLiteRowFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="AlbumLiteRow"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the album.</param>
|
||||
/// <param name="title">Optional. The title of the album.</param>
|
||||
/// <param name="totalTracks">Optional. The number of tracks of the release.</param>
|
||||
/// <returns>The created <see cref="AlbumLiteRow"/>.</returns>
|
||||
public AlbumLiteRow Create(
|
||||
Guid? id = null,
|
||||
string? title = null,
|
||||
int? totalTracks = null)
|
||||
{
|
||||
return new AlbumLiteRow
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
Title = title ?? _faker.Music.Genre(),
|
||||
TotalTracks = totalTracks ?? _faker.Random.Int(1, 30)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AlbumLiteRow"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="AlbumLiteRow"/> instances.</returns>
|
||||
public List<AlbumLiteRow> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+79
-24
@@ -20,7 +20,6 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Au
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumEntityFixture
|
||||
{
|
||||
private readonly Random _random = new();
|
||||
private readonly Faker _faker = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
@@ -36,18 +35,46 @@ public class AlbumEntityFixture
|
||||
/// <param name="libraryId">Optional. The Id of the media library that owns the album.</param>
|
||||
/// <param name="title">Optional. The title of the album.</param>
|
||||
/// <param name="tracks">Optional. The tracks of the album.</param>
|
||||
/// <param name="includeTracks">Whether the album should own a generated track, or no track at all.</param>
|
||||
/// <param name="includeMetadata">Whether the owned metadata collections (Tags, Genres, Contributors, Ratings) should be included, or forced to empty collections.</param>
|
||||
/// <param name="originalReleaseDate">Optional. The original release date of the album.</param>
|
||||
/// <param name="originalReleaseYear">Optional. The original release year of the album.</param>
|
||||
/// <param name="reReleaseDate">Optional. The re-release date of the album.</param>
|
||||
/// <param name="reReleaseYear">Optional. The re-release year of the album.</param>
|
||||
/// <param name="barcode">Optional. The barcode of the album.</param>
|
||||
/// <param name="originalTitle">Optional. The original title of the album.</param>
|
||||
/// <param name="description">Optional. A brief description or summary of the album.</param>
|
||||
/// <param name="languageCode">Optional. The language code of the album.</param>
|
||||
/// <param name="languageName">Optional. The language name of the album.</param>
|
||||
/// <param name="languageNativeName">Optional. The language native name of the album.</param>
|
||||
/// <param name="originalLanguageCode">Optional. The original language code of the album.</param>
|
||||
/// <param name="originalLanguageName">Optional. The original language name of the album.</param>
|
||||
/// <param name="originalLanguageNativeName">Optional. The original language native name of the album.</param>
|
||||
/// <param name="releaseType">Optional. The release type of the album.</param>
|
||||
/// <param name="releaseStatus">Optional. The release status of the album.</param>
|
||||
/// <param name="totalDiscs">Optional. The total number of discs of the album.</param>
|
||||
/// <param name="mediaFormat">Optional. The media format of the album.</param>
|
||||
/// <param name="catalogNumber">Optional. The catalog number of the album.</param>
|
||||
/// <param name="musicBrainzReleaseId">Optional. The MusicBrainz release identifier of the album.</param>
|
||||
/// <param name="musicBrainzReleaseGroupId">Optional. The MusicBrainz release group identifier of the album.</param>
|
||||
/// <param name="musicBrainzReleaseArtistId">Optional. The MusicBrainz release artist identifier of the album.</param>
|
||||
/// <param name="includeTracks">Whether the album should own a generated track, or no track at all.</param>
|
||||
/// <param name="includeMetadata">Whether the owned metadata collections (Tags, Genres, Contributors, Ratings) should be included, or forced to empty collections.</param>
|
||||
/// <param name="includeOriginalReleaseDate">Whether the original release date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeOriginalReleaseYear">Whether the original release year should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReReleaseDate">Whether the re-release date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReReleaseYear">Whether the re-release year 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="includeOriginalTitle">Whether the original title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLanguage">Whether the language of the album should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeOriginalLanguage">Whether the original language of the album should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReleaseType">Whether the release type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReleaseStatus">Whether the release status should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTotalDiscs">Whether the total number of discs 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="includeCatalogNumber">Whether the catalog number should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzReleaseId">Whether the MusicBrainz release identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzReleaseGroupId">Whether the MusicBrainz release group identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzReleaseArtistId">Whether the MusicBrainz release artist identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="AlbumEntity"/>.</returns>
|
||||
public AlbumEntity Create(
|
||||
Guid? id = null,
|
||||
@@ -55,26 +82,54 @@ public class AlbumEntityFixture
|
||||
Guid? libraryId = null,
|
||||
string? title = null,
|
||||
List<TrackEntity>? tracks = null,
|
||||
bool includeTracks = true,
|
||||
bool includeMetadata = true,
|
||||
DateOnly? originalReleaseDate = null,
|
||||
int? originalReleaseYear = null,
|
||||
DateOnly? reReleaseDate = null,
|
||||
int? reReleaseYear = null,
|
||||
string? barcode = null,
|
||||
string? originalTitle = null,
|
||||
string? description = null,
|
||||
string? languageCode = null,
|
||||
string? languageName = null,
|
||||
string? languageNativeName = null,
|
||||
string? originalLanguageCode = null,
|
||||
string? originalLanguageName = null,
|
||||
string? originalLanguageNativeName = null,
|
||||
MusicReleaseType? releaseType = null,
|
||||
MusicReleaseStatus? releaseStatus = null,
|
||||
int? totalDiscs = null,
|
||||
MusicMediaFormat? mediaFormat = null,
|
||||
string? catalogNumber = null,
|
||||
Guid? musicBrainzReleaseId = null,
|
||||
Guid? musicBrainzReleaseGroupId = null,
|
||||
Guid? musicBrainzReleaseArtistId = null,
|
||||
bool includeTracks = true,
|
||||
bool includeMetadata = true,
|
||||
bool includeOriginalReleaseDate = true,
|
||||
bool includeOriginalReleaseYear = true,
|
||||
bool includeReReleaseDate = true,
|
||||
bool includeReReleaseYear = true,
|
||||
bool includeBarcode = true)
|
||||
bool includeBarcode = true,
|
||||
bool includeOriginalTitle = true,
|
||||
bool includeDescription = true,
|
||||
bool includeLanguage = true,
|
||||
bool includeOriginalLanguage = true,
|
||||
bool includeReleaseType = true,
|
||||
bool includeReleaseStatus = true,
|
||||
bool includeTotalDiscs = true,
|
||||
bool includeMediaFormat = true,
|
||||
bool includeCatalogNumber = true,
|
||||
bool includeMusicBrainzReleaseId = true,
|
||||
bool includeMusicBrainzReleaseGroupId = true,
|
||||
bool includeMusicBrainzReleaseArtistId = true)
|
||||
{
|
||||
Guid resolvedId = id ?? Guid.NewGuid();
|
||||
Guid resolvedArtistId = artistId ?? Guid.NewGuid();
|
||||
Guid resolvedLibraryId = libraryId ?? Guid.NewGuid();
|
||||
const int MAXIMUM_RELEASE_YEAR = 2026;
|
||||
int resolvedOriginalReleaseYear = originalReleaseYear ?? _random.Next(1900, MAXIMUM_RELEASE_YEAR);
|
||||
int resolvedOriginalReleaseYear = originalReleaseYear ?? Random.Shared.Next(1900, MAXIMUM_RELEASE_YEAR);
|
||||
int resolvedReReleaseYearUpperBound = Math.Max(resolvedOriginalReleaseYear + 1, MAXIMUM_RELEASE_YEAR);
|
||||
int resolvedReReleaseYear = reReleaseYear ?? _random.Next(resolvedOriginalReleaseYear, resolvedReReleaseYearUpperBound);
|
||||
int resolvedReReleaseYear = reReleaseYear ?? Random.Shared.Next(resolvedOriginalReleaseYear, resolvedReReleaseYearUpperBound);
|
||||
DateOnly resolvedOriginalReleaseDate = originalReleaseDate ?? _faker.DateOnlyBetween(new DateOnly(resolvedOriginalReleaseYear, 1, 1), new DateOnly(resolvedOriginalReleaseYear, 12, 31));
|
||||
DateOnly resolvedReReleaseDate = reReleaseDate ?? _faker.DateOnlyBetween(resolvedReReleaseYear == resolvedOriginalReleaseYear ? resolvedOriginalReleaseDate : new DateOnly(resolvedReReleaseYear, 1, 1), new DateOnly(resolvedReReleaseYear, 12, 31));
|
||||
List<TrackEntity> resolvedTracks = tracks ?? (includeTracks ? [_trackEntityFixture.Create(albumId: resolvedId, libraryId: resolvedLibraryId, includeMetadata: includeMetadata, includeOriginalReleaseDate: includeOriginalReleaseDate, includeOriginalReleaseYear: includeOriginalReleaseYear, includeReReleaseDate: includeReReleaseDate, includeReReleaseYear: includeReReleaseYear)] : []);
|
||||
@@ -91,30 +146,30 @@ public class AlbumEntityFixture
|
||||
UpdatedBy = null
|
||||
})
|
||||
.RuleFor(x => x.Title, f => title ?? f.Random.String2(f.Random.Number(1, 255)))
|
||||
.RuleFor(x => x.OriginalTitle, f => f.Random.String2(f.Random.Number(1, 255)))
|
||||
.RuleFor(x => x.Description, f => f.Random.String2(f.Random.Number(1, 2000)))
|
||||
.RuleFor(x => x.OriginalTitle, f => includeOriginalTitle ? (originalTitle ?? f.Random.String2(f.Random.Number(1, 255))) : null)
|
||||
.RuleFor(x => x.Description, f => includeDescription ? (description ?? f.Random.String2(f.Random.Number(1, 2000))) : null)
|
||||
.RuleFor(x => x.OriginalReleaseDate, includeOriginalReleaseDate ? resolvedOriginalReleaseDate : (DateOnly?)null)
|
||||
.RuleFor(x => x.OriginalReleaseYear, includeOriginalReleaseYear ? resolvedOriginalReleaseYear : (int?)null)
|
||||
.RuleFor(x => x.ReReleaseDate, includeReReleaseDate ? resolvedReReleaseDate : (DateOnly?)null)
|
||||
.RuleFor(x => x.ReReleaseYear, includeReReleaseYear ? resolvedReReleaseYear : (int?)null)
|
||||
.RuleFor(x => x.ReleaseCountry, f => f.PickRandom<ReleaseCountry>())
|
||||
.RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.LanguageCode, f => f.Random.String2(2))
|
||||
.RuleFor(x => x.LanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.LanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.OriginalLanguageCode, f => f.Random.String2(2))
|
||||
.RuleFor(x => x.OriginalLanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.OriginalLanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.ReleaseType, f => f.PickRandom<MusicReleaseType>())
|
||||
.RuleFor(x => x.ReleaseStatus, f => f.PickRandom<MusicReleaseStatus>())
|
||||
.RuleFor(x => x.TotalDiscs, _random.Next(1, 3))
|
||||
.RuleFor(x => x.LanguageCode, f => includeLanguage ? (languageCode ?? f.Random.String2(2)) : null)
|
||||
.RuleFor(x => x.LanguageName, f => includeLanguage ? (languageName ?? f.Random.String2(f.Random.Number(1, 50))) : null)
|
||||
.RuleFor(x => x.LanguageNativeName, f => includeLanguage ? (languageNativeName ?? f.Random.String2(f.Random.Number(1, 50))) : null)
|
||||
.RuleFor(x => x.OriginalLanguageCode, f => includeOriginalLanguage ? (originalLanguageCode ?? f.Random.String2(2)) : null)
|
||||
.RuleFor(x => x.OriginalLanguageName, f => includeOriginalLanguage ? (originalLanguageName ?? f.Random.String2(f.Random.Number(1, 50))) : null)
|
||||
.RuleFor(x => x.OriginalLanguageNativeName, f => includeOriginalLanguage ? (originalLanguageNativeName ?? f.Random.String2(f.Random.Number(1, 50))) : null)
|
||||
.RuleFor(x => x.ReleaseType, f => includeReleaseType ? (releaseType ?? f.PickRandom<MusicReleaseType>()) : (MusicReleaseType?)null)
|
||||
.RuleFor(x => x.ReleaseStatus, f => includeReleaseStatus ? (releaseStatus ?? f.PickRandom<MusicReleaseStatus>()) : (MusicReleaseStatus?)null)
|
||||
.RuleFor(x => x.TotalDiscs, includeTotalDiscs ? (totalDiscs ?? Random.Shared.Next(1, 3)) : (int?)null)
|
||||
.RuleFor(x => x.TotalTracks, resolvedTracks.Count)
|
||||
.RuleFor(x => x.MediaFormat, f => f.PickRandom<MusicMediaFormat>())
|
||||
.RuleFor(x => x.MediaFormat, f => includeMediaFormat ? (mediaFormat ?? f.PickRandom<MusicMediaFormat>()) : (MusicMediaFormat?)null)
|
||||
.RuleFor(x => x.Barcode, f => includeBarcode ? (barcode ?? f.Random.String2(f.Random.Number(12, 13), "0123456789")) : null)
|
||||
.RuleFor(x => x.CatalogNumber, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.MusicBrainzReleaseId, f => f.Random.Guid())
|
||||
.RuleFor(x => x.MusicBrainzReleaseGroupId, f => f.Random.Guid())
|
||||
.RuleFor(x => x.MusicBrainzReleaseArtistId, f => f.Random.Guid())
|
||||
.RuleFor(x => x.CatalogNumber, f => includeCatalogNumber ? (catalogNumber ?? f.Random.String2(f.Random.Number(1, 50))) : null)
|
||||
.RuleFor(x => x.MusicBrainzReleaseId, f => includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? f.Random.Guid()) : (Guid?)null)
|
||||
.RuleFor(x => x.MusicBrainzReleaseGroupId, f => includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? f.Random.Guid()) : (Guid?)null)
|
||||
.RuleFor(x => x.MusicBrainzReleaseArtistId, f => includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? f.Random.Guid()) : (Guid?)null)
|
||||
.RuleFor(x => x.Tags, f => includeMetadata ? [.. _tagEntityFixture.CreateMany(f.Random.Number(1, 3))] : [])
|
||||
.RuleFor(x => x.Genres, f => includeMetadata ? [.. _genreEntityFixture.CreateMany(f.Random.Number(1, 3))] : [])
|
||||
.RuleFor(x => x.Contributors, f => includeMetadata ? _albumContributorEntityFixture.CreateMany(f.Random.Number(1, 3), albumId: resolvedId) : [])
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AddAlbumCommand"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddAlbumCommandFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
private readonly AddTrackCommandFixture _addTrackCommandFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid command to add an album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the album belongs to, taken from the route.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the album belongs to, taken from the route.</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="albumId">Optional. The Id of the album, when it already exists.</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="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 should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeRatings">Whether the ratings should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTracks">Whether the tracks should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created command to add an album.</returns>
|
||||
public AddAlbumCommand Create(
|
||||
string? libraryId = null,
|
||||
string? artistId = null,
|
||||
AlbumMetadataDto? metadata = null,
|
||||
MusicMediaFormat? mediaFormat = null,
|
||||
string? barcode = null,
|
||||
string? catalogNumber = null,
|
||||
Guid? musicBrainzReleaseId = null,
|
||||
Guid? musicBrainzReleaseGroupId = null,
|
||||
Guid? musicBrainzReleaseArtistId = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
List<AddTrackCommand>? tracks = null,
|
||||
Guid? albumId = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeArtistId = true,
|
||||
bool includeMetadata = true,
|
||||
bool includeMediaFormat = true,
|
||||
bool includeBarcode = true,
|
||||
bool includeCatalogNumber = true,
|
||||
bool includeMusicBrainzReleaseId = true,
|
||||
bool includeMusicBrainzReleaseGroupId = true,
|
||||
bool includeMusicBrainzReleaseArtistId = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true,
|
||||
bool includeTracks = true,
|
||||
bool includeAlbumId = true)
|
||||
{
|
||||
string? resolvedLibraryId = includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null;
|
||||
string? resolvedArtistId = includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null;
|
||||
|
||||
return new AddAlbumCommand(
|
||||
resolvedLibraryId,
|
||||
resolvedArtistId,
|
||||
includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null,
|
||||
includeMediaFormat ? (mediaFormat ?? _faker.PickRandom<MusicMediaFormat>()) : null,
|
||||
includeBarcode ? (barcode ?? _faker.Random.String2(_faker.Random.Int(12, 13), "0123456789")) : null,
|
||||
includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(_faker.Random.Int(1, 50))) : null,
|
||||
includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null,
|
||||
includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null,
|
||||
includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null,
|
||||
includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
|
||||
includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
|
||||
includeTracks ? (tracks ?? GenerateTracks(resolvedLibraryId, resolvedArtistId)) : null,
|
||||
includeAlbumId ? (albumId ?? _faker.Random.Guid()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AddAlbumCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<AddAlbumCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates the tracks of the album, tied to the album's library and artist identifiers.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the tracks belong to.</param>
|
||||
/// <param name="artistId">The Id of the artist the tracks belong to.</param>
|
||||
/// <returns>The generated tracks.</returns>
|
||||
private List<AddTrackCommand> GenerateTracks(string? libraryId, string? artistId)
|
||||
{
|
||||
return [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _addTrackCommandFixture.Create(libraryId: libraryId, artistId: artistId))];
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="DeleteAlbumCommand"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteAlbumCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="DeleteAlbumCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the album belongs to, taken from the route.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the album belongs to, taken from the route.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album 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>
|
||||
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="DeleteAlbumCommand"/>.</returns>
|
||||
public DeleteAlbumCommand Create(
|
||||
string? libraryId = null,
|
||||
string? artistId = null,
|
||||
string? albumId = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeArtistId = true,
|
||||
bool includeAlbumId = true)
|
||||
{
|
||||
return new DeleteAlbumCommand(
|
||||
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="DeleteAlbumCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="DeleteAlbumCommand"/> instances.</returns>
|
||||
public List<DeleteAlbumCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateAlbumCommand"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumCommandFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid command to update an album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the album belongs to, taken from the route.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the album belongs to, taken from the route.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album to update, taken from the route.</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="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="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 should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeRatings">Whether the ratings should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created command to update an album.</returns>
|
||||
public UpdateAlbumCommand Create(
|
||||
string? libraryId = null,
|
||||
string? artistId = null,
|
||||
string? albumId = null,
|
||||
AlbumMetadataDto? metadata = null,
|
||||
MusicMediaFormat? mediaFormat = null,
|
||||
string? barcode = null,
|
||||
string? catalogNumber = null,
|
||||
Guid? musicBrainzReleaseId = null,
|
||||
Guid? musicBrainzReleaseGroupId = null,
|
||||
Guid? musicBrainzReleaseArtistId = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeArtistId = true,
|
||||
bool includeAlbumId = true,
|
||||
bool includeMetadata = true,
|
||||
bool includeMediaFormat = true,
|
||||
bool includeBarcode = true,
|
||||
bool includeCatalogNumber = true,
|
||||
bool includeMusicBrainzReleaseId = true,
|
||||
bool includeMusicBrainzReleaseGroupId = true,
|
||||
bool includeMusicBrainzReleaseArtistId = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true)
|
||||
{
|
||||
return new UpdateAlbumCommand(
|
||||
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null,
|
||||
includeMediaFormat ? (mediaFormat ?? _faker.PickRandom<MusicMediaFormat>()) : null,
|
||||
includeBarcode ? (barcode ?? _faker.Random.String2(_faker.Random.Int(12, 13), "0123456789")) : null,
|
||||
includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(_faker.Random.Int(1, 50))) : null,
|
||||
includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null,
|
||||
includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null,
|
||||
includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null,
|
||||
includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
|
||||
includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="UpdateAlbumCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<UpdateAlbumCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetAlbumQuery"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetAlbumQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the album belongs to, taken from the route.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the album belongs to, taken from the route.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album 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>
|
||||
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetAlbumQuery"/>.</returns>
|
||||
public GetAlbumQuery Create(
|
||||
string? libraryId = null,
|
||||
string? artistId = null,
|
||||
string? albumId = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeArtistId = true,
|
||||
bool includeAlbumId = true)
|
||||
{
|
||||
return new GetAlbumQuery(
|
||||
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetAlbumQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetAlbumQuery"/> instances.</returns>
|
||||
public List<GetAlbumQuery> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetAlbumTracksQuery"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetAlbumTracksQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the album belongs to, taken from the route.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the album belongs to, taken from the route.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album whose tracks 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>
|
||||
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetAlbumTracksQuery"/>.</returns>
|
||||
public GetAlbumTracksQuery Create(
|
||||
string? libraryId = null,
|
||||
string? artistId = null,
|
||||
string? albumId = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeArtistId = true,
|
||||
bool includeAlbumId = true)
|
||||
{
|
||||
return new GetAlbumTracksQuery(
|
||||
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetAlbumTracksQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetAlbumTracksQuery"/> instances.</returns>
|
||||
public List<GetAlbumTracksQuery> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetAlbumTracksLiteQuery"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksLiteQueryFixture
|
||||
{
|
||||
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetAlbumTracksLiteQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the album belongs to, taken from the route.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the album belongs to, taken from the route.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album whose tracks 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="includeAlbumId">Whether the album 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="GetAlbumTracksLiteQuery"/>.</returns>
|
||||
public GetAlbumTracksLiteQuery Create(
|
||||
string? libraryId = null,
|
||||
string? artistId = null,
|
||||
string? albumId = null,
|
||||
PaginationDataDto? paginationData = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeArtistId = true,
|
||||
bool includeAlbumId = true,
|
||||
bool includePaginationData = true)
|
||||
{
|
||||
return new GetAlbumTracksLiteQuery(
|
||||
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null,
|
||||
includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetAlbumTracksLiteQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetAlbumTracksLiteQuery"/> instances.</returns>
|
||||
public List<GetAlbumTracksLiteQuery> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AlbumMetadataDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumMetadataDtoFixture
|
||||
{
|
||||
private const int MINIMUM_RELEASE_YEAR = 1900;
|
||||
private const int MAXIMUM_RELEASE_YEAR = 2026;
|
||||
|
||||
private readonly Faker _faker = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly TagDtoFixture _tagDtoFixture = new();
|
||||
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
|
||||
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="AlbumMetadataDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="title">Optional. The title of the album.</param>
|
||||
/// <param name="originalTitle">Optional. The original title of the album.</param>
|
||||
/// <param name="description">Optional. A brief description or summary of the album.</param>
|
||||
/// <param name="releaseInfo">Optional. The release information of the album.</param>
|
||||
/// <param name="language">Optional. The language of the album.</param>
|
||||
/// <param name="originalLanguage">Optional. The original language of the album.</param>
|
||||
/// <param name="tags">Optional. The tags that describe or categorize the album.</param>
|
||||
/// <param name="genres">Optional. The genres associated with the album.</param>
|
||||
/// <param name="releaseType">Optional. The type of the release.</param>
|
||||
/// <param name="releaseStatus">Optional. The status of the release.</param>
|
||||
/// <param name="totalDiscs">Optional. The number of discs of the release.</param>
|
||||
/// <param name="totalTracks">Optional. The number of tracks of the release.</param>
|
||||
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeOriginalTitle">Whether the original title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReleaseInfo">Whether the release information should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLanguage">Whether the language should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeOriginalLanguage">Whether the original language should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTags">Whether the tags should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeGenres">Whether the genres should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReleaseType">Whether the release type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReleaseStatus">Whether the release status should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTotalDiscs">Whether the total number of discs should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTotalTracks">Whether the total number of tracks should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="AlbumMetadataDto"/>.</returns>
|
||||
public AlbumMetadataDto Create(
|
||||
string? title = null,
|
||||
string? originalTitle = null,
|
||||
string? description = null,
|
||||
ReleaseInfoDto? releaseInfo = null,
|
||||
LanguageInfoDto? language = null,
|
||||
LanguageInfoDto? originalLanguage = null,
|
||||
List<TagDto>? tags = null,
|
||||
List<GenreDto>? genres = null,
|
||||
MusicReleaseType? releaseType = null,
|
||||
MusicReleaseStatus? releaseStatus = null,
|
||||
int? totalDiscs = null,
|
||||
int? totalTracks = null,
|
||||
bool includeTitle = true,
|
||||
bool includeOriginalTitle = true,
|
||||
bool includeDescription = true,
|
||||
bool includeReleaseInfo = true,
|
||||
bool includeLanguage = true,
|
||||
bool includeOriginalLanguage = true,
|
||||
bool includeTags = true,
|
||||
bool includeGenres = true,
|
||||
bool includeReleaseType = true,
|
||||
bool includeReleaseStatus = true,
|
||||
bool includeTotalDiscs = true,
|
||||
bool includeTotalTracks = true)
|
||||
{
|
||||
return new AlbumMetadataDto(
|
||||
includeTitle ? (title ?? _faker.Music.Genre()) : null,
|
||||
includeOriginalTitle ? (originalTitle ?? _faker.Music.Genre()) : null,
|
||||
includeDescription ? (description ?? _faker.Lorem.Paragraph()) : null,
|
||||
includeReleaseInfo ? (releaseInfo ?? GenerateReleaseInfo()) : null,
|
||||
includeLanguage ? (language ?? _languageInfoDtoFixture.Create()) : null,
|
||||
includeOriginalLanguage ? (originalLanguage ?? _languageInfoDtoFixture.Create()) : null,
|
||||
includeTags ? (tags ?? GenerateDistinctTags()) : null,
|
||||
includeGenres ? (genres ?? GenerateDistinctGenres()) : null,
|
||||
includeReleaseType ? (releaseType ?? _faker.PickRandom<MusicReleaseType>()) : null,
|
||||
includeReleaseStatus ? (releaseStatus ?? _faker.PickRandom<MusicReleaseStatus>()) : null,
|
||||
includeTotalDiscs ? (totalDiscs ?? _faker.Random.Int(1, 3)) : null,
|
||||
includeTotalTracks ? (totalTracks ?? _faker.Random.Int(1, 30)) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AlbumMetadataDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<AlbumMetadataDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ReleaseInfoDto"/> with consistent dates and years.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="ReleaseInfoDto"/>.</returns>
|
||||
private ReleaseInfoDto GenerateReleaseInfo()
|
||||
{
|
||||
int originalReleaseYear = Random.Shared.Next(MINIMUM_RELEASE_YEAR, MAXIMUM_RELEASE_YEAR);
|
||||
int reReleaseYear = Random.Shared.Next(originalReleaseYear, MAXIMUM_RELEASE_YEAR);
|
||||
return _releaseInfoDtoFixture.Create(
|
||||
originalReleaseDate: new DateOnly(originalReleaseYear, 1, 1),
|
||||
originalReleaseYear: originalReleaseYear,
|
||||
reReleaseDate: new DateOnly(reReleaseYear, 1, 1),
|
||||
reReleaseYear: reReleaseYear,
|
||||
releaseCountry: _faker.PickRandom<ReleaseCountry>(),
|
||||
releaseVersion: _faker.Random.String2(_faker.Random.Number(1, 50)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates two genres with distinct names, so that the storage deduplication never collapses them into one.
|
||||
/// </summary>
|
||||
/// <returns>The created genres.</returns>
|
||||
private List<GenreDto> GenerateDistinctGenres()
|
||||
{
|
||||
return
|
||||
[
|
||||
_genreDtoFixture.Create(name: CreateUniqueName()),
|
||||
_genreDtoFixture.Create(name: CreateUniqueName())
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates two tags with distinct names, so that the storage deduplication never collapses them into one.
|
||||
/// </summary>
|
||||
/// <returns>The created tags.</returns>
|
||||
private List<TagDto> GenerateDistinctTags()
|
||||
{
|
||||
return
|
||||
[
|
||||
_tagDtoFixture.Create(name: CreateUniqueName()),
|
||||
_tagDtoFixture.Create(name: CreateUniqueName())
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a unique name, so that the generated genres and tags never collapse into one after storage deduplication.
|
||||
/// </summary>
|
||||
/// <returns>A unique name of at most 50 characters.</returns>
|
||||
private string CreateUniqueName()
|
||||
{
|
||||
string uniqueSuffix = Guid.NewGuid().ToString("N")[..12];
|
||||
int maximumWordLength = 50 - uniqueSuffix.Length - 1;
|
||||
string word = _faker.Lorem.Word();
|
||||
string truncatedWord = word.Length > maximumWordLength ? word[..maximumWordLength] : word;
|
||||
return $"{truncatedWord}-{uniqueSuffix}";
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AddAlbumRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddAlbumRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly AddTrackRequestFixture _addTrackRequestFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid request to add an album.
|
||||
/// </summary>
|
||||
/// <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="includeMetadata">Whether the metadata 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>
|
||||
/// <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>
|
||||
/// <returns>The created request to add an album.</returns>
|
||||
public AddAlbumRequest Create(
|
||||
AlbumMetadataDto? metadata = null,
|
||||
MusicMediaFormat? mediaFormat = null,
|
||||
string? barcode = null,
|
||||
string? catalogNumber = null,
|
||||
Guid? musicBrainzReleaseId = null,
|
||||
Guid? musicBrainzReleaseGroupId = null,
|
||||
Guid? musicBrainzReleaseArtistId = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
List<AddTrackRequest>? tracks = null,
|
||||
bool includeMetadata = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true,
|
||||
bool includeTracks = true,
|
||||
bool includeMediaFormat = true,
|
||||
bool includeBarcode = true,
|
||||
bool includeCatalogNumber = true,
|
||||
bool includeMusicBrainzReleaseId = true,
|
||||
bool includeMusicBrainzReleaseGroupId = true,
|
||||
bool includeMusicBrainzReleaseArtistId = true)
|
||||
{
|
||||
return new AddAlbumRequest(
|
||||
includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null,
|
||||
includeMediaFormat ? (mediaFormat ?? _faker.PickRandom<MusicMediaFormat>()) : null,
|
||||
includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null,
|
||||
includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(10)) : null,
|
||||
includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null,
|
||||
includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null,
|
||||
includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null,
|
||||
includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null,
|
||||
includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null,
|
||||
includeTracks ? (tracks ?? _addTrackRequestFixture.CreateMany(_faker.Random.Int(1, 3))) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AddAlbumRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<AddAlbumRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateAlbumRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid request to update an album.
|
||||
/// </summary>
|
||||
/// <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="includeMetadata">Whether the metadata 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="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>
|
||||
/// <returns>The created request to update an album.</returns>
|
||||
public UpdateAlbumRequest Create(
|
||||
AlbumMetadataDto? metadata = null,
|
||||
MusicMediaFormat? mediaFormat = null,
|
||||
string? barcode = null,
|
||||
string? catalogNumber = null,
|
||||
Guid? musicBrainzReleaseId = null,
|
||||
Guid? musicBrainzReleaseGroupId = null,
|
||||
Guid? musicBrainzReleaseArtistId = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
bool includeMetadata = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true,
|
||||
bool includeMediaFormat = true,
|
||||
bool includeBarcode = true,
|
||||
bool includeCatalogNumber = true,
|
||||
bool includeMusicBrainzReleaseId = true,
|
||||
bool includeMusicBrainzReleaseGroupId = true,
|
||||
bool includeMusicBrainzReleaseArtistId = true)
|
||||
{
|
||||
return new UpdateAlbumRequest(
|
||||
includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null,
|
||||
includeMediaFormat ? (mediaFormat ?? _faker.PickRandom<MusicMediaFormat>()) : null,
|
||||
includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null,
|
||||
includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(10)) : null,
|
||||
includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null,
|
||||
includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null,
|
||||
includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null,
|
||||
includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null,
|
||||
includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="UpdateAlbumRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<UpdateAlbumRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AlbumLiteResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumLiteResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="AlbumLiteResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the album.</param>
|
||||
/// <param name="title">Optional. The title of the album.</param>
|
||||
/// <param name="totalTracks">Optional. The number of tracks of the release.</param>
|
||||
/// <returns>The created <see cref="AlbumLiteResponse"/>.</returns>
|
||||
public AlbumLiteResponse Create(
|
||||
Guid? id = null,
|
||||
string? title = null,
|
||||
int? totalTracks = null)
|
||||
{
|
||||
return new AlbumLiteResponse(
|
||||
id ?? Guid.NewGuid(),
|
||||
title ?? _faker.Commerce.ProductName(),
|
||||
totalTracks ?? _faker.Random.Int(1, 30));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AlbumLiteResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<AlbumLiteResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AlbumResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
private readonly TrackResponseFixture _trackResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="AlbumResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the album.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the album belongs to.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the album belongs to.</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="createdOnUtc">Optional. The date and time when the album was created.</param>
|
||||
/// <param name="updatedOnUtc">Optional. The date and time when the album was updated.</param>
|
||||
/// <param name="contributors">Optional. The list of contributor references of the album.</param>
|
||||
/// <param name="ratings">Optional. The list of ratings of the album.</param>
|
||||
/// <param name="tracks">Optional. The list of tracks of the album.</param>
|
||||
/// <param name="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="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="includeRatings">Whether the ratings should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTracks">Whether the tracks should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="AlbumResponse"/>.</returns>
|
||||
public AlbumResponse Create(
|
||||
Guid? id = null,
|
||||
Guid? artistId = null,
|
||||
Guid? libraryId = null,
|
||||
AlbumMetadataDto? metadata = null,
|
||||
MusicMediaFormat? mediaFormat = null,
|
||||
string? barcode = null,
|
||||
string? catalogNumber = null,
|
||||
Guid? musicBrainzReleaseId = null,
|
||||
Guid? musicBrainzReleaseGroupId = null,
|
||||
Guid? musicBrainzReleaseArtistId = null,
|
||||
DateTime? createdOnUtc = null,
|
||||
DateTime? updatedOnUtc = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
List<TrackResponse>? tracks = null,
|
||||
bool includeMediaFormat = true,
|
||||
bool includeBarcode = true,
|
||||
bool includeCatalogNumber = true,
|
||||
bool includeMusicBrainzReleaseId = true,
|
||||
bool includeMusicBrainzReleaseGroupId = true,
|
||||
bool includeMusicBrainzReleaseArtistId = true,
|
||||
bool includeUpdatedOnUtc = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true,
|
||||
bool includeTracks = true)
|
||||
{
|
||||
return new AlbumResponse(
|
||||
id ?? Guid.NewGuid(),
|
||||
artistId ?? Guid.NewGuid(),
|
||||
libraryId ?? Guid.NewGuid(),
|
||||
metadata ?? _albumMetadataDtoFixture.Create(),
|
||||
includeMediaFormat ? (mediaFormat ?? _faker.PickRandom<MusicMediaFormat>()) : null,
|
||||
includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null,
|
||||
includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(10)) : null,
|
||||
includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? Guid.NewGuid()) : null,
|
||||
includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? Guid.NewGuid()) : null,
|
||||
includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? Guid.NewGuid()) : null,
|
||||
createdOnUtc ?? _faker.Date.Past().ToUniversalTime(),
|
||||
includeUpdatedOnUtc ? (updatedOnUtc ?? _faker.Date.Recent().ToUniversalTime()) : null,
|
||||
includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(1)) : null,
|
||||
includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(1)) : null,
|
||||
includeTracks ? (tracks ?? _trackResponseFixture.CreateMany(1)) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AlbumResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<AlbumResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+735
@@ -0,0 +1,735 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AlbumRepository"/> class, exercising it against a real SQLite database.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumRepositoryTests
|
||||
{
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly AlbumContributorEntityFixture _albumContributorEntityFixture = new();
|
||||
private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new();
|
||||
private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new();
|
||||
private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new();
|
||||
private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenCalledWithAValidAlbum_ShouldPersistTheAlbumAndItsAggregate()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = BuildFullAlbum(artist.Id, libraryId, "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
AlbumEntity? storedAlbum = await context.Albums
|
||||
.AsNoTracking()
|
||||
.Include(candidate => candidate.Ratings)
|
||||
.Include(candidate => candidate.Tags)
|
||||
.Include(candidate => candidate.Genres)
|
||||
.Include(candidate => candidate.Contributors)
|
||||
.Include(candidate => candidate.Tracks)
|
||||
.ThenInclude(candidate => candidate.Moods)
|
||||
.AsSplitQuery()
|
||||
.FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
|
||||
Assert.NotNull(storedAlbum);
|
||||
Assert.Equal("A Night at the Opera", storedAlbum!.Title);
|
||||
Assert.Single(storedAlbum.Ratings);
|
||||
Assert.Equal(2, storedAlbum.Tags.Count);
|
||||
Assert.Equal(2, storedAlbum.Genres.Count);
|
||||
Assert.Single(storedAlbum.Contributors);
|
||||
TrackEntity storedTrack = Assert.Single(storedAlbum.Tracks);
|
||||
Assert.Equal(2, storedTrack.Moods.Count);
|
||||
// Each tag and genre of the aggregate is stored exactly once.
|
||||
Assert.Single(await context.Set<TagEntity>().Where(tag => tag.Name == "album-tag-1").ToListAsync());
|
||||
Assert.Single(await context.Set<GenreEntity>().Where(genre => genre.Name == "album-genre-1").ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAlbumWithTheSameIdAlreadyExists_ShouldReturnAlbumAlreadyExists()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-id-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity existingAlbum = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(existingAlbum);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: existingAlbum.Id, artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenTwoTracksOfTheSameRequestShareAPath_ShouldReturnTrackAlreadyExists()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-duprequest-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
album.Tracks =
|
||||
[
|
||||
_trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false),
|
||||
_trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false)
|
||||
];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenATrackPathIsAlreadyStoredInTheLibrary_ShouldReturnTrackAlreadyExists()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-storedpath-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity existingAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Existing");
|
||||
context.Tracks.Add(_trackEntityFixture.Create(
|
||||
albumId: existingAlbum.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldPersistTheAlbum()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-otherlibrary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid firstLibraryId = Guid.NewGuid();
|
||||
ArtistEntity firstArtist = await SeedArtistAsync(context, firstLibraryId);
|
||||
AlbumEntity firstAlbum = await SeedAlbumAsync(context, firstLibraryId, firstArtist.Id, "First");
|
||||
context.Tracks.Add(_trackEntityFixture.Create(
|
||||
albumId: firstAlbum.Id, libraryId: firstLibraryId, path: "/music/queen/we-are-the-champions.flac", includeMetadata: false));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
Guid secondLibraryId = Guid.NewGuid();
|
||||
ArtistEntity secondArtist = await SeedArtistAsync(context, secondLibraryId);
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: secondArtist.Id, libraryId: secondLibraryId, includeTracks: false, includeMetadata: false);
|
||||
album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: secondLibraryId, path: "/music/queen/we-are-the-champions.flac", includeMetadata: false)];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
|
||||
Assert.NotNull(storedAlbum);
|
||||
Assert.Equal(secondLibraryId, storedAlbum!.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenTagsAndGenresAlreadyExistByName_ShouldReuseTheStoredRows()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-reuse-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
context.Set<TagEntity>().Add(_tagEntityFixture.Create(name: "ExistingTag"));
|
||||
context.Set<GenreEntity>().Add(_genreEntityFixture.Create(name: "ExistingGenre"));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
album.Tags = [_tagEntityFixture.Create(name: "ExistingTag")];
|
||||
album.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")];
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, includeMetadata: false);
|
||||
track.Tags = [_tagEntityFixture.Create(name: "ExistingTag")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")];
|
||||
album.Tracks = [track];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
// The shared rows are reused instead of being duplicated.
|
||||
Assert.Single(await context.Set<TagEntity>().Where(tag => tag.Name == "ExistingTag").ToListAsync());
|
||||
Assert.Single(await context.Set<GenreEntity>().Where(genre => genre.Name == "ExistingGenre").ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenANewTagAndGenreNameIsSharedBetweenTheAlbumAndItsTracks_ShouldPersistItOnce()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-shared-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
|
||||
album.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")];
|
||||
album.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")];
|
||||
track.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")];
|
||||
album.Tracks = [track];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
// The name shared by the album and its tracks is persisted exactly once.
|
||||
Assert.Single(await context.Set<TagEntity>().Where(tag => tag.Name == "SharedNewTag").ToListAsync());
|
||||
Assert.Single(await context.Set<GenreEntity>().Where(genre => genre.Name == "SharedNewGenre").ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeAnyAuditColumn()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
Guid userId = Guid.NewGuid();
|
||||
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = await SeedFullAlbumAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
Guid contributorId = album.Contributors[0].Id;
|
||||
DateTime contributorCreatedOnUtc = album.Contributors[0].CreatedOnUtc;
|
||||
// Detach the seeded graph, so that the update must load the tracked album through its include chain instead of returning the already populated seeded instance.
|
||||
context.ChangeTracker.Clear();
|
||||
AlbumEntity incoming = await LoadDetachedAlbumAsync(context, album.Id);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
|
||||
Assert.NotNull(storedAlbum);
|
||||
Assert.Null(storedAlbum!.UpdatedOnUtc);
|
||||
AlbumContributorEntity storedContributor = Assert.Single(storedAlbum.Contributors);
|
||||
Assert.Equal(contributorId, storedContributor.Id);
|
||||
Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc);
|
||||
Assert.Single(await context.Set<TagEntity>().Where(tag => tag.Name == "album-tag-1").ToListAsync());
|
||||
Assert.Single(await context.Set<GenreEntity>().Where(genre => genre.Name == "album-genre-1").ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenOnlyTheScalarValuesChanged_ShouldStampTheAlbumAndPreserveArtistAndLibrary()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-scalars-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
Guid userId = Guid.NewGuid();
|
||||
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = await SeedFullAlbumAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
AlbumEntity incoming = await LoadDetachedAlbumAsync(context, album.Id);
|
||||
incoming.Title = "A Night at the Opera (Remastered)";
|
||||
incoming.ArtistId = Guid.NewGuid();
|
||||
incoming.LibraryId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
|
||||
Assert.NotNull(storedAlbum);
|
||||
Assert.Equal("A Night at the Opera (Remastered)", storedAlbum!.Title);
|
||||
// The stored identity is preserved and only the actual edit is stamped.
|
||||
Assert.Equal(artist.Id, storedAlbum.ArtistId);
|
||||
Assert.Equal(libraryId, storedAlbum.LibraryId);
|
||||
Assert.Equal(utcNow, storedAlbum.UpdatedOnUtc);
|
||||
Assert.Equal(userId, storedAlbum.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenRatingsAndContributorsChange_ShouldReconcileThem()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-owned-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
Guid keptMediaContributorId = Guid.NewGuid();
|
||||
Guid removedMediaContributorId = Guid.NewGuid();
|
||||
Guid addedMediaContributorId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
album.Ratings =
|
||||
[
|
||||
_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
|
||||
_audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10),
|
||||
_audioRatingEntityFixture.Create(value: 2, maxValue: 5, source: AudioRatingSource.LastFm, voteCount: 20)
|
||||
];
|
||||
album.Contributors =
|
||||
[
|
||||
_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer),
|
||||
_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Composer)
|
||||
];
|
||||
context.Albums.Add(album);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
AlbumEntity incoming = await LoadDetachedAlbumAsync(context, album.Id);
|
||||
incoming.Ratings =
|
||||
[
|
||||
_audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
|
||||
_audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10),
|
||||
_audioRatingEntityFixture.Create(value: 1, maxValue: 5, source: AudioRatingSource.Discogs, voteCount: 5)
|
||||
];
|
||||
incoming.Contributors =
|
||||
[
|
||||
_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer),
|
||||
_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: addedMediaContributorId, role: MediaContributorRole.Vocals)
|
||||
];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity? storedAlbum = await context.Albums
|
||||
.AsNoTracking()
|
||||
.Include(candidate => candidate.Ratings)
|
||||
.Include(candidate => candidate.Contributors)
|
||||
.FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
|
||||
Assert.NotNull(storedAlbum);
|
||||
Assert.Equal(3, storedAlbum!.Ratings.Count);
|
||||
Assert.Contains(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.MusicBrainz && rating.Value == 3M);
|
||||
Assert.Contains(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.User && rating.Value == 5M);
|
||||
Assert.Contains(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.Discogs && rating.Value == 1M);
|
||||
Assert.DoesNotContain(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.LastFm);
|
||||
Assert.Equal(2, storedAlbum.Contributors.Count);
|
||||
Assert.DoesNotContain(storedAlbum.Contributors, contributor => contributor.MediaContributorId == removedMediaContributorId);
|
||||
Assert.Contains(storedAlbum.Contributors, contributor => contributor.MediaContributorId == addedMediaContributorId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenAlbumExists_ShouldIncludeTheNavigationProperties()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = await SeedFullAlbumAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
Result<AlbumEntity?> result = await sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity retrievedAlbum = result.Value!;
|
||||
Assert.NotNull(retrievedAlbum.Artist);
|
||||
Assert.Equal(artist.Id, retrievedAlbum.Artist!.Id);
|
||||
Assert.Single(retrievedAlbum.Ratings);
|
||||
Assert.Equal(2, retrievedAlbum.Tags.Count);
|
||||
Assert.Equal(2, retrievedAlbum.Genres.Count);
|
||||
Assert.Single(retrievedAlbum.Contributors);
|
||||
TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks);
|
||||
Assert.Single(retrievedTrack.Ratings);
|
||||
Assert.Equal(2, retrievedTrack.Genres.Count);
|
||||
Assert.Equal(2, retrievedTrack.Moods.Count);
|
||||
Assert.Equal(2, retrievedTrack.Isrcs.Count);
|
||||
Assert.Single(retrievedTrack.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnAnUntrackedAlbum()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(album);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<AlbumEntity?> result = await sut.GetByIdAsync(
|
||||
album.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(context.ChangeTracker.Entries<AlbumEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumsLiteByArtistIdAsync_WhenCalled_ShouldNotTrackTheEntities()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(album);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<AlbumLiteRow>> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value.Data);
|
||||
Assert.Empty(context.ChangeTracker.Entries<AlbumEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByArtistIdAsync_WhenCalled_ShouldReturnTheArtistAlbumsOrderedWithTheirCollections()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyartist-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity betaAlbum = await SeedFullAlbumAsync(context, libraryId, artist.Id, "Beta");
|
||||
AlbumEntity alphaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Alpha");
|
||||
ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(
|
||||
artistId: otherArtist.Id, libraryId: libraryId, title: "Gamma", includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(albumOfAnotherArtist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<AlbumEntity>> result = await sut.GetByArtistIdAsync(artist.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal([alphaAlbum.Id, betaAlbum.Id], result.Value.Select(album => album.Id));
|
||||
AlbumEntity retrievedAlbum = result.Value.Single(album => album.Id == betaAlbum.Id);
|
||||
Assert.Single(retrievedAlbum.Ratings);
|
||||
Assert.Equal(2, retrievedAlbum.Tags.Count);
|
||||
Assert.Equal(2, retrievedAlbum.Genres.Count);
|
||||
Assert.Single(retrievedAlbum.Contributors);
|
||||
TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks);
|
||||
Assert.Equal(2, retrievedTrack.Moods.Count);
|
||||
Assert.Single(retrievedTrack.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumsLiteByArtistIdAsync_WhenPaginationDataIsNull_ShouldReturnAllArtistAlbumsOrdered()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-null-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity betaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Beta");
|
||||
AlbumEntity alphaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Alpha");
|
||||
ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(
|
||||
artistId: otherArtist.Id, libraryId: libraryId, title: "Gamma", includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(albumOfAnotherArtist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<AlbumLiteRow>> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal([alphaAlbum.Id, betaAlbum.Id], result.Value.Data.Select(row => row.Id));
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Equal(1, result.Value.CurrentPage);
|
||||
Assert.Equal(2, result.Value.PerPage);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, 2, 1, 2)] // The first page is fully returned.
|
||||
[InlineData(2, 2, 2, 2)] // A middle page is fully returned.
|
||||
[InlineData(3, 2, 3, 1)] // The last page is partially returned.
|
||||
[InlineData(99, 2, 3, 1)] // A page beyond the last one is clamped to the last page.
|
||||
public async Task GetAlbumsLiteByArtistIdAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage(int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount)
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-page-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
List<AlbumEntity> albums = _albumEntityFixture.CreateMany(5);
|
||||
for (int index = 0; index < albums.Count; index++)
|
||||
{
|
||||
albums[index].ArtistId = artist.Id;
|
||||
albums[index].LibraryId = libraryId;
|
||||
albums[index].Title = $"Album {index}";
|
||||
albums[index].Tracks = [];
|
||||
}
|
||||
context.Albums.AddRange(albums);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<AlbumLiteRow>> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, paginationData, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(5, result.Value.Count);
|
||||
Assert.Equal(3, result.Value.NumberOfPages);
|
||||
Assert.Equal(expectedCurrentPage, result.Value.CurrentPage);
|
||||
Assert.Equal(perPage, result.Value.PerPage);
|
||||
Assert.Equal(expectedRowCount, result.Value.Data.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an album repository backed by the provided context, wiring the real track repository.
|
||||
/// </summary>
|
||||
/// <param name="context">The context the repository operates on.</param>
|
||||
/// <returns>The created repository.</returns>
|
||||
private static AlbumRepository CreateAlbumRepository(LuminaDbContext context)
|
||||
{
|
||||
return new AlbumRepository(context, new TrackRepository(context));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist with no albums or contributors, so that the required foreign key of an album is satisfied.
|
||||
/// </summary>
|
||||
/// <param name="context">The context the artist is persisted through.</param>
|
||||
/// <param name="libraryId">The Id of the library that owns the artist.</param>
|
||||
/// <returns>The persisted artist.</returns>
|
||||
private async Task<ArtistEntity> SeedArtistAsync(LuminaDbContext context, Guid libraryId)
|
||||
{
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
|
||||
context.Artists.Add(artist);
|
||||
await context.SaveChangesAsync();
|
||||
return artist;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album that belongs to the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="context">The context the album is persisted through.</param>
|
||||
/// <param name="libraryId">The Id of the library that owns the album.</param>
|
||||
/// <param name="artistId">The Id of the artist that owns the album.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The persisted album.</returns>
|
||||
private async Task<AlbumEntity> SeedAlbumAsync(LuminaDbContext context, Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, title: title, includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(album);
|
||||
await context.SaveChangesAsync();
|
||||
return album;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album with one track, including every related collection deterministically.
|
||||
/// </summary>
|
||||
/// <param name="context">The context the album is persisted through.</param>
|
||||
/// <param name="libraryId">The Id of the library that owns the album.</param>
|
||||
/// <param name="artistId">The Id of the artist that owns the album.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The persisted album.</returns>
|
||||
private async Task<AlbumEntity> SeedFullAlbumAsync(LuminaDbContext context, Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
AlbumEntity album = BuildFullAlbum(artistId, libraryId, title);
|
||||
context.Albums.Add(album);
|
||||
await context.SaveChangesAsync();
|
||||
return album;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds an album with one track, including every related collection deterministically, without persisting it.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The Id of the artist that owns the album.</param>
|
||||
/// <param name="libraryId">The Id of the library that owns the album.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The created album.</returns>
|
||||
private AlbumEntity BuildFullAlbum(Guid artistId, Guid libraryId, string title)
|
||||
{
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, title: title, includeTracks: false, includeMetadata: false);
|
||||
album.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
|
||||
album.Tags = [_tagEntityFixture.Create(name: "album-tag-1"), _tagEntityFixture.Create(name: "album-tag-2")];
|
||||
album.Genres = [_genreEntityFixture.Create(name: "album-genre-1"), _genreEntityFixture.Create(name: "album-genre-2")];
|
||||
album.Contributors = [_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)];
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
|
||||
track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.User, voteCount: 10)];
|
||||
track.Tags = [_tagEntityFixture.Create(name: "track-tag-1"), _tagEntityFixture.Create(name: "track-tag-2")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "track-genre-1"), _genreEntityFixture.Create(name: "track-genre-2")];
|
||||
track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")];
|
||||
track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")];
|
||||
track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
|
||||
album.Tracks = [track];
|
||||
return album;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads a detached copy of a stored album with the whole aggregate, so that it can be handed to the repository as the desired state of an edit.
|
||||
/// </summary>
|
||||
/// <param name="context">The context that tracks the stored album.</param>
|
||||
/// <param name="albumId">The Id of the album to load.</param>
|
||||
/// <returns>The detached copy of the album.</returns>
|
||||
private static async Task<AlbumEntity> LoadDetachedAlbumAsync(LuminaDbContext context, Guid albumId)
|
||||
{
|
||||
return await context.Albums
|
||||
.AsNoTracking()
|
||||
.Include(album => album.Ratings)
|
||||
.Include(album => album.Tags)
|
||||
.Include(album => album.Genres)
|
||||
.Include(album => album.Contributors)
|
||||
.Include(album => album.Tracks)
|
||||
.ThenInclude(track => track.Ratings)
|
||||
.Include(album => album.Tracks)
|
||||
.ThenInclude(track => track.Genres)
|
||||
.Include(album => album.Tracks)
|
||||
.ThenInclude(track => track.Tags)
|
||||
.Include(album => album.Tracks)
|
||||
.ThenInclude(track => track.Moods)
|
||||
.Include(album => album.Tracks)
|
||||
.ThenInclude(track => track.Isrcs)
|
||||
.Include(album => album.Tracks)
|
||||
.ThenInclude(track => track.Contributors)
|
||||
.AsSplitQuery()
|
||||
.FirstAsync(album => album.Id == albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
|
||||
/// </summary>
|
||||
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
|
||||
/// <param name="userId">The Id of the user reported as the current user.</param>
|
||||
/// <param name="utcNow">The current UTC time reported by the time provider.</param>
|
||||
/// <returns>The created context.</returns>
|
||||
private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow)
|
||||
{
|
||||
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
|
||||
currentUserService.UserId.Returns(userId);
|
||||
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
dateTimeProvider.UtcNow.Returns(utcNow);
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseSqlite(anchorConnection.ConnectionString)
|
||||
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
|
||||
.Options);
|
||||
context.Database.EnsureCreated();
|
||||
return context;
|
||||
}
|
||||
}
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddAlbumEndpointTests(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 AddAlbum_WhenCalledWithValidData_ShouldAddAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(
|
||||
metadata: _albumMetadataDtoFixture.Create(title: "News of the World"),
|
||||
contributors: [],
|
||||
ratings: [],
|
||||
tracks: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AlbumResponse? albumResponse = JsonSerializer.Deserialize<AlbumResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(albumResponse);
|
||||
Assert.Equal(artistId, albumResponse!.ArtistId);
|
||||
Assert.Equal(libraryId, albumResponse.LibraryId);
|
||||
Assert.Equal("News of the World", albumResponse.Metadata.Title);
|
||||
|
||||
Assert.NotNull(response.Headers.Location);
|
||||
Assert.EndsWith($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumResponse.Id}", response.Headers.Location!.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenMetadataIsMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(includeMetadata: false, contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Metadata.MetadataCannotBeNull.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenTitleIsMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(
|
||||
metadata: _albumMetadataDtoFixture.Create(includeTitle: false),
|
||||
contributors: [],
|
||||
ratings: [],
|
||||
tracks: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Music.AlbumTitleCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutDisclosingIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
Guid otherLibraryId = Guid.NewGuid();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{artistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(otherLibraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{artistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Library.LibraryIdCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Music.ArtistIdCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request, cts.Token));
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
/// <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 Id of the seeded artist.</returns>
|
||||
private async Task<Guid> 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;
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
+336
@@ -0,0 +1,336 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteAlbumEndpointTests : 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="DeleteAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteAlbumEndpointTests(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 DeleteAlbum_WhenAlbumBelongsToAnOwnedArtist_ShouldDeleteTheAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid otherAlbumId) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Null(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId));
|
||||
// The sibling album of the artist is preserved.
|
||||
Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == otherAlbumId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _, _) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumRequestedThroughDifferentArtist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId, _) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId, Guid albumId, _) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, _) = await SeedLibraryArtistWithTwoAlbumsAsync(otherUserId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <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 that owns two albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and the two albums.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid otherAlbumId)> SeedLibraryArtistWithTwoAlbumsAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid otherAlbumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
AlbumEntity otherAlbum = _albumEntityFixture.Create(id: otherAlbumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album, otherAlbum], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, otherAlbumId);
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
+335
@@ -0,0 +1,335 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumEndpointTests : 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="GetAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAlbumEndpointTests(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 GetAlbum_WhenAlbumBelongsToAnOwnedLibrary_ShouldReturnAlbumDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AlbumResponse? album = JsonSerializer.Deserialize<AlbumResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(album);
|
||||
Assert.Equal(albumId, album!.Id);
|
||||
Assert.Equal(artistId, album.ArtistId);
|
||||
Assert.Equal(libraryId, album.LibraryId);
|
||||
Assert.Equal("A Night at the Opera", album.Metadata.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumRequestedThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
// The route artist id is enforced, so an album of another artist is reported as not found, without disclosing that it exists.
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumRequestedThroughDifferentLibrary_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId, "News of the World");
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="albumTitle">The title of the seeded album.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAlbumTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksEndpointTests : 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 TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAlbumTracksEndpointTests(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 GetAlbumTracks_WhenAlbumHasTracks_ShouldReturnTrackDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TrackResponse>? tracks = await response.Content.ReadFromJsonAsync<List<TrackResponse>>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
TrackResponse track = Assert.Single(tracks!);
|
||||
Assert.Equal("Bohemian Rhapsody", track.Metadata.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumHasNoTracks_ShouldReturnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TrackResponse>? tracks = await response.Content.ReadFromJsonAsync<List<TrackResponse>>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Empty(tracks!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumRequestedThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="albumTitle">The title of the seeded album.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist, one of its albums and one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/bohemian-rhapsody-{Guid.NewGuid():N}.flac", title: "Bohemian Rhapsody", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAlbumTracksLiteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksLiteEndpointTests : 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 TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksLiteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAlbumTracksLiteEndpointTests(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 GetAlbumTracksLite_WhenAlbumHasTracks_ShouldReturnTrackLiteDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<TrackLiteResponse>? tracks = await response.Content.ReadFromJsonAsync<PaginatedResponse<TrackLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Equal(1, tracks!.Count);
|
||||
TrackLiteResponse track = Assert.Single(tracks.Data);
|
||||
Assert.Equal("Bohemian Rhapsody", track.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumHasNoTracks_ShouldReturnEmptyPaginatedResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<TrackLiteResponse>? tracks = await response.Content.ReadFromJsonAsync<PaginatedResponse<TrackLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Empty(tracks!.Data);
|
||||
Assert.Equal(0, tracks.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid/tracks/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="albumTitle">The title of the seeded album.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist, one of its albums and one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/bohemian-rhapsody-{Guid.NewGuid():N}.flac", title: "Bohemian Rhapsody", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
+344
@@ -0,0 +1,344 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly UpdateAlbumRequestFixture _updateAlbumRequestFixture = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateAlbumEndpointTests(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 UpdateAlbum_WhenCalledByOwnerWithValidData_ShouldUpdateAlbumAndPersistChanges()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(
|
||||
metadata: _albumMetadataDtoFixture.Create(title: "Updated Album"),
|
||||
contributors: [],
|
||||
ratings: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AlbumResponse? albumResponse = JsonSerializer.Deserialize<AlbumResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(albumResponse);
|
||||
Assert.Equal(albumId, albumResponse!.Id);
|
||||
Assert.Equal("Updated Album", albumResponse.Metadata.Title);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
AlbumEntity storedAlbum = dbContext.Albums.Single(album => album.Id == albumId);
|
||||
Assert.Equal("Updated Album", storedAlbum.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId, "News of the World");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenMetadataIsMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(includeMetadata: false, contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "MetadataCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <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 and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="albumTitle">The title of the seeded album.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="AddAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddAlbumEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddAlbumEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<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/{artistId}/albums", problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenUnauthorized_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task AddAlbum_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task AddAlbum_WithSQLInjectionInArtistRouteId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("ArtistIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task AddAlbum_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousTitle)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
(Guid libraryId, Guid artistId) = await SeedLibraryArtistAndAlbumAsync(userId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(
|
||||
metadata: _albumMetadataDtoFixture.Create(title: maliciousTitle),
|
||||
contributors: [],
|
||||
ratings: [],
|
||||
tracks: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request);
|
||||
|
||||
// Assert
|
||||
// The malicious title passes validation, reaches the parameterized insert, and is persisted verbatim: if it were
|
||||
// concatenated into raw SQL, the insert would fail and the album would not be created.
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(2, await dbContext.Albums.CountAsync(album => album.LibraryId == libraryId));
|
||||
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
_seededUsernames.Add(ownerUsername);
|
||||
(Guid libraryId, Guid artistId) = await SeedLibraryArtistAndAlbumAsync(ownerId);
|
||||
|
||||
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(requesterUsername);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<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"/>, together with an artist that owns one album.
|
||||
/// </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)> SeedLibraryArtistAndAlbumAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="DeleteAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteAlbumEndpointTests : 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 AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteAlbumEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// A unique X-Forwarded-For isolates rate limiting state per test.
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<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 Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task DeleteAlbum_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task DeleteAlbum_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task DeleteAlbum_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistWithTwoAlbumsAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<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("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutDeletingIt()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(actingUsername);
|
||||
(Guid ownLibraryId, _, _) = await SeedLibraryArtistWithTwoAlbumsAsync(actingUserId);
|
||||
|
||||
// The album lives in a library owned by another user, and is referenced through the acting user's own library route.
|
||||
HttpClient victimClient = _apiFactory.CreateClient();
|
||||
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
|
||||
_seededUsernames.Add(victimUsername);
|
||||
(_, Guid victimArtistId, Guid victimAlbumId) = await SeedLibraryArtistWithTwoAlbumsAsync(victimUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
|
||||
// The other user's album is untouched.
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId));
|
||||
|
||||
}
|
||||
|
||||
/// <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 that owns two albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and the first album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistWithTwoAlbumsAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid otherAlbumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
AlbumEntity otherAlbum = _albumEntityFixture.Create(id: otherAlbumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album, otherAlbum], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumEndpointTests : 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 AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAlbumEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// A unique X-Forwarded-For isolates rate limiting state per test.
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<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 Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task GetAlbum_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task GetAlbum_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task GetAlbum_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousAlbumId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<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 and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetAlbumTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksEndpointTests : 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 AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAlbumTracksEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// A unique X-Forwarded-For isolates rate limiting state per test.
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<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 Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task GetAlbumTracks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task GetAlbumTracks_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task GetAlbumTracks_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousAlbumId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<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, one of its albums and one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/we-are-the-champions-{Guid.NewGuid():N}.flac", title: "We Are the Champions", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetAlbumTracksLiteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksLiteEndpointTests : 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 AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksLiteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAlbumTracksLiteEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// A unique X-Forwarded-For isolates rate limiting state per test.
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<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 Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task GetAlbumTracksLite_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task GetAlbumTracksLite_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task GetAlbumTracksLite_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousAlbumId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<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, one of its albums and one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/we-are-the-champions-{Guid.NewGuid():N}.flac", title: "We Are the Champions", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="UpdateAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly UpdateAlbumRequestFixture _updateAlbumRequestFixture = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateAlbumEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<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}/albums/{albumId}", problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenUnauthorized_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateAlbum_WithSQLInjectionInBody_ShouldNotCorruptOrLeakData(string maliciousTitle)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: maliciousTitle), contributors: [], ratings: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request);
|
||||
|
||||
// Assert
|
||||
// The malicious title passes validation, reaches the parameterized update, and is persisted verbatim: if it were
|
||||
// concatenated into raw SQL, the update would fail and the album would not be updated.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
AlbumEntity? storedAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
|
||||
Assert.NotNull(storedAlbum);
|
||||
Assert.Equal(maliciousTitle, storedAlbum!.Title);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateAlbum_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", request);
|
||||
|
||||
// Assert
|
||||
await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateAlbum_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}", request);
|
||||
|
||||
// Assert
|
||||
await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateAlbum_WithSQLInjectionInAlbumRouteId_ShouldRemainSecure(string maliciousAlbumId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}", request);
|
||||
|
||||
// Assert
|
||||
await AssertCleanValidationErrorAsync(response, maliciousAlbumId, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
_seededUsernames.Add(ownerUsername);
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(ownerId);
|
||||
|
||||
HttpClient requesterClient = _apiFactory.CreateClient();
|
||||
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
|
||||
_seededUsernames.Add(requesterUsername);
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Dictionary<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 UpdateAlbum_WhenResourceBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(actingUsername);
|
||||
(Guid ownLibraryId, _, _) = await SeedLibraryArtistAndAlbumAsync(actingUserId);
|
||||
|
||||
// The resource lives in a library owned by another user, and is referenced through the acting user's own library route.
|
||||
HttpClient victimClient = _apiFactory.CreateClient();
|
||||
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
|
||||
_seededUsernames.Add(victimUsername);
|
||||
(_, Guid victimArtistId, Guid victimAlbumId) = await SeedLibraryArtistAndAlbumAsync(victimUserId);
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: "Hijacked"), contributors: [], ratings: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
|
||||
// The other user's album is untouched.
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
AlbumEntity? storedAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId);
|
||||
Assert.NotNull(storedAlbum);
|
||||
Assert.Equal("News of the World", storedAlbum.Title);
|
||||
}
|
||||
|
||||
/// <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 and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddAlbumCommandMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddAlbumCommandMappingTests
|
||||
{
|
||||
private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new();
|
||||
private readonly AddTrackCommandFixture _addTrackCommandFixture = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly IsrcDtoFixture _isrcDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Album> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Album album = result.Value;
|
||||
Assert.Equal(command.Metadata!.Title, album.Metadata.Title);
|
||||
Assert.Equal(command.MediaFormat, album.MediaFormat.Value);
|
||||
Assert.Equal(command.Barcode, album.Barcode.Value.Value);
|
||||
Assert.Equal(command.CatalogNumber, album.CatalogNumber.Value);
|
||||
Assert.Equal(command.MusicBrainzReleaseId, album.MusicBrainzReleaseId.Value.Value);
|
||||
Assert.Equal(command.MusicBrainzReleaseGroupId, album.MusicBrainzReleaseGroupId.Value.Value);
|
||||
Assert.Equal(command.MusicBrainzReleaseArtistId, album.MusicBrainzReleaseArtistId.Value.Value);
|
||||
Assert.Equal(command.Contributors!.Count, album.Contributors.Count);
|
||||
Assert.Equal(command.Ratings!.Count, album.Ratings.Count);
|
||||
Assert.Equal(command.Tracks!.Count, album.Tracks.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenAlbumIdIsProvided_ShouldReuseTheProvidedAlbumId()
|
||||
{
|
||||
// Arrange
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create(albumId: albumId);
|
||||
|
||||
// Act
|
||||
Result<Album> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(albumId, result.Value.Id.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenAlbumIdIsNotProvided_ShouldMintANewAlbumId()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand firstCommand = _addAlbumCommandFixture.Create();
|
||||
AddAlbumCommand secondCommand = _addAlbumCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Album> firstResult = firstCommand.ToDomainEntity();
|
||||
Result<Album> secondResult = secondCommand.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(firstResult.IsFailure);
|
||||
Assert.False(secondResult.IsFailure);
|
||||
// Two independent mappings must mint two distinct album Ids, instead of both collapsing to the same default value.
|
||||
Assert.NotEqual(firstResult.Value.Id.Value, secondResult.Value.Id.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNones()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create(
|
||||
includeMediaFormat: false,
|
||||
includeBarcode: false,
|
||||
includeCatalogNumber: false,
|
||||
includeMusicBrainzReleaseId: false,
|
||||
includeMusicBrainzReleaseGroupId: false,
|
||||
includeMusicBrainzReleaseArtistId: false,
|
||||
contributors: [],
|
||||
ratings: [],
|
||||
tracks: []);
|
||||
|
||||
// Act
|
||||
Result<Album> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Album album = result.Value;
|
||||
Assert.Equal(command.Metadata!.Title, album.Metadata.Title);
|
||||
Assert.False(album.MediaFormat.HasValue);
|
||||
Assert.False(album.Barcode.HasValue);
|
||||
Assert.False(album.CatalogNumber.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseId.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseGroupId.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseArtistId.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create(
|
||||
metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]));
|
||||
|
||||
// Act
|
||||
Result<Album> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenBarcodeCannotBeEmpty_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create(barcode: string.Empty);
|
||||
|
||||
// Act
|
||||
Result<Album> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.BarcodeValueCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenBarcodeHasInvalidFormat_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create(barcode: "not-a-barcode");
|
||||
|
||||
// Act
|
||||
Result<Album> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.InvalidFormatForBarcode, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)]);
|
||||
|
||||
// Act
|
||||
Result<Album> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTrackCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand invalidTrack = _addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(value: "invalid")]);
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [invalidTrack]);
|
||||
|
||||
// Act
|
||||
Result<Album> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.Music.IsrcInvalidFormat.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMultipleCommands_ShouldMapEachCommand()
|
||||
{
|
||||
// Arrange
|
||||
List<AddAlbumCommand> commands = _addAlbumCommandFixture.CreateMany(3);
|
||||
|
||||
// Act
|
||||
List<Result<Album>> results = [.. commands.ToDomainEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(commands.Count, results.Count);
|
||||
Assert.All(results, result => Assert.False(result.IsFailure));
|
||||
for (int i = 0; i < commands.Count; i++)
|
||||
{
|
||||
Assert.Equal(commands[i].Metadata!.Title, results[i].Value.Metadata.Title);
|
||||
Assert.Equal(commands[i].Tracks!.Count, results[i].Value.Tracks.Count);
|
||||
}
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddAlbumRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddAlbumRequestMappingTests
|
||||
{
|
||||
private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.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.Null(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();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.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].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
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(
|
||||
includeMediaFormat: false,
|
||||
includeBarcode: false,
|
||||
includeCatalogNumber: false,
|
||||
includeMusicBrainzReleaseId: false,
|
||||
includeMusicBrainzReleaseGroupId: false,
|
||||
includeMusicBrainzReleaseArtistId: false,
|
||||
includeTracks: false);
|
||||
|
||||
// Act
|
||||
AddAlbumCommand result = request.ToCommand(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result.Metadata);
|
||||
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
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.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<AddAlbumRequest> requests = _addAlbumRequestFixture.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].Tracks!.Count, result[i].Tracks!.Count);
|
||||
Assert.Equal(libraryId.ToString(), result[i].LibraryId);
|
||||
Assert.Equal(artistId.ToString(), result[i].ArtistId);
|
||||
}
|
||||
}
|
||||
}
|
||||
+344
@@ -0,0 +1,344 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AlbumEntityMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumEntityMappingTests
|
||||
{
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidAlbumEntity_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity entity = _albumEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Album> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Album album = result.Value;
|
||||
Assert.Equal(entity.Id, album.Id.Value);
|
||||
Assert.Equal(entity.Title, album.Metadata.Title);
|
||||
Assert.True(album.Metadata.OriginalTitle.HasValue);
|
||||
Assert.Equal(entity.OriginalTitle, album.Metadata.OriginalTitle.Value);
|
||||
Assert.True(album.Metadata.Description.HasValue);
|
||||
Assert.Equal(entity.Description, album.Metadata.Description.Value);
|
||||
Assert.Equal(entity.OriginalReleaseDate, album.Metadata.ReleaseInfo.OriginalReleaseDate.Value);
|
||||
Assert.Equal(entity.OriginalReleaseYear, album.Metadata.ReleaseInfo.OriginalReleaseYear.Value);
|
||||
Assert.Equal(entity.ReReleaseDate, album.Metadata.ReleaseInfo.ReReleaseDate.Value);
|
||||
Assert.Equal(entity.ReReleaseYear, album.Metadata.ReleaseInfo.ReReleaseYear.Value);
|
||||
Assert.Equal(entity.ReleaseCountry, album.Metadata.ReleaseInfo.ReleaseCountry.Value);
|
||||
Assert.Equal(entity.ReleaseVersion, album.Metadata.ReleaseInfo.ReleaseVersion.Value);
|
||||
Assert.Equal(entity.Genres.Select(genre => genre.Name).OrderBy(name => name), album.Metadata.Genres.Select(genre => genre.Name).OrderBy(name => name));
|
||||
Assert.Equal(entity.Tags.Select(tag => tag.Name).OrderBy(name => name), album.Metadata.Tags.Select(tag => tag.Name).OrderBy(name => name));
|
||||
Assert.True(album.Metadata.Language.HasValue);
|
||||
Assert.Equal(entity.LanguageCode!.ToLowerInvariant(), album.Metadata.Language.Value.LanguageCode);
|
||||
Assert.Equal(entity.LanguageName, album.Metadata.Language.Value.LanguageName);
|
||||
Assert.Equal(entity.LanguageNativeName, album.Metadata.Language.Value.NativeName.Value);
|
||||
Assert.True(album.Metadata.OriginalLanguage.HasValue);
|
||||
Assert.Equal(entity.OriginalLanguageCode!.ToLowerInvariant(), album.Metadata.OriginalLanguage.Value.LanguageCode);
|
||||
Assert.Equal(entity.OriginalLanguageName, album.Metadata.OriginalLanguage.Value.LanguageName);
|
||||
Assert.Equal(entity.OriginalLanguageNativeName, album.Metadata.OriginalLanguage.Value.NativeName.Value);
|
||||
Assert.Equal(entity.ReleaseType, album.Metadata.ReleaseType.Value);
|
||||
Assert.Equal(entity.ReleaseStatus, album.Metadata.ReleaseStatus.Value);
|
||||
Assert.Equal(entity.TotalDiscs, album.Metadata.TotalDiscs.Value);
|
||||
Assert.Equal(entity.TotalTracks, album.Metadata.TotalTracks);
|
||||
Assert.Equal(entity.MediaFormat, album.MediaFormat.Value);
|
||||
Assert.Equal(entity.Barcode, album.Barcode.Value.Value);
|
||||
Assert.Equal(entity.CatalogNumber, album.CatalogNumber.Value);
|
||||
Assert.Equal(entity.MusicBrainzReleaseId, album.MusicBrainzReleaseId.Value.Value);
|
||||
Assert.Equal(entity.MusicBrainzReleaseGroupId, album.MusicBrainzReleaseGroupId.Value.Value);
|
||||
Assert.Equal(entity.MusicBrainzReleaseArtistId, album.MusicBrainzReleaseArtistId.Value.Value);
|
||||
Assert.Equal(entity.Contributors.Select(contributor => contributor.MediaContributorId), album.Contributors.Select(contributor => contributor.ContributorId.Value));
|
||||
Assert.Equal(entity.Contributors.Select(contributor => contributor.Role), album.Contributors.Select(contributor => contributor.Role));
|
||||
Assert.Equal(entity.Ratings.Select(rating => rating.Value), album.Ratings.Select(rating => (decimal?)rating.Value));
|
||||
Assert.Equal(entity.Tracks.Select(track => track.Id), album.Tracks.Select(track => track.Id.Value));
|
||||
Assert.Equal(entity.CreatedOnUtc, album.CreatedOnUtc);
|
||||
Assert.Equal(entity.UpdatedOnUtc, album.UpdatedOnUtc.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNones()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity entity = _albumEntityFixture.Create(
|
||||
includeMetadata: false,
|
||||
includeTracks: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalTitle: false,
|
||||
includeDescription: false,
|
||||
includeLanguage: false,
|
||||
includeOriginalLanguage: false,
|
||||
includeReleaseType: false,
|
||||
includeReleaseStatus: false,
|
||||
includeTotalDiscs: false,
|
||||
includeMediaFormat: false,
|
||||
includeCatalogNumber: false,
|
||||
includeMusicBrainzReleaseId: false,
|
||||
includeMusicBrainzReleaseGroupId: false,
|
||||
includeMusicBrainzReleaseArtistId: false);
|
||||
|
||||
// Act
|
||||
Result<Album> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Album album = result.Value;
|
||||
Assert.False(album.Metadata.OriginalTitle.HasValue);
|
||||
Assert.False(album.Metadata.Description.HasValue);
|
||||
Assert.False(album.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue);
|
||||
Assert.False(album.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue);
|
||||
Assert.False(album.Metadata.ReleaseInfo.ReReleaseDate.HasValue);
|
||||
Assert.False(album.Metadata.ReleaseInfo.ReReleaseYear.HasValue);
|
||||
Assert.Empty(album.Metadata.Genres);
|
||||
Assert.Empty(album.Metadata.Tags);
|
||||
Assert.False(album.Metadata.Language.HasValue);
|
||||
Assert.False(album.Metadata.OriginalLanguage.HasValue);
|
||||
Assert.False(album.Metadata.ReleaseType.HasValue);
|
||||
Assert.False(album.Metadata.ReleaseStatus.HasValue);
|
||||
Assert.False(album.Metadata.TotalDiscs.HasValue);
|
||||
Assert.False(album.MediaFormat.HasValue);
|
||||
Assert.False(album.Barcode.HasValue);
|
||||
Assert.False(album.CatalogNumber.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseId.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseGroupId.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseArtistId.HasValue);
|
||||
Assert.Empty(album.Contributors);
|
||||
Assert.Empty(album.Ratings);
|
||||
Assert.Empty(album.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenReleaseInfoIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity entity = _albumEntityFixture.Create(
|
||||
originalReleaseDate: new DateOnly(2000, 1, 1),
|
||||
originalReleaseYear: 1999);
|
||||
|
||||
// Act
|
||||
Result<Album> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity entity = _albumEntityFixture.Create();
|
||||
entity.Genres = [_genreEntityFixture.Create(name: string.Empty)];
|
||||
|
||||
// Act
|
||||
Result<Album> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTagIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity entity = _albumEntityFixture.Create();
|
||||
entity.Tags = [_tagEntityFixture.Create(name: " ")];
|
||||
|
||||
// Act
|
||||
Result<Album> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenBarcodeCannotBeEmpty_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity entity = _albumEntityFixture.Create(barcode: string.Empty);
|
||||
|
||||
// Act
|
||||
Result<Album> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.BarcodeValueCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenBarcodeHasInvalidFormat_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity entity = _albumEntityFixture.Create(barcode: "not-a-barcode");
|
||||
|
||||
// Act
|
||||
Result<Album> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.InvalidFormatForBarcode, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenRatingIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity entity = _albumEntityFixture.Create();
|
||||
entity.Ratings = [_audioRatingEntityFixture.Create(value: 6, maxValue: 5)];
|
||||
|
||||
// Act
|
||||
Result<Album> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTrackIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity trackEntity = _trackEntityFixture.Create();
|
||||
trackEntity.Isrcs = [new TrackIsrcEntity("not-an-isrc")];
|
||||
AlbumEntity entity = _albumEntityFixture.Create(tracks: [trackEntity]);
|
||||
|
||||
// Act
|
||||
Result<Album> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.IsrcInvalidFormat, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingAlbumEntity_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity entity = _albumEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
AlbumResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(entity.Id, result.Id);
|
||||
Assert.Equal(entity.ArtistId, result.ArtistId);
|
||||
Assert.Equal(entity.LibraryId, result.LibraryId);
|
||||
Assert.Equal(entity.Title, result.Metadata.Title);
|
||||
Assert.Equal(entity.OriginalTitle, result.Metadata.OriginalTitle);
|
||||
Assert.Equal(entity.Description, result.Metadata.Description);
|
||||
Assert.Equal(entity.OriginalReleaseDate, result.Metadata.ReleaseInfo!.OriginalReleaseDate);
|
||||
Assert.Equal(entity.OriginalReleaseYear, result.Metadata.ReleaseInfo.OriginalReleaseYear);
|
||||
Assert.Equal(entity.ReReleaseDate, result.Metadata.ReleaseInfo.ReReleaseDate);
|
||||
Assert.Equal(entity.ReReleaseYear, result.Metadata.ReleaseInfo.ReReleaseYear);
|
||||
Assert.Equal(entity.ReleaseCountry, result.Metadata.ReleaseInfo.ReleaseCountry);
|
||||
Assert.Equal(entity.ReleaseVersion, result.Metadata.ReleaseInfo.ReleaseVersion);
|
||||
Assert.NotNull(result.Metadata.Language);
|
||||
Assert.Equal(entity.LanguageCode, result.Metadata.Language!.LanguageCode);
|
||||
Assert.Equal(entity.LanguageName, result.Metadata.Language.LanguageName);
|
||||
Assert.Equal(entity.LanguageNativeName, result.Metadata.Language.NativeName);
|
||||
Assert.NotNull(result.Metadata.OriginalLanguage);
|
||||
Assert.Equal(entity.OriginalLanguageCode, result.Metadata.OriginalLanguage!.LanguageCode);
|
||||
Assert.Equal(entity.OriginalLanguageName, result.Metadata.OriginalLanguage.LanguageName);
|
||||
Assert.Equal(entity.OriginalLanguageNativeName, result.Metadata.OriginalLanguage.NativeName);
|
||||
Assert.Equal(entity.Tags.Select(tag => tag.Name).OrderBy(name => name), result.Metadata.Tags!.Select(tag => tag.Name).OrderBy(name => name));
|
||||
Assert.Equal(entity.Genres.Select(genre => genre.Name).OrderBy(name => name), result.Metadata.Genres!.Select(genre => genre.Name).OrderBy(name => name));
|
||||
Assert.Equal(entity.ReleaseType, result.Metadata.ReleaseType);
|
||||
Assert.Equal(entity.ReleaseStatus, result.Metadata.ReleaseStatus);
|
||||
Assert.Equal(entity.TotalDiscs, result.Metadata.TotalDiscs);
|
||||
Assert.Equal(entity.TotalTracks, result.Metadata.TotalTracks);
|
||||
Assert.Equal(entity.MediaFormat, result.MediaFormat);
|
||||
Assert.Equal(entity.Barcode, result.Barcode);
|
||||
Assert.Equal(entity.CatalogNumber, result.CatalogNumber);
|
||||
Assert.Equal(entity.MusicBrainzReleaseId, result.MusicBrainzReleaseId);
|
||||
Assert.Equal(entity.MusicBrainzReleaseGroupId, result.MusicBrainzReleaseGroupId);
|
||||
Assert.Equal(entity.MusicBrainzReleaseArtistId, result.MusicBrainzReleaseArtistId);
|
||||
Assert.Equal(entity.CreatedOnUtc, result.CreatedOnUtc);
|
||||
Assert.Equal(entity.UpdatedOnUtc, result.UpdatedOnUtc);
|
||||
Assert.Equal(entity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role)), result.Contributors);
|
||||
Assert.Equal(entity.Ratings.Select(rating => new AudioRatingDto(rating.Value, rating.MaxValue, rating.Source, rating.VoteCount)), result.Ratings);
|
||||
Assert.Equal(entity.Tracks.Select(track => track.Id), result.Tracks!.Select(track => track.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenLanguageSubpropertiesAreBlank_ShouldMapLanguagesToNull()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity entity = _albumEntityFixture.Create(includeLanguage: false, includeOriginalLanguage: false);
|
||||
|
||||
// Act
|
||||
AlbumResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Metadata.Language);
|
||||
Assert.Null(result.Metadata.OriginalLanguage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMetadataCollectionsAreEmpty_ShouldMapEmptyCollections()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity entity = _albumEntityFixture.Create(includeMetadata: false, includeTracks: false);
|
||||
|
||||
// Act
|
||||
AlbumResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Contributors!);
|
||||
Assert.Empty(result.Ratings!);
|
||||
Assert.Empty(result.Tracks!);
|
||||
Assert.Empty(result.Metadata.Tags!);
|
||||
Assert.Empty(result.Metadata.Genres!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleAlbumEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<AlbumEntity> entities = _albumEntityFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<AlbumResponse> 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].Title, results[i].Metadata.Title);
|
||||
}
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AlbumLiteRowMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumLiteRowMappingTests
|
||||
{
|
||||
private readonly AlbumLiteRowFixture _albumLiteRowFixture = new();
|
||||
private readonly PaginatedResultDtoFixture<AlbumLiteRow> _paginatedResultDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingAlbumLiteRow_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AlbumLiteRow readModel = _albumLiteRowFixture.Create();
|
||||
|
||||
// Act
|
||||
AlbumLiteResponse result = readModel.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(readModel.Id, result.Id);
|
||||
Assert.Equal(readModel.Title, result.Title);
|
||||
Assert.Equal(readModel.TotalTracks, result.TotalTracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleAlbumLiteRows_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<AlbumLiteRow> readModels = _albumLiteRowFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<AlbumLiteResponse> 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.Title), results.Select(response => response.Title));
|
||||
Assert.Equal(readModels.Select(readModel => readModel.TotalTracks), results.Select(response => response.TotalTracks));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingPaginatedAlbumLiteRows_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<AlbumLiteRow> readModels = _albumLiteRowFixture.CreateMany(2);
|
||||
PaginatedResultDto<AlbumLiteRow> paginatedReadModels = _paginatedResultDtoFixture.Create(
|
||||
data: readModels,
|
||||
currentPage: 1,
|
||||
perPage: 10,
|
||||
count: 2,
|
||||
numberOfPages: 1);
|
||||
|
||||
// Act
|
||||
PaginatedResponse<AlbumLiteResponse> 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);
|
||||
}
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
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.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AlbumMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumMappingTests
|
||||
{
|
||||
private readonly AlbumFixture _albumFixture = new();
|
||||
private readonly TrackFixture _trackFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingCompleteAlbum_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Album album = _albumFixture.Create();
|
||||
|
||||
// Act
|
||||
AlbumEntity result = album.ToRepositoryEntity(artistId, libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(album.Id.Value, result.Id);
|
||||
Assert.Equal(artistId, result.ArtistId);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
Assert.Equal(album.Metadata.Title, result.Title);
|
||||
Assert.Equal(album.Metadata.OriginalTitle.HasValue ? album.Metadata.OriginalTitle.Value : null, result.OriginalTitle);
|
||||
Assert.Equal(album.Metadata.Description.HasValue ? album.Metadata.Description.Value : null, result.Description);
|
||||
Assert.Equal(album.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue ? album.Metadata.ReleaseInfo.OriginalReleaseDate.Value : null, result.OriginalReleaseDate);
|
||||
Assert.Equal(album.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue ? album.Metadata.ReleaseInfo.OriginalReleaseYear.Value : null, result.OriginalReleaseYear);
|
||||
Assert.Equal(album.Metadata.ReleaseInfo.ReReleaseDate.HasValue ? album.Metadata.ReleaseInfo.ReReleaseDate.Value : null, result.ReReleaseDate);
|
||||
Assert.Equal(album.Metadata.ReleaseInfo.ReReleaseYear.HasValue ? album.Metadata.ReleaseInfo.ReReleaseYear.Value : null, result.ReReleaseYear);
|
||||
Assert.Equal(album.Metadata.ReleaseInfo.ReleaseCountry.HasValue ? album.Metadata.ReleaseInfo.ReleaseCountry.Value : null, result.ReleaseCountry);
|
||||
Assert.Equal(album.Metadata.ReleaseInfo.ReleaseVersion.HasValue ? album.Metadata.ReleaseInfo.ReleaseVersion.Value : null, result.ReleaseVersion);
|
||||
Assert.Equal(album.Metadata.Language.HasValue ? album.Metadata.Language.Value.LanguageCode : null, result.LanguageCode);
|
||||
Assert.Equal(album.Metadata.Language.HasValue ? album.Metadata.Language.Value.LanguageName : null, result.LanguageName);
|
||||
Assert.Equal(album.Metadata.Language.HasValue && album.Metadata.Language.Value.NativeName.HasValue ? album.Metadata.Language.Value.NativeName.Value : null, result.LanguageNativeName);
|
||||
Assert.Equal(album.Metadata.OriginalLanguage.HasValue ? album.Metadata.OriginalLanguage.Value.LanguageCode : null, result.OriginalLanguageCode);
|
||||
Assert.Equal(album.Metadata.OriginalLanguage.HasValue ? album.Metadata.OriginalLanguage.Value.LanguageName : null, result.OriginalLanguageName);
|
||||
Assert.Equal(album.Metadata.OriginalLanguage.HasValue && album.Metadata.OriginalLanguage.Value.NativeName.HasValue ? album.Metadata.OriginalLanguage.Value.NativeName.Value : null, result.OriginalLanguageNativeName);
|
||||
Assert.Equal(album.Metadata.Genres.ToRepositoryEntities().Distinct().Select(genre => genre.Name).OrderBy(name => name), result.Genres.Select(genre => genre.Name).OrderBy(name => name));
|
||||
Assert.Equal(album.Metadata.Tags.ToRepositoryEntities().Distinct().Select(tag => tag.Name).OrderBy(name => name), result.Tags.Select(tag => tag.Name).OrderBy(name => name));
|
||||
Assert.Equal(album.Metadata.ReleaseType.HasValue ? album.Metadata.ReleaseType.Value : null, result.ReleaseType);
|
||||
Assert.Equal(album.Metadata.ReleaseStatus.HasValue ? album.Metadata.ReleaseStatus.Value : null, result.ReleaseStatus);
|
||||
Assert.Equal(album.Metadata.TotalDiscs.HasValue ? album.Metadata.TotalDiscs.Value : null, result.TotalDiscs);
|
||||
Assert.Equal(album.Metadata.TotalTracks, result.TotalTracks);
|
||||
Assert.Equal(album.MediaFormat.HasValue ? album.MediaFormat.Value : null, result.MediaFormat);
|
||||
Assert.Equal(album.Barcode.HasValue ? album.Barcode.Value.Value : null, result.Barcode);
|
||||
Assert.Equal(album.CatalogNumber.HasValue ? album.CatalogNumber.Value : null, result.CatalogNumber);
|
||||
Assert.Equal(album.MusicBrainzReleaseId.HasValue ? album.MusicBrainzReleaseId.Value.Value : null, result.MusicBrainzReleaseId);
|
||||
Assert.Equal(album.MusicBrainzReleaseGroupId.HasValue ? album.MusicBrainzReleaseGroupId.Value.Value : null, result.MusicBrainzReleaseGroupId);
|
||||
Assert.Equal(album.MusicBrainzReleaseArtistId.HasValue ? album.MusicBrainzReleaseArtistId.Value.Value : null, result.MusicBrainzReleaseArtistId);
|
||||
Assert.Equal(album.Ratings.ToRepositoryEntities(), result.Ratings);
|
||||
Assert.Equal(album.CreatedOnUtc, result.CreatedOnUtc);
|
||||
Assert.Equal(Guid.Empty, result.CreatedBy);
|
||||
Assert.Null(result.UpdatedOnUtc);
|
||||
Assert.Null(result.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingContributors_ShouldCreateAContributorEntityPerContributor()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Album album = _albumFixture.Create();
|
||||
|
||||
// Act
|
||||
AlbumEntity result = album.ToRepositoryEntity(artistId, libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(album.Contributors.Count, result.Contributors.Count);
|
||||
for (int i = 0; i < album.Contributors.Count; i++)
|
||||
{
|
||||
MusicMediaContributor contributor = album.Contributors.ElementAt(i);
|
||||
AlbumContributorEntity contributorEntity = result.Contributors[i];
|
||||
Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId);
|
||||
Assert.Equal(contributor.Role, contributorEntity.Role);
|
||||
Assert.Equal(album.Id.Value, contributorEntity.AlbumId);
|
||||
Assert.Equal(album.CreatedOnUtc, contributorEntity.CreatedOnUtc);
|
||||
Assert.Equal(Guid.Empty, contributorEntity.CreatedBy);
|
||||
Assert.Null(contributorEntity.UpdatedBy);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingTracks_ShouldCreateATrackEntityPerTrackBelongingToTheAlbumAndLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Album album = _albumFixture.Create(tracks: _trackFixture.CreateMany(2));
|
||||
|
||||
// Act
|
||||
AlbumEntity result = album.ToRepositoryEntity(artistId, libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Tracks.Count);
|
||||
for (int i = 0; i < album.Tracks.Count; i++)
|
||||
{
|
||||
Track track = album.Tracks.ElementAt(i);
|
||||
TrackEntity trackEntity = result.Tracks[i];
|
||||
Assert.Equal(track.Id.Value, trackEntity.Id);
|
||||
Assert.Equal(album.Id.Value, trackEntity.AlbumId);
|
||||
Assert.Equal(libraryId, trackEntity.LibraryId);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNulls()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
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(),
|
||||
contributors: [],
|
||||
ratings: [],
|
||||
tracks: []);
|
||||
|
||||
// Act
|
||||
AlbumEntity result = album.ToRepositoryEntity(artistId, libraryId);
|
||||
|
||||
// Assert
|
||||
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.Empty(result.Contributors);
|
||||
Assert.Empty(result.Ratings);
|
||||
Assert.Empty(result.Tracks);
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AlbumMetadataDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumMetadataDtoMappingTests
|
||||
{
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly TagDtoFixture _tagDtoFixture = new();
|
||||
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
|
||||
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AlbumMetadataDto dto = _albumMetadataDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<AlbumMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumMetadata metadata = result.Value;
|
||||
Assert.Equal(dto.Title, metadata.Title);
|
||||
Assert.True(metadata.OriginalTitle.HasValue);
|
||||
Assert.Equal(dto.OriginalTitle, metadata.OriginalTitle.Value);
|
||||
Assert.True(metadata.Description.HasValue);
|
||||
Assert.Equal(dto.Description, metadata.Description.Value);
|
||||
Assert.True(metadata.ReleaseInfo.OriginalReleaseDate.HasValue);
|
||||
Assert.Equal(dto.ReleaseInfo!.OriginalReleaseDate, metadata.ReleaseInfo.OriginalReleaseDate.Value);
|
||||
Assert.True(metadata.ReleaseInfo.OriginalReleaseYear.HasValue);
|
||||
Assert.Equal(dto.ReleaseInfo.OriginalReleaseYear, metadata.ReleaseInfo.OriginalReleaseYear.Value);
|
||||
Assert.True(metadata.ReleaseInfo.ReReleaseDate.HasValue);
|
||||
Assert.Equal(dto.ReleaseInfo.ReReleaseDate, metadata.ReleaseInfo.ReReleaseDate.Value);
|
||||
Assert.True(metadata.ReleaseInfo.ReReleaseYear.HasValue);
|
||||
Assert.Equal(dto.ReleaseInfo.ReReleaseYear, metadata.ReleaseInfo.ReReleaseYear.Value);
|
||||
Assert.True(metadata.ReleaseInfo.ReleaseCountry.HasValue);
|
||||
Assert.Equal(dto.ReleaseInfo.ReleaseCountry, metadata.ReleaseInfo.ReleaseCountry.Value);
|
||||
Assert.True(metadata.ReleaseInfo.ReleaseVersion.HasValue);
|
||||
Assert.Equal(dto.ReleaseInfo.ReleaseVersion, metadata.ReleaseInfo.ReleaseVersion.Value);
|
||||
Assert.True(metadata.Language.HasValue);
|
||||
Assert.Equal(dto.Language!.LanguageCode!.ToLowerInvariant(), metadata.Language.Value.LanguageCode);
|
||||
Assert.Equal(dto.Language.LanguageName, metadata.Language.Value.LanguageName);
|
||||
Assert.Equal(dto.Language.NativeName, metadata.Language.Value.NativeName.Value);
|
||||
Assert.True(metadata.OriginalLanguage.HasValue);
|
||||
Assert.Equal(dto.OriginalLanguage!.LanguageCode!.ToLowerInvariant(), metadata.OriginalLanguage.Value.LanguageCode);
|
||||
Assert.Equal(dto.OriginalLanguage.LanguageName, metadata.OriginalLanguage.Value.LanguageName);
|
||||
Assert.Equal(dto.OriginalLanguage.NativeName, metadata.OriginalLanguage.Value.NativeName.Value);
|
||||
Assert.Equal(dto.Genres!.Select(genre => genre.Name), metadata.Genres.Select(genre => genre.Name));
|
||||
Assert.Equal(dto.Tags!.Select(tag => tag.Name), metadata.Tags.Select(tag => tag.Name));
|
||||
Assert.True(metadata.ReleaseType.HasValue);
|
||||
Assert.Equal(dto.ReleaseType, metadata.ReleaseType.Value);
|
||||
Assert.True(metadata.ReleaseStatus.HasValue);
|
||||
Assert.Equal(dto.ReleaseStatus, metadata.ReleaseStatus.Value);
|
||||
Assert.True(metadata.TotalDiscs.HasValue);
|
||||
Assert.Equal(dto.TotalDiscs, metadata.TotalDiscs.Value);
|
||||
Assert.Equal(dto.TotalTracks, metadata.TotalTracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults()
|
||||
{
|
||||
// Arrange
|
||||
AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(
|
||||
includeOriginalTitle: false,
|
||||
includeDescription: false,
|
||||
includeReleaseInfo: false,
|
||||
includeLanguage: false,
|
||||
includeOriginalLanguage: false,
|
||||
includeTags: false,
|
||||
includeGenres: false,
|
||||
includeReleaseType: false,
|
||||
includeReleaseStatus: false,
|
||||
includeTotalDiscs: false,
|
||||
includeTotalTracks: false);
|
||||
|
||||
// Act
|
||||
Result<AlbumMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumMetadata metadata = result.Value;
|
||||
Assert.Equal(dto.Title, metadata.Title);
|
||||
Assert.False(metadata.OriginalTitle.HasValue);
|
||||
Assert.False(metadata.Description.HasValue);
|
||||
Assert.False(metadata.ReleaseInfo.OriginalReleaseDate.HasValue);
|
||||
Assert.False(metadata.ReleaseInfo.OriginalReleaseYear.HasValue);
|
||||
Assert.False(metadata.ReleaseInfo.ReReleaseDate.HasValue);
|
||||
Assert.False(metadata.ReleaseInfo.ReReleaseYear.HasValue);
|
||||
Assert.False(metadata.ReleaseInfo.ReleaseCountry.HasValue);
|
||||
Assert.False(metadata.ReleaseInfo.ReleaseVersion.HasValue);
|
||||
Assert.False(metadata.Language.HasValue);
|
||||
Assert.False(metadata.OriginalLanguage.HasValue);
|
||||
Assert.Empty(metadata.Genres);
|
||||
Assert.Empty(metadata.Tags);
|
||||
Assert.False(metadata.ReleaseType.HasValue);
|
||||
Assert.False(metadata.ReleaseStatus.HasValue);
|
||||
Assert.False(metadata.TotalDiscs.HasValue);
|
||||
Assert.Equal(0, metadata.TotalTracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenLanguageIsMissingRequiredSubproperties_ShouldMapLanguageToNone()
|
||||
{
|
||||
// Arrange
|
||||
LanguageInfoDto incompleteLanguage = _languageInfoDtoFixture.Create(includeLanguageCode: false);
|
||||
AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(
|
||||
language: incompleteLanguage,
|
||||
originalLanguage: _languageInfoDtoFixture.Create(includeLanguageName: false));
|
||||
|
||||
// Act
|
||||
Result<AlbumMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.Language.HasValue);
|
||||
Assert.False(result.Value.OriginalLanguage.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenReleaseInfoIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfoDto releaseInfo = _releaseInfoDtoFixture.Create(
|
||||
originalReleaseDate: new DateOnly(2000, 1, 1),
|
||||
originalReleaseYear: 1999);
|
||||
AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(releaseInfo: releaseInfo);
|
||||
|
||||
// Act
|
||||
Result<AlbumMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]);
|
||||
|
||||
// Act
|
||||
Result<AlbumMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTagIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: " ")]);
|
||||
|
||||
// Act
|
||||
Result<AlbumMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
|
||||
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.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateAlbumCommandMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumCommandMappingTests
|
||||
{
|
||||
private readonly UpdateAlbumCommandFixture _updateAlbumCommandFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId) = CreateDomainArtist(libraryId);
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString());
|
||||
|
||||
// Act
|
||||
Result<Artist> result = command.ToDomainEntity(artist);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(artist, result.Value);
|
||||
Album updatedAlbum = result.Value.Albums.First(album => album.Id.Value == albumId);
|
||||
Assert.Equal(command.Metadata!.Title, updatedAlbum.Metadata.Title);
|
||||
Assert.Equal(command.MediaFormat, updatedAlbum.MediaFormat.Value);
|
||||
Assert.Equal(command.Barcode, updatedAlbum.Barcode.Value.Value);
|
||||
Assert.Equal(command.CatalogNumber, updatedAlbum.CatalogNumber.Value);
|
||||
Assert.Equal(command.MusicBrainzReleaseId, updatedAlbum.MusicBrainzReleaseId.Value.Value);
|
||||
Assert.Equal(command.MusicBrainzReleaseGroupId, updatedAlbum.MusicBrainzReleaseGroupId.Value.Value);
|
||||
Assert.Equal(command.MusicBrainzReleaseArtistId, updatedAlbum.MusicBrainzReleaseArtistId.Value.Value);
|
||||
Assert.Equal(command.Contributors!.Count, updatedAlbum.Contributors.Count);
|
||||
Assert.Equal(command.Ratings!.Count, updatedAlbum.Ratings.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredPropertiesAndNones()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId) = CreateDomainArtist(libraryId);
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
artistId: artist.Id.Value.ToString(),
|
||||
albumId: albumId.ToString(),
|
||||
includeMediaFormat: false,
|
||||
includeBarcode: false,
|
||||
includeCatalogNumber: false,
|
||||
includeMusicBrainzReleaseId: false,
|
||||
includeMusicBrainzReleaseGroupId: false,
|
||||
includeMusicBrainzReleaseArtistId: false,
|
||||
contributors: [],
|
||||
ratings: []);
|
||||
|
||||
// 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(command.Metadata!.Title, updatedAlbum.Metadata.Title);
|
||||
Assert.False(updatedAlbum.MediaFormat.HasValue);
|
||||
Assert.False(updatedAlbum.Barcode.HasValue);
|
||||
Assert.False(updatedAlbum.CatalogNumber.HasValue);
|
||||
Assert.False(updatedAlbum.MusicBrainzReleaseId.HasValue);
|
||||
Assert.False(updatedAlbum.MusicBrainzReleaseGroupId.HasValue);
|
||||
Assert.False(updatedAlbum.MusicBrainzReleaseArtistId.HasValue);
|
||||
Assert.Empty(updatedAlbum.Contributors);
|
||||
Assert.Empty(updatedAlbum.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId) = CreateDomainArtist(libraryId);
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
artistId: artist.Id.Value.ToString(),
|
||||
albumId: albumId.ToString(),
|
||||
metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]));
|
||||
|
||||
// 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_WhenRatingCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId) = CreateDomainArtist(libraryId);
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
artistId: artist.Id.Value.ToString(),
|
||||
albumId: albumId.ToString(),
|
||||
ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)]);
|
||||
|
||||
// Act
|
||||
Result<Artist> result = command.ToDomainEntity(artist);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenBarcodeCannotBeEmpty_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId) = CreateDomainArtist(libraryId);
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
artistId: artist.Id.Value.ToString(),
|
||||
albumId: albumId.ToString(),
|
||||
barcode: string.Empty);
|
||||
|
||||
// Act
|
||||
Result<Artist> result = command.ToDomainEntity(artist);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.BarcodeValueCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenBarcodeHasInvalidFormat_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId) = CreateDomainArtist(libraryId);
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
artistId: artist.Id.Value.ToString(),
|
||||
albumId: albumId.ToString(),
|
||||
barcode: "not-a-barcode");
|
||||
|
||||
// Act
|
||||
Result<Artist> result = command.ToDomainEntity(artist);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.InvalidFormatForBarcode, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenAlbumIsNotPartOfTheArtist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid _) = CreateDomainArtist(libraryId);
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
artistId: artist.Id.Value.ToString(),
|
||||
albumId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
Result<Artist> result = command.ToDomainEntity(artist);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a domain artist that owns a single album 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 Id of its album.</returns>
|
||||
private (Artist artist, Guid albumId) CreateDomainArtist(Guid libraryId)
|
||||
{
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, libraryId: libraryId, includeTracks: false);
|
||||
ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]);
|
||||
Result<Artist> artistResult = artistEntity.ToDomainEntity();
|
||||
return (artistResult.Value, albumId);
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateAlbumRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumRequestMappingTests
|
||||
{
|
||||
private readonly UpdateAlbumRequestFixture _updateAlbumRequestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
UpdateAlbumCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString(), albumId.ToString());
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(libraryId.ToString(), result.LibraryId);
|
||||
Assert.Equal(artistId.ToString(), result.ArtistId);
|
||||
Assert.Equal(albumId.ToString(), result.AlbumId);
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredPropertiesAndNulls()
|
||||
{
|
||||
// Arrange
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(
|
||||
includeMediaFormat: false,
|
||||
includeBarcode: false,
|
||||
includeCatalogNumber: false,
|
||||
includeMusicBrainzReleaseId: false,
|
||||
includeMusicBrainzReleaseGroupId: false,
|
||||
includeMusicBrainzReleaseArtistId: false);
|
||||
|
||||
// Act
|
||||
UpdateAlbumCommand result = request.ToCommand(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result.Metadata);
|
||||
Assert.Null(result.MediaFormat);
|
||||
Assert.Null(result.Barcode);
|
||||
Assert.Null(result.CatalogNumber);
|
||||
Assert.Null(result.MusicBrainzReleaseId);
|
||||
Assert.Null(result.MusicBrainzReleaseGroupId);
|
||||
Assert.Null(result.MusicBrainzReleaseArtistId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenRouteIdsAreNull_ShouldMapNullRouteIds()
|
||||
{
|
||||
// Arrange
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
UpdateAlbumCommand result = request.ToCommand(null, null, null);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.LibraryId);
|
||||
Assert.Null(result.ArtistId);
|
||||
Assert.Null(result.AlbumId);
|
||||
}
|
||||
}
|
||||
+532
@@ -0,0 +1,532 @@
|
||||
#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.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.Tracks.Commands.AddTrack;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
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.Albums.Commands.AddAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddAlbumCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddAlbumCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IArtistRepository _mockArtistRepository;
|
||||
private readonly IAlbumRepository _mockAlbumRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IMediaContributorRepository _mockMediaContributorRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<AddAlbumCommand> _mockValidator;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly AddAlbumCommandHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
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();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddAlbumCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public AddAlbumCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockArtistRepository = Substitute.For<IArtistRepository>();
|
||||
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<AddAlbumCommand>>();
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
|
||||
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
|
||||
_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<AddAlbumCommand>()).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);
|
||||
// Default stub: the persisted album can be read back by its Id.
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Result.From<AlbumEntity?>(_albumEntityFixture.Create(id: callInfo.Arg<Guid>(), includeTracks: false)));
|
||||
|
||||
_sut = new AddAlbumCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<AddAlbumCommand>()).Returns([Errors.Music.AlbumTitleCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumTitleCannotBeEmpty, 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
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<ArtistEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: Guid.NewGuid());
|
||||
StubExistingArtist(artist);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId));
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId));
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<LibraryEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId));
|
||||
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackPathMustBeWithinLibraryContentLocations, result.FirstError);
|
||||
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
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]);
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId));
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]);
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId));
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([]));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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 command = _addAlbumCommandFixture.Create(contributors: [], tracks: [_addTrackCommandFixture.Create(contributors: [])]);
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: string.Empty));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]));
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError);
|
||||
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheArtistAlreadyHasTheAlbum_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity existingAlbum = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false);
|
||||
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: [existingAlbum], includeContributors: false);
|
||||
StubExistingArtist(artist);
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TheArtistAlreadyHasTheAlbum, 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
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId));
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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_ShouldReturnFailureResultWithoutReadingTheAlbum()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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 _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPersistedAlbumCannotBeRead_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId));
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPersistedAlbumDoesNotExist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId));
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<AlbumEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalledWithValidCommand_ShouldPersistTheAlbumAndReturnItsResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid existingAlbumId = Guid.NewGuid();
|
||||
AlbumEntity existingAlbum = _albumEntityFixture.Create(id: existingAlbumId, artistId: artistId, libraryId: libraryId, includeTracks: false);
|
||||
ArtistEntity existingArtist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: [existingAlbum], includeContributors: false);
|
||||
StubExistingArtist(existingArtist);
|
||||
AddAlbumCommand command = _addAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString());
|
||||
ArtistEntity? updatedArtist = null;
|
||||
AlbumEntity? persistedAlbum = null;
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
updatedArtist = callInfo.Arg<ArtistEntity>();
|
||||
return Result.Updated;
|
||||
});
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
persistedAlbum = _albumEntityFixture.Create(id: callInfo.Arg<Guid>(), artistId: artistId, libraryId: libraryId, includeTracks: false);
|
||||
return Result.From<AlbumEntity?>(persistedAlbum);
|
||||
});
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(updatedArtist);
|
||||
Assert.NotNull(persistedAlbum);
|
||||
Assert.Equal(persistedAlbum!.Id, result.Value.Id);
|
||||
Assert.Equal(persistedAlbum.ArtistId, result.Value.ArtistId);
|
||||
Assert.Equal(persistedAlbum.LibraryId, result.Value.LibraryId);
|
||||
Assert.Contains(updatedArtist!.Albums, album => album.Id == persistedAlbum.Id);
|
||||
await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artist repository so that the artist read returns <paramref name="artist"/>.
|
||||
/// </summary>
|
||||
/// <param name="artist">The artist returned by the artist repository.</param>
|
||||
private void StubExistingArtist(ArtistEntity artist)
|
||||
{
|
||||
_mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(artist));
|
||||
}
|
||||
}
|
||||
+2727
File diff suppressed because it is too large.
Load diff
+394
@@ -0,0 +1,394 @@
|
||||
#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.Albums.Commands.DeleteAlbum;
|
||||
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.DeleteAlbum;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
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;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteAlbumCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteAlbumCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IArtistRepository _mockArtistRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<DeleteAlbumCommand> _mockValidator;
|
||||
private readonly DeleteAlbumCommandHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly DeleteAlbumCommandFixture _deleteAlbumCommandFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteAlbumCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteAlbumCommandHandlerTests()
|
||||
{
|
||||
_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<DeleteAlbumCommand>>();
|
||||
_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 update succeeds and saving changes succeeds.
|
||||
_mockValidator.Validate(Arg.Any<DeleteAlbumCommand>()).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.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success);
|
||||
|
||||
_sut = new DeleteAlbumCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumExists_ShouldRemoveAlbumFromArtistAndReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
Guid albumId = Guid.Parse(command.AlbumId!);
|
||||
ArtistEntity artist = CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid());
|
||||
StubExistingArtist(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).UpdateAsync(
|
||||
Arg.Is<ArtistEntity>(updatedArtist =>
|
||||
updatedArtist.Id == artistId &&
|
||||
updatedArtist.Albums.Count == 1 &&
|
||||
updatedArtist.Albums.All(album => album.Id != albumId)),
|
||||
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
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<DeleteAlbumCommand>()).Returns([DomainErrors.Music.AlbumIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Music.AlbumIdCannotBeEmpty, 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
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.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
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.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().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.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
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
Guid albumId = Guid.Parse(command.AlbumId!);
|
||||
ArtistEntity artist = CreateArtistWithAlbums(Guid.NewGuid(), artistId, albumId, Guid.NewGuid());
|
||||
StubExistingArtist(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
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
Guid albumId = Guid.Parse(command.AlbumId!);
|
||||
StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid()));
|
||||
_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().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumDoesNotExistInArtist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, Guid.NewGuid(), Guid.NewGuid()));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError);
|
||||
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_ShouldReturnFailureResultWithoutDeleting()
|
||||
{
|
||||
// Arrange
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
Guid albumId = Guid.Parse(command.AlbumId!);
|
||||
StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid()));
|
||||
_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().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
Guid albumId = Guid.Parse(command.AlbumId!);
|
||||
StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid()));
|
||||
_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().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenArtistDomainConversionFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
Guid albumId = Guid.Parse(command.AlbumId!);
|
||||
AlbumEntity firstAlbum = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false);
|
||||
AlbumEntity secondAlbum = _albumEntityFixture.Create(id: Guid.NewGuid(), artistId: artistId, libraryId: libraryId, includeTracks: false);
|
||||
// An empty name is rejected by the artist aggregate invariant, so the repository entity fails to convert to a domain entity.
|
||||
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: string.Empty, albums: [firstAlbum, secondAlbum]);
|
||||
StubExistingArtist(artist);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.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_ShouldReturnErrorWithoutSaving()
|
||||
{
|
||||
// Arrange
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
Guid albumId = Guid.Parse(command.AlbumId!);
|
||||
// The artist owns a single album, which the aggregate forbids removing.
|
||||
ArtistEntity artist = CreateArtistWithAlbums(libraryId, artistId, albumId);
|
||||
StubExistingArtist(artist);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.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_WhenUpdateArtistFails_ShouldReturnErrorWithoutSaving()
|
||||
{
|
||||
// Arrange
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
Guid albumId = Guid.Parse(command.AlbumId!);
|
||||
StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid()));
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), 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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
Guid albumId = Guid.Parse(command.AlbumId!);
|
||||
StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid()));
|
||||
_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).UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an artist that owns the provided albums.
|
||||
/// </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="albumIds">The Ids of the albums the artist owns.</param>
|
||||
/// <returns>The created artist entity.</returns>
|
||||
private ArtistEntity CreateArtistWithAlbums(Guid libraryId, Guid artistId, params Guid[] albumIds)
|
||||
{
|
||||
List<AlbumEntity> albums = [.. albumIds.Select(albumId => _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false, includeMetadata: true))];
|
||||
return _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: albums, includeContributors: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artist repository so that the artist read returns <paramref name="artist"/>.
|
||||
/// </summary>
|
||||
/// <param name="artist">The artist returned by the artist repository.</param>
|
||||
private void StubExistingArtist(ArtistEntity artist)
|
||||
{
|
||||
_mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(artist));
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum;
|
||||
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.Albums.Commands.DeleteAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteAlbumCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteAlbumCommandValidatorTests
|
||||
{
|
||||
private readonly DeleteAlbumCommandFixture _deleteAlbumCommandFixture = new();
|
||||
private readonly DeleteAlbumCommandValidator _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
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.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
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[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-album-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId)
|
||||
{
|
||||
// Arrange
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(albumId: albumId, includeAlbumId: albumId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.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
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(artistId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(albumId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors()
|
||||
{
|
||||
// Arrange
|
||||
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+528
@@ -0,0 +1,528 @@
|
||||
#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.UpdateAlbum;
|
||||
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.UpdateAlbum;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateAlbumCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IArtistRepository _mockArtistRepository;
|
||||
private readonly IAlbumRepository _mockAlbumRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IMediaContributorRepository _mockMediaContributorRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<UpdateAlbumCommand> _mockValidator;
|
||||
private readonly UpdateAlbumCommandHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly UpdateAlbumCommandFixture _updateAlbumCommandFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateAlbumCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockArtistRepository = Substitute.For<IArtistRepository>();
|
||||
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<UpdateAlbumCommand>>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
|
||||
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
|
||||
_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<UpdateAlbumCommand>()).Returns([]);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
// Default stub: the library exists.
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
|
||||
// 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);
|
||||
// Default stub: the persisted album can be read back by its Id.
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Result.From<AlbumEntity?>(_albumEntityFixture.Create(id: callInfo.Arg<Guid>(), includeTracks: false)));
|
||||
|
||||
_sut = new UpdateAlbumCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<UpdateAlbumCommand>()).Returns([Errors.Music.AlbumTitleCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumTitleCannotBeEmpty, 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
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create();
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create();
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<ArtistEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create();
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: Guid.NewGuid());
|
||||
StubExistingArtist(artist);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId));
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumIsNotPartOfTheArtist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId));
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId));
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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();
|
||||
StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId));
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<LibraryEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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_WhenContributorRepositoryFails_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId));
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId));
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([]));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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();
|
||||
StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId));
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString(), contributors: []);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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 artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: string.Empty, albums: [album]);
|
||||
StubExistingArtist(artist);
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId));
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
artistId: artistId.ToString(),
|
||||
albumId: albumId.ToString(),
|
||||
metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, 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();
|
||||
StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId));
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReadingTheAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId));
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> 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 _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPersistedAlbumCannotBeRead_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId));
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPersistedAlbumDoesNotExist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId));
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<AlbumEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalledWithValidCommand_ShouldUpdateTheAlbumAndReturnItsResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId));
|
||||
UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
ArtistEntity? updatedArtist = null;
|
||||
AlbumEntity? persistedAlbum = null;
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
updatedArtist = callInfo.Arg<ArtistEntity>();
|
||||
return Result.Updated;
|
||||
});
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
persistedAlbum = _albumEntityFixture.Create(id: callInfo.Arg<Guid>(), artistId: artistId, libraryId: libraryId, includeTracks: false);
|
||||
return Result.From<AlbumEntity?>(persistedAlbum);
|
||||
});
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(updatedArtist);
|
||||
Assert.NotNull(persistedAlbum);
|
||||
Assert.Equal(albumId, result.Value.Id);
|
||||
Assert.Equal(artistId, result.Value.ArtistId);
|
||||
Assert.Equal(libraryId, result.Value.LibraryId);
|
||||
Assert.Contains(updatedArtist!.Albums, album => album.Id == albumId);
|
||||
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 artist read returns <paramref name="artist"/>.
|
||||
/// </summary>
|
||||
/// <param name="artist">The artist returned by the artist repository.</param>
|
||||
private void StubExistingArtist(ArtistEntity artist)
|
||||
{
|
||||
_mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(artist));
|
||||
}
|
||||
}
|
||||
+1398
File diff suppressed because it is too large.
Load diff
+223
@@ -0,0 +1,223 @@
|
||||
#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.Albums.Queries.GetAlbum;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
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.Albums.Queries.GetAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAlbumQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IAlbumRepository _mockAlbumRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<GetAlbumQuery> _mockValidator;
|
||||
private readonly GetAlbumQueryHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly GetAlbumQueryFixture _getAlbumQueryFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public GetAlbumQueryHandlerTests()
|
||||
{
|
||||
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<GetAlbumQuery>>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
// Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes.
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockValidator.Validate(Arg.Any<GetAlbumQuery>()).Returns([]);
|
||||
|
||||
_sut = new GetAlbumQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumExists_ShouldReturnMappedAlbumResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: true, includeMetadata: true);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(albumId, result.Value.Id);
|
||||
Assert.Equal(artistId, result.Value.ArtistId);
|
||||
Assert.Equal(libraryId, result.Value.LibraryId);
|
||||
Assert.Equal(album.Title, result.Value.Metadata.Title);
|
||||
Assert.NotNull(result.Value.Tracks);
|
||||
Assert.Equal(album.Tracks.Count, result.Value.Tracks!.Count);
|
||||
await _mockAlbumRepository.Received(1).GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResultWithoutEvaluatingThePolicy()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.Create();
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.Create();
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<AlbumEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.Create();
|
||||
Guid artistId = Guid.Parse(query.ArtistId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: Guid.NewGuid());
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The mismatch is reported as not found, without disclosing that the album exists in another library.
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The mismatch is reported as not found, without disclosing that the album exists under another artist.
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, 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();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<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>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<GetAlbumQuery>()).Returns([Errors.Music.AlbumIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<AlbumResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumIdCannotBeEmpty, result.FirstError);
|
||||
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum;
|
||||
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.Albums.Queries.GetAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAlbumQueryValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumQueryValidatorTests
|
||||
{
|
||||
private readonly GetAlbumQueryFixture _getAlbumQueryFixture = new();
|
||||
private readonly GetAlbumQueryValidator _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
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.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
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[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-album-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId)
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.Create(albumId: albumId, includeAlbumId: albumId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.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
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.Create(artistId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.Create(albumId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumQuery query = _getAlbumQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
#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.Albums.Queries.GetAlbumTracks;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
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.Albums.Queries.GetAlbumTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAlbumTracksQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IAlbumRepository _mockAlbumRepository;
|
||||
private readonly ITrackRepository _mockTrackRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<GetAlbumTracksQuery> _mockValidator;
|
||||
private readonly GetAlbumTracksQueryHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly GetAlbumTracksQueryFixture _getAlbumTracksQueryFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public GetAlbumTracksQueryHandlerTests()
|
||||
{
|
||||
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
|
||||
_mockTrackRepository = Substitute.For<ITrackRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
|
||||
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<GetAlbumTracksQuery>>();
|
||||
_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<GetAlbumTracksQuery>()).Returns([]);
|
||||
|
||||
_sut = new GetAlbumTracksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumExists_ShouldReturnMappedTracks()
|
||||
{
|
||||
// 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);
|
||||
List<TrackEntity> tracks = _trackEntityFixture.CreateMany(2);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<TrackEntity>>(tracks));
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(tracks.Count, result.Value.Count);
|
||||
Assert.Equal(tracks[0].Id, result.Value[0].Id);
|
||||
Assert.Equal(tracks[1].Id, result.Value[1].Id);
|
||||
await _mockTrackRepository.Received(1).GetByAlbumIdAsync(albumId, 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_WhenAlbumRepositoryFails_ShouldReturnFailureResultWithoutReadingTracks()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create();
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
await _mockTrackRepository.DidNotReceive().GetByAlbumIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create();
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<AlbumEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
await _mockTrackRepository.DidNotReceive().GetByAlbumIdAsync(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_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create();
|
||||
Guid artistId = Guid.Parse(query.ArtistId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: Guid.NewGuid());
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The mismatch is reported as not found, without disclosing that the album exists in another library.
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The mismatch is reported as not found, without disclosing that the album exists under another artist.
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, 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();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackResponse>> 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 _mockTrackRepository.DidNotReceive().GetByAlbumIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTrackRepositoryFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// 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);
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackResponse>> 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
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<GetAlbumTracksQuery>()).Returns([Errors.Music.AlbumIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumIdCannotBeEmpty, result.FirstError);
|
||||
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockTrackRepository.DidNotReceive().GetByAlbumIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks;
|
||||
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.Albums.Queries.GetAlbumTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAlbumTracksQueryValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksQueryValidatorTests
|
||||
{
|
||||
private readonly GetAlbumTracksQueryFixture _getAlbumTracksQueryFixture = new();
|
||||
private readonly GetAlbumTracksQueryValidator _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
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.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
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[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-album-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId)
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(albumId: albumId, includeAlbumId: albumId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.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
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(artistId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(albumId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
#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.Tracks;
|
||||
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.Albums.Queries.GetAlbumTracksLite;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
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.Albums.Queries.GetAlbumTracksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAlbumTracksLiteQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksLiteQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IAlbumRepository _mockAlbumRepository;
|
||||
private readonly ITrackRepository _mockTrackRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<GetAlbumTracksLiteQuery> _mockValidator;
|
||||
private readonly GetAlbumTracksLiteQueryHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackLiteRowFixture _trackLiteRowFixture = new();
|
||||
private readonly GetAlbumTracksLiteQueryFixture _getAlbumTracksLiteQueryFixture = new();
|
||||
private readonly PaginatedResultDtoFixture<TrackLiteRow> _paginatedResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksLiteQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public GetAlbumTracksLiteQueryHandlerTests()
|
||||
{
|
||||
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
|
||||
_mockTrackRepository = Substitute.For<ITrackRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
|
||||
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<GetAlbumTracksLiteQuery>>();
|
||||
_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<GetAlbumTracksLiteQuery>()).Returns([]);
|
||||
|
||||
_sut = new GetAlbumTracksLiteQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumExists_ShouldReturnMappedPaginatedTrackLiteResponses()
|
||||
{
|
||||
// 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);
|
||||
List<TrackLiteRow> trackLiteRows = _trackLiteRowFixture.CreateMany(2);
|
||||
PaginatedResultDto<TrackLiteRow> paginatedTracks = _paginatedResultDtoFixture.Create(data: trackLiteRows, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
_mockTrackRepository.GetTracksLiteByAlbumIdAsync(albumId, Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(paginatedTracks));
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<TrackLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(trackLiteRows.Count, result.Value.Data.Count);
|
||||
Assert.Equal(trackLiteRows[0].Id, result.Value.Data[0].Id);
|
||||
Assert.Equal(trackLiteRows[0].Title, result.Value.Data[0].Title);
|
||||
Assert.Equal(trackLiteRows[0].TrackNumber, result.Value.Data[0].TrackNumber);
|
||||
Assert.Equal(paginatedTracks.CurrentPage, result.Value.CurrentPage);
|
||||
Assert.Equal(paginatedTracks.PerPage, result.Value.PerPage);
|
||||
Assert.Equal(paginatedTracks.Count, result.Value.Count);
|
||||
Assert.Equal(paginatedTracks.NumberOfPages, result.Value.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalled_ShouldForwardTheAlbumIdAndPaginationToTheRepository()
|
||||
{
|
||||
// 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);
|
||||
PaginatedResultDto<TrackLiteRow> paginatedTracks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
_mockTrackRepository.GetTracksLiteByAlbumIdAsync(Arg.Any<Guid>(), Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(paginatedTracks));
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockTrackRepository.Received(1).GetTracksLiteByAlbumIdAsync(
|
||||
albumId,
|
||||
Arg.Is<PaginationDataDto>(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && paginationData.PerPage == query.PaginationData.PerPage),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResultWithoutReadingTracks()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create();
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<TrackLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
await _mockTrackRepository.DidNotReceive().GetTracksLiteByAlbumIdAsync(Arg.Any<Guid>(), Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create();
|
||||
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<AlbumEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<TrackLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
await _mockTrackRepository.DidNotReceive().GetTracksLiteByAlbumIdAsync(Arg.Any<Guid>(), Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create();
|
||||
Guid artistId = Guid.Parse(query.ArtistId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: Guid.NewGuid());
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<TrackLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The mismatch is reported as not found, without disclosing that the album exists in another library.
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<TrackLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The mismatch is reported as not found, without disclosing that the album exists under another artist.
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, 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();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<TrackLiteResponse>> 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 _mockTrackRepository.DidNotReceive().GetTracksLiteByAlbumIdAsync(Arg.Any<Guid>(), Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTrackRepositoryFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// 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);
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
_mockTrackRepository.GetTracksLiteByAlbumIdAsync(albumId, Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<TrackLiteResponse>> 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
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<TrackLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<GetAlbumTracksLiteQuery>()).Returns([Errors.Music.AlbumIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<TrackLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumIdCannotBeEmpty, result.FirstError);
|
||||
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockTrackRepository.DidNotReceive().GetTracksLiteByAlbumIdAsync(Arg.Any<Guid>(), Arg.Any<PaginationDataDto?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite;
|
||||
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.Albums.Queries.GetAlbumTracksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAlbumTracksLiteQueryValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksLiteQueryValidatorTests
|
||||
{
|
||||
private readonly GetAlbumTracksLiteQueryFixture _getAlbumTracksLiteQueryFixture = new();
|
||||
private readonly GetAlbumTracksLiteQueryValidator _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
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.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
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[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-album-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId)
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(albumId: albumId, includeAlbumId: albumId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.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
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(artistId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(albumId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
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="AlbumConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumConfigurationTests : IDisposable
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AlbumConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public AlbumConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Albums", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(AlbumEntity.Id));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty artistIdProperty = entityType.GetProperty(nameof(AlbumEntity.ArtistId));
|
||||
IProperty libraryIdProperty = entityType.GetProperty(nameof(AlbumEntity.LibraryId));
|
||||
IProperty titleProperty = entityType.GetProperty(nameof(AlbumEntity.Title));
|
||||
IProperty originalTitleProperty = entityType.GetProperty(nameof(AlbumEntity.OriginalTitle));
|
||||
IProperty descriptionProperty = entityType.GetProperty(nameof(AlbumEntity.Description));
|
||||
IProperty releaseCountryProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseCountry));
|
||||
IProperty releaseTypeProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseType));
|
||||
IProperty releaseStatusProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseStatus));
|
||||
IProperty mediaFormatProperty = entityType.GetProperty(nameof(AlbumEntity.MediaFormat));
|
||||
IProperty barcodeProperty = entityType.GetProperty(nameof(AlbumEntity.Barcode));
|
||||
IProperty catalogNumberProperty = entityType.GetProperty(nameof(AlbumEntity.CatalogNumber));
|
||||
IProperty languageCodeProperty = entityType.GetProperty(nameof(AlbumEntity.LanguageCode));
|
||||
|
||||
// Assert
|
||||
Assert.False(artistIdProperty.IsNullable);
|
||||
Assert.False(libraryIdProperty.IsNullable);
|
||||
Assert.False(titleProperty.IsNullable);
|
||||
Assert.Equal(255, titleProperty.GetMaxLength());
|
||||
Assert.Equal(255, originalTitleProperty.GetMaxLength());
|
||||
Assert.Equal(2000, descriptionProperty.GetMaxLength());
|
||||
Assert.Equal(typeof(ReleaseCountry?), releaseCountryProperty.ClrType);
|
||||
Assert.Equal("TEXT", releaseCountryProperty.GetColumnType());
|
||||
Assert.Equal(2, releaseCountryProperty.GetMaxLength());
|
||||
Assert.Equal(typeof(MusicReleaseType?), releaseTypeProperty.ClrType);
|
||||
Assert.Equal("TEXT", releaseTypeProperty.GetColumnType());
|
||||
Assert.Equal(50, releaseTypeProperty.GetMaxLength());
|
||||
Assert.Equal(typeof(MusicReleaseStatus?), releaseStatusProperty.ClrType);
|
||||
Assert.Equal("TEXT", releaseStatusProperty.GetColumnType());
|
||||
Assert.Equal(50, releaseStatusProperty.GetMaxLength());
|
||||
Assert.Equal(typeof(MusicMediaFormat?), mediaFormatProperty.ClrType);
|
||||
Assert.Equal("TEXT", mediaFormatProperty.GetColumnType());
|
||||
Assert.Equal(50, mediaFormatProperty.GetMaxLength());
|
||||
Assert.Equal(13, barcodeProperty.GetMaxLength());
|
||||
Assert.Equal(50, catalogNumberProperty.GetMaxLength());
|
||||
Assert.True(languageCodeProperty.IsNullable);
|
||||
Assert.Equal(typeof(string), languageCodeProperty.ClrType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureArtistRelationshipWithCascadeDelete()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
List<IForeignKey> foreignKeys = [.. entityType.GetForeignKeys()];
|
||||
|
||||
// Assert
|
||||
IForeignKey artistForeignKey = Assert.Single(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(ArtistEntity));
|
||||
Assert.Equal(nameof(AlbumEntity.ArtistId), artistForeignKey.Properties.Single().Name);
|
||||
Assert.Equal(DeleteBehavior.Cascade, artistForeignKey.DeleteBehavior);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureOwnedAlbumRatings()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType ratingEntityType = _context.Model.GetEntityTypes()
|
||||
.Single(entityType => entityType.IsOwned() && entityType.ClrType == typeof(AudioRatingEntity) && entityType.GetTableName() == "AlbumRatings");
|
||||
|
||||
// Act
|
||||
string? tableName = ratingEntityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = ratingEntityType.FindPrimaryKey()!.Properties;
|
||||
IProperty valueProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.Value));
|
||||
IProperty maxValueProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.MaxValue));
|
||||
IProperty voteCountProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.VoteCount));
|
||||
IProperty sourceProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.Source));
|
||||
|
||||
// Assert
|
||||
Assert.Equal("AlbumRatings", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
Assert.Equal("decimal(3,2)", valueProperty.GetColumnType());
|
||||
Assert.False(valueProperty.IsNullable);
|
||||
Assert.Equal("decimal(3,2)", maxValueProperty.GetColumnType());
|
||||
Assert.False(maxValueProperty.IsNullable);
|
||||
Assert.True(voteCountProperty.IsNullable);
|
||||
Assert.Equal(typeof(AudioRatingSource?), sourceProperty.ClrType);
|
||||
Assert.Equal("TEXT", sourceProperty.GetColumnType());
|
||||
Assert.Equal(50, sourceProperty.GetMaxLength());
|
||||
Assert.True(sourceProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureManyToManyJoinTablesForTagsAndGenres()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
List<ISkipNavigation> skipNavigations = [.. entityType.GetSkipNavigations()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, skipNavigations.Count);
|
||||
ISkipNavigation tagsNavigation = Assert.Single(skipNavigations, navigation => navigation.Name == nameof(AlbumEntity.Tags));
|
||||
Assert.Equal("AlbumTags", tagsNavigation.JoinEntityType.GetTableName());
|
||||
Assert.Equal(["AlbumId", "TagId"], tagsNavigation.JoinEntityType.FindPrimaryKey()!.Properties.Select(property => property.Name));
|
||||
ISkipNavigation genresNavigation = Assert.Single(skipNavigations, navigation => navigation.Name == nameof(AlbumEntity.Genres));
|
||||
Assert.Equal("AlbumGenres", genresNavigation.JoinEntityType.GetTableName());
|
||||
Assert.Equal(["AlbumId", "GenreId"], genresNavigation.JoinEntityType.FindPrimaryKey()!.Properties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureIndexesOnArtistIdTitleAndLibraryIdTitle()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
List<IIndex> indexes = [.. entityType.GetIndexes()];
|
||||
|
||||
// Assert
|
||||
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(AlbumEntity.ArtistId), nameof(AlbumEntity.Title)]));
|
||||
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(AlbumEntity.LibraryId), nameof(AlbumEntity.Title)]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(AlbumEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(AlbumEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(AlbumEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(AlbumEntity.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();
|
||||
}
|
||||
}
|
||||
+740
@@ -0,0 +1,740 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AlbumRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly ITrackRepository _mockTrackRepository;
|
||||
private readonly AlbumRepository _sut;
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly AlbumContributorEntityFixture _albumContributorEntityFixture = new();
|
||||
private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new();
|
||||
private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new();
|
||||
private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new();
|
||||
private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AlbumRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public AlbumRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_mockTrackRepository = Substitute.For<ITrackRepository>();
|
||||
_mockTrackRepository.InsertAsync(Arg.Any<TrackEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
|
||||
_mockTrackRepository.UpdateAsync(Arg.Any<TrackEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
|
||||
_mockTrackRepository.GetExistingPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyCollection<string>>([]));
|
||||
_sut = new AlbumRepository(_mockContext, _mockTrackRepository);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAlbumDoesNotExist_ShouldAddAlbumToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<AlbumEntity>? addedAlbum = _mockContext.ChangeTracker.Entries<AlbumEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == album.Id);
|
||||
Assert.NotNull(addedAlbum);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAlbumWithTheSameIdAlreadyExists_ShouldReturnAlbumAlreadyExists()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity existingAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
_mockContext.Albums.Add(existingAlbum);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: existingAlbum.Id, includeTracks: false, includeMetadata: false);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumAlreadyExists, result.FirstError);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<AlbumEntity>()); // Only the existing album should remain tracked.
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenTwoTracksOfTheSameRequestShareAPath_ShouldReturnTrackAlreadyExists()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
album.Tracks =
|
||||
[
|
||||
_trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false),
|
||||
_trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false)
|
||||
];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
|
||||
// The duplicate within the request is detected before the stored paths are even consulted.
|
||||
await _mockTrackRepository.DidNotReceive().GetExistingPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenATrackPathIsAlreadyStoredInTheLibrary_ShouldReturnTrackAlreadyExists()
|
||||
{
|
||||
// Arrange
|
||||
_mockTrackRepository.GetExistingPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyCollection<string>>(["/music/queen/bohemian-rhapsody.flac"]));
|
||||
|
||||
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
|
||||
Assert.Empty(_mockContext.ChangeTracker.Entries<AlbumEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldAddAlbumToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/we-will-rock-you.flac", includeMetadata: false)];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
// The same physical path is only unique within its library, so another library is allowed to register it.
|
||||
Assert.Contains(_mockContext.ChangeTracker.Entries<AlbumEntity>(), entry => entry.State == EntityState.Added && entry.Entity.Id == album.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenExistingTagAndGenreNamesAreFound_ShouldReplaceThemWithTheStoredInstancesOnTheAlbumAndItsTracks()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity existingTag = _tagEntityFixture.Create(name: "ExistingTag");
|
||||
GenreEntity existingGenre = _genreEntityFixture.Create(name: "ExistingGenre");
|
||||
_mockContext.Set<TagEntity>().Add(existingTag);
|
||||
_mockContext.Set<GenreEntity>().Add(existingGenre);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
album.Tags = [_tagEntityFixture.Create(name: "ExistingTag"), _tagEntityFixture.Create(name: "NewAlbumTag")];
|
||||
album.Genres = [_genreEntityFixture.Create(name: "ExistingGenre"), _genreEntityFixture.Create(name: "NewAlbumGenre")];
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, includeMetadata: false);
|
||||
track.Tags = [_tagEntityFixture.Create(name: "ExistingTag"), _tagEntityFixture.Create(name: "NewTrackTag")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "ExistingGenre"), _genreEntityFixture.Create(name: "NewTrackGenre")];
|
||||
album.Tracks = [track];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<AlbumEntity>? addedAlbum = _mockContext.ChangeTracker.Entries<AlbumEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == album.Id);
|
||||
Assert.NotNull(addedAlbum);
|
||||
AlbumEntity addedAlbumEntity = addedAlbum!.Entity;
|
||||
Assert.Contains(addedAlbumEntity.Tags, tag => tag.Name == "ExistingTag" && ReferenceEquals(tag, existingTag));
|
||||
Assert.Contains(addedAlbumEntity.Tags, tag => tag.Name == "NewAlbumTag" && !ReferenceEquals(tag, existingTag));
|
||||
Assert.Contains(addedAlbumEntity.Genres, genre => genre.Name == "ExistingGenre" && ReferenceEquals(genre, existingGenre));
|
||||
Assert.Contains(addedAlbumEntity.Genres, genre => genre.Name == "NewAlbumGenre" && !ReferenceEquals(genre, existingGenre));
|
||||
TrackEntity addedTrack = Assert.Single(addedAlbumEntity.Tracks);
|
||||
Assert.Contains(addedTrack.Tags, tag => tag.Name == "ExistingTag" && ReferenceEquals(tag, existingTag));
|
||||
Assert.Contains(addedTrack.Tags, tag => tag.Name == "NewTrackTag" && !ReferenceEquals(tag, existingTag));
|
||||
Assert.Contains(addedTrack.Genres, genre => genre.Name == "ExistingGenre" && ReferenceEquals(genre, existingGenre));
|
||||
Assert.Contains(addedTrack.Genres, genre => genre.Name == "NewTrackGenre" && !ReferenceEquals(genre, existingGenre));
|
||||
// The shared rows are reused instead of being duplicated.
|
||||
Assert.Single(_mockContext.Set<TagEntity>().Where(tag => tag.Name == "ExistingTag"));
|
||||
Assert.Single(_mockContext.Set<GenreEntity>().Where(genre => genre.Name == "ExistingGenre"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenANewTagAndGenreNameIsSharedBetweenTheAlbumAndItsTracks_ShouldTrackASingleInstancePerName()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, includeMetadata: false);
|
||||
album.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")];
|
||||
album.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")];
|
||||
track.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")];
|
||||
album.Tracks = [track];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
// The name shared by the album and its tracks is represented by a single tracked instance, so the same key is never tracked twice.
|
||||
EntityEntry<TagEntity> addedTag = Assert.Single(_mockContext.ChangeTracker.Entries<TagEntity>(), entry => entry.Entity.Name == "SharedNewTag");
|
||||
EntityEntry<GenreEntity> addedGenre = Assert.Single(_mockContext.ChangeTracker.Entries<GenreEntity>(), entry => entry.Entity.Name == "SharedNewGenre");
|
||||
Assert.True(ReferenceEquals(album.Tags.Single(tag => tag.Name == "SharedNewTag"), addedTag.Entity));
|
||||
Assert.True(ReferenceEquals(track.Tags.Single(tag => tag.Name == "SharedNewTag"), addedTag.Entity));
|
||||
Assert.True(ReferenceEquals(album.Genres.Single(genre => genre.Name == "SharedNewGenre"), addedGenre.Entity));
|
||||
Assert.True(ReferenceEquals(track.Genres.Single(genre => genre.Name == "SharedNewGenre"), addedGenre.Entity));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAlbumHasNoTracksOrTagsOrGenres_ShouldStillAddAlbumAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
album.Tags = [];
|
||||
album.Genres = [];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<AlbumEntity>? addedAlbum = _mockContext.ChangeTracker.Entries<AlbumEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == album.Id);
|
||||
Assert.NotNull(addedAlbum);
|
||||
Assert.Empty(addedAlbum!.Entity.Tracks);
|
||||
Assert.Empty(addedAlbum.Entity.Tags);
|
||||
Assert.Empty(addedAlbum.Entity.Genres);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFound()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity data = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAlbumExists_ShouldUpdateItsScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
_mockContext.Albums.Add(storedAlbum);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false);
|
||||
data.Title = "A Night at the Opera";
|
||||
data.TotalTracks = 12;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
AlbumEntity? retrievedAlbum = await _mockContext.Albums.FindAsync(storedAlbum.Id);
|
||||
Assert.NotNull(retrievedAlbum);
|
||||
Assert.Equal("A Night at the Opera", retrievedAlbum!.Title);
|
||||
Assert.Equal(12, retrievedAlbum.TotalTracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenIncomingArtistIdAndLibraryIdDiffer_ShouldPreserveTheStoredIdentity()
|
||||
{
|
||||
// Arrange
|
||||
Guid storedArtistId = Guid.NewGuid();
|
||||
Guid storedLibraryId = Guid.NewGuid();
|
||||
AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtistId, libraryId: storedLibraryId, includeTracks: false, includeMetadata: false);
|
||||
_mockContext.Albums.Add(storedAlbum);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false);
|
||||
data.ArtistId = Guid.NewGuid();
|
||||
data.LibraryId = Guid.NewGuid();
|
||||
data.Title = "A Night at the Opera";
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity? retrievedAlbum = await _mockContext.Albums.FindAsync(storedAlbum.Id);
|
||||
Assert.NotNull(retrievedAlbum);
|
||||
Assert.Equal(storedArtistId, retrievedAlbum!.ArtistId);
|
||||
Assert.Equal(storedLibraryId, retrievedAlbum.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenIncomingAuditColumnsDiffer_ShouldPreserveTheStoredAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
Guid storedCreatedBy = Guid.NewGuid();
|
||||
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
storedAlbum.CreatedOnUtc = storedCreatedOnUtc;
|
||||
storedAlbum.CreatedBy = storedCreatedBy;
|
||||
storedAlbum.UpdatedOnUtc = null;
|
||||
storedAlbum.UpdatedBy = null;
|
||||
_mockContext.Albums.Add(storedAlbum);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false);
|
||||
data.Title = "A Night at the Opera";
|
||||
data.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
|
||||
data.CreatedBy = Guid.NewGuid();
|
||||
data.UpdatedOnUtc = DateTime.UtcNow;
|
||||
data.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity? retrievedAlbum = await _mockContext.Albums.FindAsync(storedAlbum.Id);
|
||||
Assert.NotNull(retrievedAlbum);
|
||||
Assert.Equal("A Night at the Opera", retrievedAlbum!.Title);
|
||||
// The audit columns are owned by the auditing interceptor alone, so an edit never overwrites them.
|
||||
Assert.Equal(storedCreatedOnUtc, retrievedAlbum.CreatedOnUtc);
|
||||
Assert.Equal(storedCreatedBy, retrievedAlbum.CreatedBy);
|
||||
Assert.Null(retrievedAlbum.UpdatedOnUtc);
|
||||
Assert.Null(retrievedAlbum.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenRatingsChange_ShouldReplaceTheChangedAddTheNewAndRemoveTheMissingOnes()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
storedAlbum.Ratings =
|
||||
[
|
||||
_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
|
||||
_audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10),
|
||||
_audioRatingEntityFixture.Create(value: 2, maxValue: 5, source: AudioRatingSource.LastFm, voteCount: 20)
|
||||
];
|
||||
_mockContext.Albums.Add(storedAlbum);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false);
|
||||
data.Ratings =
|
||||
[
|
||||
_audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
|
||||
_audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10),
|
||||
_audioRatingEntityFixture.Create(value: 1, maxValue: 5, source: AudioRatingSource.Discogs, voteCount: 5)
|
||||
];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity? retrievedAlbum = await _mockContext.Albums.Include(album => album.Ratings).FirstOrDefaultAsync(album => album.Id == storedAlbum.Id);
|
||||
Assert.NotNull(retrievedAlbum);
|
||||
List<AudioRatingEntity> ratings = retrievedAlbum!.Ratings;
|
||||
Assert.Equal(3, ratings.Count);
|
||||
// The rating whose value changed is replaced, the unchanged one is kept, the missing one is removed and the new one is added.
|
||||
Assert.Contains(ratings, rating => rating.Source == AudioRatingSource.MusicBrainz && rating.Value == 3M);
|
||||
Assert.Contains(ratings, rating => rating.Source == AudioRatingSource.User && rating.Value == 5M);
|
||||
Assert.Contains(ratings, rating => rating.Source == AudioRatingSource.Discogs && rating.Value == 1M);
|
||||
Assert.DoesNotContain(ratings, rating => rating.Source == AudioRatingSource.LastFm);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAnUnchangedContributorIsSubmitted_ShouldPreserveItsStoredIdentityAndAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
Guid keptMediaContributorId = Guid.NewGuid();
|
||||
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
AlbumContributorEntity keptContributor = _albumContributorEntityFixture.Create(
|
||||
albumId: storedAlbum.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer);
|
||||
storedAlbum.Contributors = [keptContributor];
|
||||
_mockContext.Albums.Add(storedAlbum);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
Guid keptContributorId = keptContributor.Id;
|
||||
DateTime keptContributorCreatedOnUtc = keptContributor.CreatedOnUtc;
|
||||
|
||||
AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false);
|
||||
data.Contributors =
|
||||
[_albumContributorEntityFixture.Create(albumId: storedAlbum.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer)];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumContributorEntity storedContributor = Assert.Single(
|
||||
await _mockContext.Set<AlbumContributorEntity>().Where(contributor => contributor.AlbumId == storedAlbum.Id).ToListAsync());
|
||||
Assert.Equal(keptContributorId, storedContributor.Id);
|
||||
Assert.Equal(keptContributorCreatedOnUtc, storedContributor.CreatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenContributorsChange_ShouldDeleteTheRemovedAndInsertTheAddedOnes()
|
||||
{
|
||||
// Arrange
|
||||
Guid keptMediaContributorId = Guid.NewGuid();
|
||||
Guid removedMediaContributorId = Guid.NewGuid();
|
||||
Guid addedMediaContributorId = Guid.NewGuid();
|
||||
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
AlbumContributorEntity keptContributor = _albumContributorEntityFixture.Create(
|
||||
albumId: storedAlbum.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer);
|
||||
AlbumContributorEntity removedContributor = _albumContributorEntityFixture.Create(
|
||||
albumId: storedAlbum.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Composer);
|
||||
storedAlbum.Contributors = [keptContributor, removedContributor];
|
||||
_mockContext.Albums.Add(storedAlbum);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
Guid keptContributorId = keptContributor.Id;
|
||||
|
||||
AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false);
|
||||
data.Contributors =
|
||||
[
|
||||
_albumContributorEntityFixture.Create(albumId: storedAlbum.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer),
|
||||
_albumContributorEntityFixture.Create(albumId: storedAlbum.Id, mediaContributorId: addedMediaContributorId, role: MediaContributorRole.Vocals)
|
||||
];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
List<AlbumContributorEntity> storedContributors = await _mockContext.Set<AlbumContributorEntity>()
|
||||
.Where(contributor => contributor.AlbumId == storedAlbum.Id)
|
||||
.ToListAsync();
|
||||
Assert.Equal(2, storedContributors.Count);
|
||||
// The unchanged participation keeps its identity, while only the delta is deleted and inserted.
|
||||
Assert.Equal(keptContributorId, storedContributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId).Id);
|
||||
Assert.DoesNotContain(storedContributors, contributor => contributor.MediaContributorId == removedMediaContributorId);
|
||||
Assert.Contains(storedContributors, contributor => contributor.MediaContributorId == addedMediaContributorId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenTagsAndGenresAlreadyExistByName_ShouldReuseTheStoredRows()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity existingTag = _tagEntityFixture.Create(name: "ExistingTag");
|
||||
GenreEntity existingGenre = _genreEntityFixture.Create(name: "ExistingGenre");
|
||||
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
storedAlbum.Tags = [existingTag];
|
||||
storedAlbum.Genres = [existingGenre];
|
||||
_mockContext.Albums.Add(storedAlbum);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false);
|
||||
data.Tags = [_tagEntityFixture.Create(name: "ExistingTag")];
|
||||
data.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity? retrievedAlbum = await _mockContext.Albums
|
||||
.Include(album => album.Tags)
|
||||
.Include(album => album.Genres)
|
||||
.FirstOrDefaultAsync(album => album.Id == storedAlbum.Id);
|
||||
Assert.NotNull(retrievedAlbum);
|
||||
TagEntity retrievedTag = Assert.Single(retrievedAlbum!.Tags);
|
||||
GenreEntity retrievedGenre = Assert.Single(retrievedAlbum.Genres);
|
||||
Assert.True(ReferenceEquals(retrievedTag, existingTag));
|
||||
Assert.True(ReferenceEquals(retrievedGenre, existingGenre));
|
||||
// The shared rows are reused instead of being duplicated.
|
||||
Assert.Single(_mockContext.Set<TagEntity>().Where(tag => tag.Name == "ExistingTag"));
|
||||
Assert.Single(_mockContext.Set<GenreEntity>().Where(genre => genre.Name == "ExistingGenre"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenAlbumExists_ShouldReturnTheAlbum()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
_mockContext.Albums.Add(album);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<AlbumEntity?> result = await _sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(album.Id, result.Value!.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenAlbumDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<AlbumEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenNavigationPropertiesAreIncluded_ShouldPopulateTheRelatedCollections()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
|
||||
AlbumEntity album = CreateAlbumWithFullAggregate(artist.Id, libraryId);
|
||||
_mockContext.Artists.Add(artist);
|
||||
_mockContext.Albums.Add(album);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<AlbumEntity?> result = await _sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity retrievedAlbum = result.Value!;
|
||||
Assert.NotNull(retrievedAlbum.Artist);
|
||||
Assert.Equal(artist.Id, retrievedAlbum.Artist!.Id);
|
||||
Assert.Single(retrievedAlbum.Ratings);
|
||||
Assert.Equal(2, retrievedAlbum.Tags.Count);
|
||||
Assert.Equal(2, retrievedAlbum.Genres.Count);
|
||||
Assert.Single(retrievedAlbum.Contributors);
|
||||
TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks);
|
||||
Assert.Single(retrievedTrack.Ratings);
|
||||
Assert.Equal(2, retrievedTrack.Tags.Count);
|
||||
Assert.Equal(2, retrievedTrack.Genres.Count);
|
||||
Assert.Equal(2, retrievedTrack.Moods.Count);
|
||||
Assert.Equal(2, retrievedTrack.Isrcs.Count);
|
||||
Assert.Single(retrievedTrack.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByArtistIdAsync_WhenCalled_ShouldReturnOnlyTheArtistAlbumsOrderedByTitleThenId()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AlbumEntity betaAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Beta", includeTracks: false, includeMetadata: false);
|
||||
AlbumEntity secondAlphaAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Alpha", includeTracks: false, includeMetadata: false);
|
||||
AlbumEntity firstAlphaAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Alpha", includeTracks: false, includeMetadata: false);
|
||||
AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(title: "Gamma", includeTracks: false, includeMetadata: false);
|
||||
_mockContext.Albums.AddRange(betaAlbum, secondAlphaAlbum, firstAlphaAlbum, albumOfAnotherArtist);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
List<AlbumEntity> artistAlbums = [betaAlbum, secondAlphaAlbum, firstAlphaAlbum];
|
||||
Guid[] expectedOrder = [.. artistAlbums.OrderBy(album => album.Title).ThenBy(album => album.Id).Select(album => album.Id)];
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<AlbumEntity>> result = await _sut.GetByArtistIdAsync(artistId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedOrder, result.Value.Select(album => album.Id));
|
||||
Assert.DoesNotContain(result.Value, album => album.Id == albumOfAnotherArtist.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByArtistIdAsync_WhenCalled_ShouldIncludeTheRelatedCollections()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
|
||||
AlbumEntity album = CreateAlbumWithFullAggregate(artist.Id, libraryId);
|
||||
_mockContext.Artists.Add(artist);
|
||||
_mockContext.Albums.Add(album);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<AlbumEntity>> result = await _sut.GetByArtistIdAsync(artist.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity retrievedAlbum = Assert.Single(result.Value);
|
||||
Assert.Single(retrievedAlbum.Ratings);
|
||||
Assert.Equal(2, retrievedAlbum.Tags.Count);
|
||||
Assert.Equal(2, retrievedAlbum.Genres.Count);
|
||||
Assert.Single(retrievedAlbum.Contributors);
|
||||
TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks);
|
||||
Assert.Single(retrievedTrack.Ratings);
|
||||
Assert.Equal(2, retrievedTrack.Tags.Count);
|
||||
Assert.Equal(2, retrievedTrack.Moods.Count);
|
||||
Assert.Single(retrievedTrack.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumsLiteByArtistIdAsync_WhenPaginationDataIsNull_ShouldReturnAllArtistAlbumsOrdered()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AlbumEntity secondAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Album B", includeTracks: false, includeMetadata: false);
|
||||
AlbumEntity firstAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Album A", includeTracks: false, includeMetadata: false);
|
||||
AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(title: "Album C", includeTracks: false, includeMetadata: false);
|
||||
_mockContext.Albums.AddRange(secondAlbum, firstAlbum, albumOfAnotherArtist);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<AlbumLiteRow>> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
PaginatedResultDto<AlbumLiteRow> page = result.Value;
|
||||
Assert.Equal(2, page.Count);
|
||||
Assert.Equal(2, page.Data.Count);
|
||||
Assert.Equal(1, page.CurrentPage);
|
||||
Assert.Equal(2, page.PerPage);
|
||||
Assert.Equal(1, page.NumberOfPages);
|
||||
Assert.Equal([firstAlbum.Id, secondAlbum.Id], page.Data.Select(row => row.Id));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, 2, 1, 2)] // The first page is fully returned.
|
||||
[InlineData(2, 2, 2, 2)] // A middle page is fully returned.
|
||||
[InlineData(3, 2, 3, 1)] // The last page is partially returned.
|
||||
[InlineData(99, 2, 3, 1)] // A page beyond the last one is clamped to the last page.
|
||||
public async Task GetAlbumsLiteByArtistIdAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage(int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount)
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
List<AlbumEntity> albums = _albumEntityFixture.CreateMany(5);
|
||||
for (int index = 0; index < albums.Count; index++)
|
||||
{
|
||||
albums[index].ArtistId = artistId;
|
||||
albums[index].Title = $"Album {index}";
|
||||
albums[index].Tracks = [];
|
||||
}
|
||||
_mockContext.Albums.AddRange(albums);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<AlbumLiteRow>> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, paginationData, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
PaginatedResultDto<AlbumLiteRow> page = result.Value;
|
||||
Assert.Equal(5, page.Count);
|
||||
Assert.Equal(3, page.NumberOfPages);
|
||||
Assert.Equal(expectedCurrentPage, page.CurrentPage);
|
||||
Assert.Equal(perPage, page.PerPage);
|
||||
Assert.Equal(expectedRowCount, page.Data.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumsLiteByArtistIdAsync_WhenCalled_ShouldReturnOnlyTheArtistAlbums()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AlbumEntity albumOfArtist = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false);
|
||||
AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
_mockContext.Albums.AddRange(albumOfArtist, albumOfAnotherArtist);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<AlbumLiteRow>> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, paginationData, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumLiteRow row = Assert.Single(result.Value.Data);
|
||||
Assert.Equal(albumOfArtist.Id, row.Id);
|
||||
Assert.Equal(1, result.Value.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumsLiteByArtistIdAsync_WhenCalled_ShouldProjectTheLiteFields()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false);
|
||||
album.TotalTracks = 12;
|
||||
_mockContext.Albums.Add(album);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<AlbumLiteRow>> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, paginationData, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumLiteRow row = Assert.Single(result.Value.Data);
|
||||
Assert.Equal(album.Id, row.Id);
|
||||
Assert.Equal("A Night at the Opera", row.Title);
|
||||
Assert.Equal(12, row.TotalTracks);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an album that belongs to the artist identified by <paramref name="artistId"/>, with every related collection populated deterministically.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The Id of the artist that owns the album.</param>
|
||||
/// <param name="libraryId">The Id of the library that owns the album.</param>
|
||||
/// <returns>The created album.</returns>
|
||||
private AlbumEntity CreateAlbumWithFullAggregate(Guid artistId, Guid libraryId)
|
||||
{
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
album.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
|
||||
album.Tags = [_tagEntityFixture.Create(name: "AlbumTag1"), _tagEntityFixture.Create(name: "AlbumTag2")];
|
||||
album.Genres = [_genreEntityFixture.Create(name: "AlbumGenre1"), _genreEntityFixture.Create(name: "AlbumGenre2")];
|
||||
album.Contributors = [_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)];
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
|
||||
track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.User, voteCount: 10)];
|
||||
track.Tags = [_tagEntityFixture.Create(name: "TrackTag1"), _tagEntityFixture.Create(name: "TrackTag2")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "TrackGenre1"), _genreEntityFixture.Create(name: "TrackGenre2")];
|
||||
track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")];
|
||||
track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")];
|
||||
track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
|
||||
album.Tracks = [track];
|
||||
return album;
|
||||
}
|
||||
}
|
||||
+306
@@ -1,9 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
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.Entities;
|
||||
@@ -16,6 +24,12 @@ public class AlbumTests
|
||||
{
|
||||
private readonly AlbumFixture _albumFixture = new();
|
||||
private readonly TrackFixture _trackFixture = new();
|
||||
private readonly AlbumIdFixture _albumIdFixture = 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();
|
||||
|
||||
[Fact]
|
||||
public void AddTrack_WhenTrackIsNotInTheAlbum_ShouldAddTheTrackAndReturnSuccess()
|
||||
@@ -49,4 +63,296 @@ public class AlbumTests
|
||||
Assert.Equal(Errors.Music.TheTrackIsAlreadyInTheAlbum, result.FirstError);
|
||||
Assert.Single(album.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithAllProperties_ShouldCreateAlbumWithAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
AlbumMetadata metadata = _albumMetadataFixture.Create(title: "A Night at the Opera");
|
||||
Optional<MusicMediaFormat> mediaFormat = Optional<MusicMediaFormat>.Some(MusicMediaFormat.Vinyl);
|
||||
Optional<Barcode> barcode = Optional<Barcode>.Some(_barcodeFixture.Create());
|
||||
Optional<string> catalogNumber = Optional<string>.Some("CAT-001");
|
||||
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()];
|
||||
List<Track> tracks = [_trackFixture.Create()];
|
||||
DateTime beforeCreate = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Album> result = Album.Create(
|
||||
metadata,
|
||||
mediaFormat,
|
||||
barcode,
|
||||
catalogNumber,
|
||||
releaseId,
|
||||
releaseGroupId,
|
||||
releaseArtistId,
|
||||
contributors,
|
||||
ratings,
|
||||
tracks);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Album album = result.Value;
|
||||
Assert.NotEqual(Guid.Empty, album.Id.Value);
|
||||
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.Equal(tracks, album.Tracks);
|
||||
Assert.InRange(album.CreatedOnUtc, beforeCreate, DateTime.UtcNow);
|
||||
Assert.False(album.UpdatedOnUtc.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenOptionalValuesAreAbsent_ShouldCreateAlbumWithoutThem()
|
||||
{
|
||||
// Act
|
||||
Result<Album> result = Album.Create(
|
||||
_albumMetadataFixture.Create(),
|
||||
Optional<MusicMediaFormat>.None(),
|
||||
Optional<Barcode>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Album album = result.Value;
|
||||
Assert.False(album.MediaFormat.HasValue);
|
||||
Assert.False(album.Barcode.HasValue);
|
||||
Assert.False(album.CatalogNumber.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseId.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseGroupId.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseArtistId.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCollectionsAreEmpty_ShouldCreateAlbumWithEmptyCollections()
|
||||
{
|
||||
// Act
|
||||
Result<Album> result = Album.Create(
|
||||
_albumMetadataFixture.Create(),
|
||||
Optional<MusicMediaFormat>.None(),
|
||||
Optional<Barcode>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value.Contributors);
|
||||
Assert.Empty(result.Value.Ratings);
|
||||
Assert.Empty(result.Value.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateWithId_WhenCalledWithPreExistingIdAndTimestamps_ShouldPreserveIdentityAndTimestamps()
|
||||
{
|
||||
// Arrange
|
||||
AlbumId albumId = _albumIdFixture.Create();
|
||||
AlbumMetadata metadata = _albumMetadataFixture.Create();
|
||||
DateTime createdOnUtc = DateTime.UtcNow.AddDays(-1);
|
||||
DateTime updatedOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Album> result = Album.Create(
|
||||
albumId,
|
||||
metadata,
|
||||
Optional<MusicMediaFormat>.Some(MusicMediaFormat.CD),
|
||||
Optional<Barcode>.Some(_barcodeFixture.Create()),
|
||||
Optional<string>.Some("CAT-002"),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
createdOnUtc,
|
||||
Optional<DateTime>.Some(updatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Album album = result.Value;
|
||||
Assert.Equal(albumId, album.Id);
|
||||
Assert.Equal(metadata, album.Metadata);
|
||||
Assert.Equal(createdOnUtc, album.CreatedOnUtc);
|
||||
Assert.Equal(Optional<DateTime>.Some(updatedOnUtc), album.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveTrack_WhenTrackIsInTheAlbum_ShouldRemoveTrackAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create();
|
||||
Album album = _albumFixture.Create(tracks: [track]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = album.RemoveTrack(track);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(album.Tracks);
|
||||
Assert.DoesNotContain(track, album.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveTrack_WhenTrackIsNotInTheAlbum_ShouldReturnTheTrackIsNotInTheAlbumError()
|
||||
{
|
||||
// Arrange
|
||||
Track storedTrack = _trackFixture.Create();
|
||||
Track foreignTrack = _trackFixture.Create();
|
||||
Album album = _albumFixture.Create(tracks: [storedTrack]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = album.RemoveTrack(foreignTrack);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TheTrackIsNotInTheAlbum, result.FirstError);
|
||||
Assert.Single(album.Tracks);
|
||||
Assert.Equal(storedTrack, album.Tracks.Single());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateContributors_WhenCalledTwice_ShouldReplaceTheContributorsInsteadOfAppending()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(contributors: []);
|
||||
MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create();
|
||||
MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create();
|
||||
album.UpdateContributors([firstContributor, _musicMediaContributorFixture.Create()]);
|
||||
|
||||
// Act
|
||||
album.UpdateContributors([secondContributor]);
|
||||
|
||||
// Assert
|
||||
MusicMediaContributor storedContributor = Assert.Single(album.Contributors);
|
||||
Assert.Equal(secondContributor, storedContributor);
|
||||
Assert.DoesNotContain(firstContributor, album.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateContributors_WhenCalledWithEmptyCollection_ShouldClearTheContributors()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(contributors: [_musicMediaContributorFixture.Create()]);
|
||||
|
||||
// Act
|
||||
album.UpdateContributors([]);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(album.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateRatings_WhenCalledTwice_ShouldReplaceTheRatingsInsteadOfAppending()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(ratings: []);
|
||||
AudioRating firstRating = _audioRatingFixture.Create(value: 1m, maxValue: 5m);
|
||||
AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m);
|
||||
album.UpdateRatings([firstRating, _audioRatingFixture.Create(value: 2m, maxValue: 5m)]);
|
||||
|
||||
// Act
|
||||
album.UpdateRatings([secondRating]);
|
||||
|
||||
// Assert
|
||||
AudioRating storedRating = Assert.Single(album.Ratings);
|
||||
Assert.Equal(secondRating, storedRating);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateRatings_WhenCalledWithEmptyCollection_ShouldClearTheRatings()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(ratings: [_audioRatingFixture.Create()]);
|
||||
|
||||
// Act
|
||||
album.UpdateRatings([]);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(album.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateDetails_WhenCalled_ShouldUpdateAllDetailPropertiesAndSetUpdatedOnUtc()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create();
|
||||
List<Track> originalTracks = [.. album.Tracks];
|
||||
AlbumMetadata metadata = _albumMetadataFixture.Create(title: "A Day at the Races");
|
||||
Optional<MusicMediaFormat> mediaFormat = Optional<MusicMediaFormat>.Some(MusicMediaFormat.Cassette);
|
||||
Optional<Barcode> barcode = Optional<Barcode>.Some(_barcodeFixture.Create());
|
||||
Optional<string> catalogNumber = Optional<string>.Some("CAT-003");
|
||||
Optional<MusicBrainzId> releaseId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
Optional<MusicBrainzId> releaseGroupId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
Optional<MusicBrainzId> releaseArtistId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
DateTime beforeUpdate = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = album.UpdateDetails(
|
||||
metadata,
|
||||
mediaFormat,
|
||||
barcode,
|
||||
catalogNumber,
|
||||
releaseId,
|
||||
releaseGroupId,
|
||||
releaseArtistId);
|
||||
|
||||
// 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.True(album.UpdatedOnUtc.HasValue);
|
||||
Assert.True(album.UpdatedOnUtc.Value >= beforeUpdate);
|
||||
// the tracks are not part of the details update
|
||||
Assert.Equal(originalTracks, album.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateDetails_WhenOptionalValuesAreAbsent_ShouldClearTheOptionalProperties()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = album.UpdateDetails(
|
||||
_albumMetadataFixture.Create(),
|
||||
Optional<MusicMediaFormat>.None(),
|
||||
Optional<Barcode>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None());
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(album.MediaFormat.HasValue);
|
||||
Assert.False(album.Barcode.HasValue);
|
||||
Assert.False(album.CatalogNumber.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseId.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseGroupId.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseArtistId.HasValue);
|
||||
}
|
||||
}
|
||||
+93
@@ -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="AlbumId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumIdTests
|
||||
{
|
||||
private readonly AlbumIdFixture _albumIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
AlbumId albumId = AlbumId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(Guid.Empty, albumId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
AlbumId albumId = AlbumId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, albumId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithEmptyGuid_ShouldReturnIdWithEmptyValue()
|
||||
{
|
||||
// Act
|
||||
AlbumId albumId = AlbumId.Create(Guid.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(Guid.Empty, albumId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToString_WhenCalled_ShouldReturnTheStringRepresentationOfTheValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
AlbumId albumId = _albumIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
string? result = albumId.ToString();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value.ToString(), result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
AlbumId firstId = _albumIdFixture.Create(value);
|
||||
AlbumId secondId = _albumIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
AlbumId firstId = _albumIdFixture.Create();
|
||||
AlbumId secondId = _albumIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AlbumMetadata"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumMetadataTests
|
||||
{
|
||||
private readonly AlbumMetadataFixture _albumMetadataFixture = new();
|
||||
private readonly GenreFixture _genreFixture = new();
|
||||
private readonly TagFixture _tagFixture = new();
|
||||
private readonly ReleaseInfoFixture _releaseInfoFixture = new();
|
||||
private readonly LanguageInfoFixture _languageInfoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidValues_ShouldCreateMetadataWithAllPropertiesSet()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
|
||||
Genre genre = _genreFixture.Create(name: "Rock");
|
||||
Tag tag = _tagFixture.Create(name: "classic");
|
||||
LanguageInfo language = _languageInfoFixture.Create(languageCode: "en", languageName: "English");
|
||||
LanguageInfo originalLanguage = _languageInfoFixture.Create(languageCode: "fr", languageName: "French");
|
||||
|
||||
// Act
|
||||
Result<AlbumMetadata> result = AlbumMetadata.Create(
|
||||
"A Night at the Opera",
|
||||
Optional<string>.Some("A Night at the Opera (original)"),
|
||||
Optional<string>.Some("The fourth studio album by the British rock band Queen."),
|
||||
releaseInfo,
|
||||
[genre],
|
||||
[tag],
|
||||
Optional<LanguageInfo>.Some(language),
|
||||
Optional<LanguageInfo>.Some(originalLanguage),
|
||||
Optional<MusicReleaseType>.Some(MusicReleaseType.Album),
|
||||
Optional<MusicReleaseStatus>.Some(MusicReleaseStatus.Official),
|
||||
Optional<int>.Some(2),
|
||||
12);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumMetadata metadata = result.Value;
|
||||
Assert.Equal("A Night at the Opera", metadata.Title);
|
||||
Assert.Equal(Optional<string>.Some("A Night at the Opera (original)"), metadata.OriginalTitle);
|
||||
Assert.Equal(Optional<string>.Some("The fourth studio album by the British rock band Queen."), metadata.Description);
|
||||
Assert.Equal(releaseInfo, metadata.ReleaseInfo);
|
||||
Assert.Equal(genre, Assert.Single(metadata.Genres));
|
||||
Assert.Equal(tag, Assert.Single(metadata.Tags));
|
||||
Assert.Equal(Optional<LanguageInfo>.Some(language), metadata.Language);
|
||||
Assert.Equal(Optional<LanguageInfo>.Some(originalLanguage), metadata.OriginalLanguage);
|
||||
Assert.Equal(Optional<MusicReleaseType>.Some(MusicReleaseType.Album), metadata.ReleaseType);
|
||||
Assert.Equal(Optional<MusicReleaseStatus>.Some(MusicReleaseStatus.Official), metadata.ReleaseStatus);
|
||||
Assert.Equal(Optional<int>.Some(2), metadata.TotalDiscs);
|
||||
Assert.Equal(12, metadata.TotalTracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenOptionalValuesAreAbsent_ShouldCreateMetadataWithoutThem()
|
||||
{
|
||||
// Act
|
||||
Result<AlbumMetadata> result = AlbumMetadata.Create(
|
||||
"A Night at the Opera",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
_releaseInfoFixture.Create(),
|
||||
[],
|
||||
[],
|
||||
Optional<LanguageInfo>.None(),
|
||||
Optional<LanguageInfo>.None(),
|
||||
Optional<MusicReleaseType>.None(),
|
||||
Optional<MusicReleaseStatus>.None(),
|
||||
Optional<int>.None(),
|
||||
12);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumMetadata metadata = result.Value;
|
||||
Assert.False(metadata.OriginalTitle.HasValue);
|
||||
Assert.False(metadata.Description.HasValue);
|
||||
Assert.False(metadata.Language.HasValue);
|
||||
Assert.False(metadata.OriginalLanguage.HasValue);
|
||||
Assert.False(metadata.ReleaseType.HasValue);
|
||||
Assert.False(metadata.ReleaseStatus.HasValue);
|
||||
Assert.False(metadata.TotalDiscs.HasValue);
|
||||
Assert.Empty(metadata.Genres);
|
||||
Assert.Empty(metadata.Tags);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCollectionsArePopulated_ShouldPreserveTheGenresAndTags()
|
||||
{
|
||||
// Arrange
|
||||
Genre firstGenre = _genreFixture.Create(name: "Rock");
|
||||
Genre secondGenre = _genreFixture.Create(name: "Progressive Rock");
|
||||
Tag firstTag = _tagFixture.Create(name: "classic");
|
||||
Tag secondTag = _tagFixture.Create(name: "70s");
|
||||
List<Genre> expectedGenres = [firstGenre, secondGenre];
|
||||
List<Tag> expectedTags = [firstTag, secondTag];
|
||||
|
||||
// Act
|
||||
Result<AlbumMetadata> result = AlbumMetadata.Create(
|
||||
"A Night at the Opera",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
_releaseInfoFixture.Create(),
|
||||
expectedGenres,
|
||||
expectedTags,
|
||||
Optional<LanguageInfo>.None(),
|
||||
Optional<LanguageInfo>.None(),
|
||||
Optional<MusicReleaseType>.None(),
|
||||
Optional<MusicReleaseStatus>.None(),
|
||||
Optional<int>.None(),
|
||||
12);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedGenres, result.Value.Genres);
|
||||
Assert.Equal(expectedTags, result.Value.Tags);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
|
||||
|
||||
// Act
|
||||
AlbumMetadata firstMetadata = _albumMetadataFixture.Create(
|
||||
title: "A Night at the Opera",
|
||||
originalTitle: Optional<string>.None(),
|
||||
description: Optional<string>.None(),
|
||||
releaseInfo: releaseInfo,
|
||||
genres: [_genreFixture.Create(name: "Rock")],
|
||||
tags: [_tagFixture.Create(name: "classic")],
|
||||
language: Optional<LanguageInfo>.None(),
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
releaseType: Optional<MusicReleaseType>.Some(MusicReleaseType.Album),
|
||||
releaseStatus: Optional<MusicReleaseStatus>.Some(MusicReleaseStatus.Official),
|
||||
totalDiscs: Optional<int>.Some(2),
|
||||
totalTracks: 12);
|
||||
AlbumMetadata secondMetadata = _albumMetadataFixture.Create(
|
||||
title: "A Night at the Opera",
|
||||
originalTitle: Optional<string>.None(),
|
||||
description: Optional<string>.None(),
|
||||
releaseInfo: releaseInfo,
|
||||
genres: [_genreFixture.Create(name: "Rock")],
|
||||
tags: [_tagFixture.Create(name: "classic")],
|
||||
language: Optional<LanguageInfo>.None(),
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
releaseType: Optional<MusicReleaseType>.Some(MusicReleaseType.Album),
|
||||
releaseStatus: Optional<MusicReleaseStatus>.Some(MusicReleaseStatus.Official),
|
||||
totalDiscs: Optional<int>.Some(2),
|
||||
totalTracks: 12);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstMetadata, secondMetadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentTitle_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
|
||||
|
||||
// Act
|
||||
AlbumMetadata firstMetadata = _albumMetadataFixture.Create(title: "A Night at the Opera", releaseInfo: releaseInfo);
|
||||
AlbumMetadata secondMetadata = _albumMetadataFixture.Create(title: "A Day at the Races", releaseInfo: releaseInfo);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstMetadata, secondMetadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentReleaseType_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
|
||||
|
||||
// Act
|
||||
AlbumMetadata firstMetadata = _albumMetadataFixture.Create(
|
||||
title: "A Night at the Opera",
|
||||
releaseInfo: releaseInfo,
|
||||
releaseType: Optional<MusicReleaseType>.Some(MusicReleaseType.Album));
|
||||
AlbumMetadata secondMetadata = _albumMetadataFixture.Create(
|
||||
title: "A Night at the Opera",
|
||||
releaseInfo: releaseInfo,
|
||||
releaseType: Optional<MusicReleaseType>.Some(MusicReleaseType.Single));
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstMetadata, secondMetadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentTotalTracks_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
|
||||
|
||||
// Act
|
||||
AlbumMetadata firstMetadata = _albumMetadataFixture.Create(
|
||||
title: "A Night at the Opera",
|
||||
releaseInfo: releaseInfo,
|
||||
totalTracks: 12);
|
||||
AlbumMetadata secondMetadata = _albumMetadataFixture.Create(
|
||||
title: "A Night at the Opera",
|
||||
releaseInfo: releaseInfo,
|
||||
totalTracks: 11);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstMetadata, secondMetadata);
|
||||
}
|
||||
}
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.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.Albums.AddAlbum;
|
||||
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.Albums.AddAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddAlbumEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<AddAlbumCommand, Result<AlbumResponse>> _mockHandler;
|
||||
private readonly AddAlbumEndpoint _sut;
|
||||
private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
|
||||
private readonly AlbumResponseFixture _albumResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public AddAlbumEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<AddAlbumCommand, Result<AlbumResponse>>>();
|
||||
_sut = FastEndpoints.Factory.Create<AddAlbumEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithLocationAndAlbumResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
AlbumResponse expectedResponse = _albumResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<AddAlbumCommand>(), 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
|
||||
Created<AlbumResponse> createdResult = Assert.IsType<Created<AlbumResponse>>(result);
|
||||
Assert.Equal(expectedResponse, createdResult.Value);
|
||||
Assert.NotNull(createdResult.Location);
|
||||
Assert.EndsWith($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{expectedResponse.Id}", createdResult.Location);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Errors.Music.ArtistNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddAlbumCommand>(), 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();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddAlbumCommand>(), 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();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Errors.Music.AlbumTitleCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddAlbumCommand>(), 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[] { "AlbumTitleCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendAddAlbumCommandToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_albumResponseFixture.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<AddAlbumCommand>(command =>
|
||||
command.LibraryId == libraryId.ToString() &&
|
||||
command.ArtistId == artistId.ToString() &&
|
||||
command.Metadata == request.Metadata &&
|
||||
command.MediaFormat == request.MediaFormat &&
|
||||
command.Barcode == request.Barcode &&
|
||||
command.CatalogNumber == request.CatalogNumber &&
|
||||
command.MusicBrainzReleaseId == request.MusicBrainzReleaseId &&
|
||||
command.MusicBrainzReleaseGroupId == request.MusicBrainzReleaseGroupId &&
|
||||
command.MusicBrainzReleaseArtistId == request.MusicBrainzReleaseArtistId &&
|
||||
command.Contributors == request.Contributors &&
|
||||
command.Ratings == request.Ratings &&
|
||||
command.Tracks != null &&
|
||||
command.Tracks.Count == request.Tracks!.Count &&
|
||||
command.Tracks[0].LibraryId == libraryId.ToString() &&
|
||||
command.Tracks[0].ArtistId == artistId.ToString() &&
|
||||
command.Tracks[0].AlbumId == null &&
|
||||
command.AlbumId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_albumResponseFixture.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<AddAlbumCommand>(command =>
|
||||
command.LibraryId == "not-a-library-guid" &&
|
||||
command.ArtistId == "not-an-artist-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_albumResponseFixture.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<AddAlbumCommand>(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();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<AddAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_albumResponseFixture.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);
|
||||
}
|
||||
}
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
|
||||
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.Albums.DeleteAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteAlbumEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<DeleteAlbumCommand, Result<Deleted>> _mockHandler;
|
||||
private readonly DeleteAlbumEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteAlbumEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<DeleteAlbumCommand, Result<Deleted>>>();
|
||||
_sut = FastEndpoints.Factory.Create<DeleteAlbumEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteAlbumCommand>(), 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.AlbumNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteAlbumCommand>(), 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("AlbumNotFound", 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<DeleteAlbumCommand>(), 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.AlbumIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteAlbumCommand>(), 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[] { "AlbumIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteAlbumCommandToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<DeleteAlbumCommand>(command =>
|
||||
command.LibraryId == libraryId.ToString() &&
|
||||
command.ArtistId == artistId.ToString() &&
|
||||
command.AlbumId == albumId.ToString()),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteAlbumCommand>(), 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";
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<DeleteAlbumCommand>(command =>
|
||||
command.LibraryId == "not-a-library-guid" &&
|
||||
command.ArtistId == "not-an-artist-guid" &&
|
||||
command.AlbumId == "not-an-album-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("artistId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("albumId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<DeleteAlbumCommand>(command =>
|
||||
command.LibraryId == null &&
|
||||
command.ArtistId == null &&
|
||||
command.AlbumId == 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<DeleteAlbumCommand>(), 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();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = Guid.NewGuid().ToString();
|
||||
}
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum;
|
||||
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.Albums.GetAlbum;
|
||||
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.Albums.GetAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetAlbumQuery, Result<AlbumResponse>> _mockHandler;
|
||||
private readonly GetAlbumEndpoint _sut;
|
||||
private readonly AlbumResponseFixture _albumResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetAlbumEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetAlbumQuery, Result<AlbumResponse>>>();
|
||||
_sut = FastEndpoints.Factory.Create<GetAlbumEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithAlbumResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
AlbumResponse expectedResponse = _albumResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<AlbumResponse> okResult = Assert.IsType<Ok<AlbumResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Errors.Music.AlbumNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.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("AlbumNotFound", 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();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.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();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Errors.Music.AlbumIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.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[] { "AlbumIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetAlbumQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_albumResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetAlbumQuery>(query =>
|
||||
query.LibraryId == libraryId.ToString() &&
|
||||
query.ArtistId == artistId.ToString() &&
|
||||
query.AlbumId == albumId.ToString()),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_albumResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid";
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetAlbumQuery>(query =>
|
||||
query.LibraryId == "not-a-library-guid" &&
|
||||
query.ArtistId == "not-an-artist-guid" &&
|
||||
query.AlbumId == "not-an-album-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_albumResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("artistId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("albumId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetAlbumQuery>(query =>
|
||||
query.LibraryId == null &&
|
||||
query.ArtistId == null &&
|
||||
query.AlbumId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_albumResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.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);
|
||||
}
|
||||
}
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
|
||||
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.Albums.GetAlbumTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAlbumTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetAlbumTracksQuery, Result<IReadOnlyList<TrackResponse>>> _mockHandler;
|
||||
private readonly GetAlbumTracksEndpoint _sut;
|
||||
private readonly TrackResponseFixture _trackResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetAlbumTracksEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetAlbumTracksQuery, Result<IReadOnlyList<TrackResponse>>>>();
|
||||
_sut = FastEndpoints.Factory.Create<GetAlbumTracksEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithTrackResponses()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
IReadOnlyList<TrackResponse> expectedResponse = _trackResponseFixture.CreateMany(2);
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<IReadOnlyList<TrackResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<TrackResponse>>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Errors.Music.AlbumNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.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("AlbumNotFound", 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();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.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();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Errors.Music.AlbumIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.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[] { "AlbumIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetAlbumTracksQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From((IReadOnlyList<TrackResponse>)_trackResponseFixture.CreateMany(1)));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetAlbumTracksQuery>(query =>
|
||||
query.LibraryId == libraryId.ToString() &&
|
||||
query.ArtistId == artistId.ToString() &&
|
||||
query.AlbumId == albumId.ToString()),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From((IReadOnlyList<TrackResponse>)_trackResponseFixture.CreateMany(1)));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid";
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetAlbumTracksQuery>(query =>
|
||||
query.LibraryId == "not-a-library-guid" &&
|
||||
query.ArtistId == "not-an-artist-guid" &&
|
||||
query.AlbumId == "not-an-album-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From((IReadOnlyList<TrackResponse>)_trackResponseFixture.CreateMany(1)));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("artistId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("albumId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetAlbumTracksQuery>(query =>
|
||||
query.LibraryId == null &&
|
||||
query.ArtistId == null &&
|
||||
query.AlbumId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From((IReadOnlyList<TrackResponse>)_trackResponseFixture.CreateMany(1));
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.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);
|
||||
}
|
||||
}
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Fixtures.Responses.Common;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
|
||||
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.Albums.GetAlbumTracksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAlbumTracksLiteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksLiteEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetAlbumTracksLiteQuery, Result<PaginatedResponse<TrackLiteResponse>>> _mockHandler;
|
||||
private readonly GetAlbumTracksLiteEndpoint _sut;
|
||||
private readonly GetAlbumTracksLiteRequestFixture _getAlbumTracksLiteRequestFixture = new();
|
||||
private readonly TrackLiteResponseFixture _trackLiteResponseFixture = new();
|
||||
private readonly PaginatedResponseFixture<TrackLiteResponse> _paginatedResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksLiteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetAlbumTracksLiteEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetAlbumTracksLiteQuery, Result<PaginatedResponse<TrackLiteResponse>>>>();
|
||||
_sut = FastEndpoints.Factory.Create<GetAlbumTracksLiteEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedTrackLiteResponses()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
PaginatedResponse<TrackLiteResponse> expectedResponse = CreatePaginatedResponse(trackCount: 2);
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksLiteQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<PaginatedResponse<TrackLiteResponse>> okResult = Assert.IsType<Ok<PaginatedResponse<TrackLiteResponse>>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksLiteQuery>(), 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
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Errors.Music.AlbumIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksLiteQuery>(), 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[] { "AlbumIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetAlbumTracksLiteQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksLiteQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePaginatedResponse(trackCount: 0)));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetAlbumTracksLiteQuery>(query =>
|
||||
query.LibraryId == libraryId.ToString() &&
|
||||
query.ArtistId == artistId.ToString() &&
|
||||
query.AlbumId == albumId.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();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksLiteQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePaginatedResponse(trackCount: 0)));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetAlbumTracksLiteQuery>(query =>
|
||||
query.LibraryId == libraryId.ToString() &&
|
||||
query.ArtistId == artistId.ToString() &&
|
||||
query.AlbumId == albumId.ToString() &&
|
||||
query.PaginationData == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksLiteQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePaginatedResponse(trackCount: 0)));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid";
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetAlbumTracksLiteQuery>(query =>
|
||||
query.LibraryId == "not-a-library-guid" &&
|
||||
query.ArtistId == "not-an-artist-guid" &&
|
||||
query.AlbumId == "not-an-album-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksLiteQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePaginatedResponse(trackCount: 0)));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("artistId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("albumId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetAlbumTracksLiteQuery>(query =>
|
||||
query.LibraryId == null &&
|
||||
query.ArtistId == null &&
|
||||
query.AlbumId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<GetAlbumTracksLiteQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(CreatePaginatedResponse(trackCount: 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{TrackLiteResponse}"/> with the specified number of tracks.
|
||||
/// </summary>
|
||||
/// <param name="trackCount">The number of track responses to include in the data collection.</param>
|
||||
/// <returns>A configured paginated response instance.</returns>
|
||||
private PaginatedResponse<TrackLiteResponse> CreatePaginatedResponse(int trackCount)
|
||||
{
|
||||
List<TrackLiteResponse> tracks = [];
|
||||
for (int index = 0; index < trackCount; index++)
|
||||
tracks.Add(_trackLiteResponseFixture.Create());
|
||||
|
||||
return _paginatedResponseFixture.Create(data: tracks, currentPage: 1, perPage: 10, count: trackCount, numberOfPages: trackCount > 0 ? 1 : 0);
|
||||
}
|
||||
}
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.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.Albums.UpdateAlbum;
|
||||
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.Albums.UpdateAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<UpdateAlbumCommand, Result<AlbumResponse>> _mockHandler;
|
||||
private readonly UpdateAlbumEndpoint _sut;
|
||||
private readonly UpdateAlbumRequestFixture _updateAlbumRequestFixture = new();
|
||||
private readonly AlbumResponseFixture _albumResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateAlbumEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<UpdateAlbumCommand, Result<AlbumResponse>>>();
|
||||
_sut = FastEndpoints.Factory.Create<UpdateAlbumEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithAlbumResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
AlbumResponse expectedResponse = _albumResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<AlbumResponse> okResult = Assert.IsType<Ok<AlbumResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Errors.Music.AlbumNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.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("AlbumNotFound", 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();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.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();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Errors.Music.AlbumIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.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[] { "AlbumIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateAlbumCommandToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_albumResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateAlbumCommand>(command =>
|
||||
command.LibraryId == libraryId.ToString() &&
|
||||
command.ArtistId == artistId.ToString() &&
|
||||
command.AlbumId == albumId.ToString() &&
|
||||
command.Metadata == request.Metadata &&
|
||||
command.MediaFormat == request.MediaFormat &&
|
||||
command.Barcode == request.Barcode &&
|
||||
command.CatalogNumber == request.CatalogNumber &&
|
||||
command.MusicBrainzReleaseId == request.MusicBrainzReleaseId &&
|
||||
command.MusicBrainzReleaseGroupId == request.MusicBrainzReleaseGroupId &&
|
||||
command.MusicBrainzReleaseArtistId == request.MusicBrainzReleaseArtistId &&
|
||||
command.Contributors == request.Contributors &&
|
||||
command.Ratings == request.Ratings),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_albumResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid";
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateAlbumCommand>(command =>
|
||||
command.LibraryId == "not-a-library-guid" &&
|
||||
command.ArtistId == "not-an-artist-guid" &&
|
||||
command.AlbumId == "not-an-album-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
|
||||
{
|
||||
// Arrange
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_albumResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("artistId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("albumId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateAlbumCommand>(command =>
|
||||
command.LibraryId == null &&
|
||||
command.ArtistId == null &&
|
||||
command.AlbumId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_albumResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user