mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 10:01:10 +00:00
Adds the music library track test suite
This commit is contained in:
1 parent
dc2692e208
commit
12d310631b
89 files changed
+18849
-9
No files matched your search
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="TrackLiteRow"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackLiteRowFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="TrackLiteRow"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the track.</param>
|
||||
/// <param name="title">Optional. The title of the track.</param>
|
||||
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
|
||||
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
|
||||
/// <param name="includeDiscNumber">Whether the disc number should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="TrackLiteRow"/>.</returns>
|
||||
public TrackLiteRow Create(
|
||||
Guid? id = null,
|
||||
string? title = null,
|
||||
int? trackNumber = null,
|
||||
int? discNumber = null,
|
||||
bool includeDiscNumber = true)
|
||||
{
|
||||
return new TrackLiteRow
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
Title = title ?? _faker.Lorem.Sentence(),
|
||||
TrackNumber = trackNumber ?? _faker.Random.Int(1, 30),
|
||||
DiscNumber = includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="TrackLiteRow"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="TrackLiteRow"/> instances.</returns>
|
||||
public List<TrackLiteRow> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AlbumContributorEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumContributorEntityFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="AlbumContributorEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the participation.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album the contributor participated in.</param>
|
||||
/// <param name="mediaContributorId">Optional. The Id of the media contributor.</param>
|
||||
/// <param name="role">Optional. The role the contributor played in the album.</param>
|
||||
/// <param name="createdBy">Optional. The Id of the user that created the participation.</param>
|
||||
/// <returns>The created <see cref="AlbumContributorEntity"/>.</returns>
|
||||
public AlbumContributorEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? albumId = null,
|
||||
Guid? mediaContributorId = null,
|
||||
MediaContributorRole? role = null,
|
||||
Guid? createdBy = null)
|
||||
{
|
||||
return new AlbumContributorEntity
|
||||
{
|
||||
Id = id ?? Guid.NewGuid(),
|
||||
AlbumId = albumId ?? Guid.NewGuid(),
|
||||
MediaContributorId = mediaContributorId ?? Guid.NewGuid(),
|
||||
Role = role ?? _faker.PickRandom<MediaContributorRole>(),
|
||||
CreatedOnUtc = _faker.Date.Past(),
|
||||
CreatedBy = createdBy ?? Guid.NewGuid(),
|
||||
UpdatedOnUtc = _faker.Random.Bool() ? _faker.Date.Recent() : null,
|
||||
UpdatedBy = _faker.Random.Bool() ? Guid.NewGuid() : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AlbumContributorEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album the contributors participated in.</param>
|
||||
/// <returns>List of configured <see cref="AlbumContributorEntity"/> instances.</returns>
|
||||
public List<AlbumContributorEntity> CreateMany(int count = 3, Guid? albumId = null)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create(albumId: albumId))];
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.Setup;
|
||||
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.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AlbumEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumEntityFixture
|
||||
{
|
||||
private readonly Random _random = new();
|
||||
private readonly Faker _faker = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly AlbumContributorEntityFixture _albumContributorEntityFixture = new();
|
||||
private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="AlbumEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the album.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist that owns the album.</param>
|
||||
/// <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="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>
|
||||
/// <returns>The created <see cref="AlbumEntity"/>.</returns>
|
||||
public AlbumEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? artistId = null,
|
||||
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,
|
||||
bool includeOriginalReleaseDate = true,
|
||||
bool includeOriginalReleaseYear = true,
|
||||
bool includeReReleaseDate = true,
|
||||
bool includeReReleaseYear = true,
|
||||
bool includeBarcode = 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 resolvedReReleaseYearUpperBound = Math.Max(resolvedOriginalReleaseYear + 1, MAXIMUM_RELEASE_YEAR);
|
||||
int resolvedReReleaseYear = reReleaseYear ?? _random.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)] : []);
|
||||
|
||||
return new Faker<AlbumEntity>()
|
||||
.CustomInstantiator(f => new AlbumEntity
|
||||
{
|
||||
Id = resolvedId,
|
||||
ArtistId = resolvedArtistId,
|
||||
LibraryId = resolvedLibraryId,
|
||||
Title = default!,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
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.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.TotalTracks, resolvedTracks.Count)
|
||||
.RuleFor(x => x.MediaFormat, f => f.PickRandom<MusicMediaFormat>())
|
||||
.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.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) : [])
|
||||
.RuleFor(x => x.Ratings, f => includeMetadata ? _audioRatingEntityFixture.CreateMany(f.Random.Number(1, 3)) : [])
|
||||
.RuleFor(x => x.Tracks, resolvedTracks)
|
||||
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
|
||||
.RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent())
|
||||
.Generate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AlbumEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="AlbumEntity"/> instances.</returns>
|
||||
public List<AlbumEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ArtistContributorEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ArtistContributorEntityFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ArtistContributorEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the participation.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the contributor participated in.</param>
|
||||
/// <param name="mediaContributorId">Optional. The Id of the media contributor.</param>
|
||||
/// <param name="role">Optional. The role the contributor played in the artist.</param>
|
||||
/// <param name="createdBy">Optional. The Id of the user that created the participation.</param>
|
||||
/// <returns>The created <see cref="ArtistContributorEntity"/>.</returns>
|
||||
public ArtistContributorEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? artistId = null,
|
||||
Guid? mediaContributorId = null,
|
||||
MediaContributorRole? role = null,
|
||||
Guid? createdBy = null)
|
||||
{
|
||||
return new ArtistContributorEntity
|
||||
{
|
||||
Id = id ?? Guid.NewGuid(),
|
||||
ArtistId = artistId ?? Guid.NewGuid(),
|
||||
MediaContributorId = mediaContributorId ?? Guid.NewGuid(),
|
||||
Role = role ?? _faker.PickRandom<MediaContributorRole>(),
|
||||
CreatedOnUtc = _faker.Date.Past(),
|
||||
CreatedBy = createdBy ?? Guid.NewGuid(),
|
||||
UpdatedOnUtc = _faker.Random.Bool() ? _faker.Date.Recent() : null,
|
||||
UpdatedBy = _faker.Random.Bool() ? Guid.NewGuid() : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="ArtistContributorEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the contributors participated in.</param>
|
||||
/// <returns>List of configured <see cref="ArtistContributorEntity"/> instances.</returns>
|
||||
public List<ArtistContributorEntity> CreateMany(int count = 3, Guid? artistId = null)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create(artistId: artistId))];
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ArtistEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ArtistEntityFixture
|
||||
{
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly ArtistContributorEntityFixture _artistContributorEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ArtistEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the artist.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library that owns the artist.</param>
|
||||
/// <param name="name">Optional. The name of the artist.</param>
|
||||
/// <param name="albums">Optional. The albums of the artist.</param>
|
||||
/// <param name="includeAlbums">Whether the artist should own a generated album, or no album at all.</param>
|
||||
/// <param name="includeContributors">Whether the artist should own a generated media contributor, or none at all.</param>
|
||||
/// <param name="includeMetadata">Whether the owned metadata collections of the generated album should be included, or forced to empty collections.</param>
|
||||
/// <returns>The created <see cref="ArtistEntity"/>.</returns>
|
||||
public ArtistEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? libraryId = null,
|
||||
string? name = null,
|
||||
List<AlbumEntity>? albums = null,
|
||||
bool includeAlbums = true,
|
||||
bool includeContributors = true,
|
||||
bool includeMetadata = true)
|
||||
{
|
||||
Guid resolvedId = id ?? Guid.NewGuid();
|
||||
Guid resolvedLibraryId = libraryId ?? Guid.NewGuid();
|
||||
List<AlbumEntity> resolvedAlbums = albums ?? (includeAlbums ? [_albumEntityFixture.Create(artistId: resolvedId, libraryId: resolvedLibraryId, includeMetadata: includeMetadata)] : []);
|
||||
|
||||
return new Faker<ArtistEntity>()
|
||||
.CustomInstantiator(f => new ArtistEntity
|
||||
{
|
||||
Id = resolvedId,
|
||||
LibraryId = resolvedLibraryId,
|
||||
Name = default!,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = null
|
||||
})
|
||||
.RuleFor(x => x.Name, f => name ?? f.Name.FullName())
|
||||
.RuleFor(x => x.Website, f => f.Internet.Url())
|
||||
.RuleFor(x => x.MusicBrainzArtistId, f => f.Random.Guid())
|
||||
.RuleFor(x => x.Albums, resolvedAlbums)
|
||||
.RuleFor(x => x.Contributors, f => includeContributors ? _artistContributorEntityFixture.CreateMany(f.Random.Number(1, 3), artistId: resolvedId) : [])
|
||||
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
|
||||
.RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent())
|
||||
.Generate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="ArtistEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ArtistEntity"/> instances.</returns>
|
||||
public List<ArtistEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AudioRatingEntity"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AudioRatingEntityFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="AudioRatingEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The rating value of the audio media element.</param>
|
||||
/// <param name="maxValue">Optional. The maximum possible rating value of the audio media element.</param>
|
||||
/// <param name="source">Optional. The source of the audio rating.</param>
|
||||
/// <param name="voteCount">Optional. The number of votes that contributed to the audio rating.</param>
|
||||
/// <param name="includeValue">Whether the value should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMaxValue">Whether the maximum value should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeSource">Whether the source should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeVoteCount">Whether the vote count should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="AudioRatingEntity"/>.</returns>
|
||||
public AudioRatingEntity Create(
|
||||
decimal? value = null,
|
||||
decimal? maxValue = null,
|
||||
AudioRatingSource? source = null,
|
||||
int? voteCount = null,
|
||||
bool includeValue = true,
|
||||
bool includeMaxValue = true,
|
||||
bool includeSource = true,
|
||||
bool includeVoteCount = true)
|
||||
{
|
||||
return new AudioRatingEntity(
|
||||
includeValue ? (value ?? _faker.Random.Decimal(1, 5)) : null,
|
||||
includeMaxValue ? (maxValue ?? 5) : null,
|
||||
includeSource ? (source ?? _faker.PickRandom<AudioRatingSource>()) : null,
|
||||
includeVoteCount ? (voteCount ?? _faker.Random.Number(1, 1000)) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AudioRatingEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<AudioRatingEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="TrackContributorEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackContributorEntityFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="TrackContributorEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the participation.</param>
|
||||
/// <param name="trackId">Optional. The Id of the track the contributor participated in.</param>
|
||||
/// <param name="mediaContributorId">Optional. The Id of the media contributor.</param>
|
||||
/// <param name="role">Optional. The role the contributor played in the track.</param>
|
||||
/// <param name="createdBy">Optional. The Id of the user that created the participation.</param>
|
||||
/// <returns>The created <see cref="TrackContributorEntity"/>.</returns>
|
||||
public TrackContributorEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? trackId = null,
|
||||
Guid? mediaContributorId = null,
|
||||
MediaContributorRole? role = null,
|
||||
Guid? createdBy = null)
|
||||
{
|
||||
return new TrackContributorEntity
|
||||
{
|
||||
Id = id ?? Guid.NewGuid(),
|
||||
TrackId = trackId ?? Guid.NewGuid(),
|
||||
MediaContributorId = mediaContributorId ?? Guid.NewGuid(),
|
||||
Role = role ?? _faker.PickRandom<MediaContributorRole>(),
|
||||
CreatedOnUtc = _faker.Date.Past(),
|
||||
CreatedBy = createdBy ?? Guid.NewGuid(),
|
||||
UpdatedOnUtc = _faker.Random.Bool() ? _faker.Date.Recent() : null,
|
||||
UpdatedBy = _faker.Random.Bool() ? Guid.NewGuid() : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="TrackContributorEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <param name="trackId">Optional. The Id of the track the contributors participated in.</param>
|
||||
/// <returns>List of configured <see cref="TrackContributorEntity"/> instances.</returns>
|
||||
public List<TrackContributorEntity> CreateMany(int count = 3, Guid? trackId = null)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create(trackId: trackId))];
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.Setup;
|
||||
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.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="TrackEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackEntityFixture
|
||||
{
|
||||
private readonly Random _random = new();
|
||||
private readonly Faker _faker = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new();
|
||||
private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new();
|
||||
private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new();
|
||||
private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="TrackEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the track.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album that owns the track.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library that owns the track.</param>
|
||||
/// <param name="path">Optional. The file system path of the track.</param>
|
||||
/// <param name="title">Optional. The title of the track.</param>
|
||||
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
|
||||
/// <param name="includeMetadata">Whether the owned metadata collections (Tags, Genres, Moods, ISRCs, Contributors, Ratings) should be included, or forced to empty collections.</param>
|
||||
/// <param name="originalReleaseDate">Optional. The original release date of the track.</param>
|
||||
/// <param name="originalReleaseYear">Optional. The original release year of the track.</param>
|
||||
/// <param name="reReleaseDate">Optional. The re-release date of the track.</param>
|
||||
/// <param name="reReleaseYear">Optional. The re-release year of the track.</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>
|
||||
/// <returns>The created <see cref="TrackEntity"/>.</returns>
|
||||
public TrackEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? albumId = null,
|
||||
Guid? libraryId = null,
|
||||
string? path = null,
|
||||
string? title = null,
|
||||
int? trackNumber = null,
|
||||
bool includeMetadata = true,
|
||||
DateOnly? originalReleaseDate = null,
|
||||
int? originalReleaseYear = null,
|
||||
DateOnly? reReleaseDate = null,
|
||||
int? reReleaseYear = null,
|
||||
bool includeOriginalReleaseDate = true,
|
||||
bool includeOriginalReleaseYear = true,
|
||||
bool includeReReleaseDate = true,
|
||||
bool includeReReleaseYear = true)
|
||||
{
|
||||
Guid resolvedId = id ?? Guid.NewGuid();
|
||||
Guid resolvedAlbumId = albumId ?? Guid.NewGuid();
|
||||
Guid resolvedLibraryId = libraryId ?? Guid.NewGuid();
|
||||
const int MAXIMUM_RELEASE_YEAR = 2026;
|
||||
int resolvedOriginalReleaseYear = originalReleaseYear ?? _random.Next(1900, MAXIMUM_RELEASE_YEAR);
|
||||
int resolvedReReleaseYearUpperBound = Math.Max(resolvedOriginalReleaseYear + 1, MAXIMUM_RELEASE_YEAR);
|
||||
int resolvedReReleaseYear = reReleaseYear ?? _random.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));
|
||||
|
||||
return new Faker<TrackEntity>()
|
||||
.CustomInstantiator(f => new TrackEntity
|
||||
{
|
||||
Id = resolvedId,
|
||||
AlbumId = resolvedAlbumId,
|
||||
LibraryId = resolvedLibraryId,
|
||||
Path = default!,
|
||||
Title = default!,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = null
|
||||
})
|
||||
.RuleFor(x => x.Path, f => path ?? f.System.FilePath())
|
||||
.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.OriginalReleaseDate, includeOriginalReleaseDate ? resolvedOriginalReleaseDate : null)
|
||||
.RuleFor(x => x.OriginalReleaseYear, includeOriginalReleaseYear ? resolvedOriginalReleaseYear : null)
|
||||
.RuleFor(x => x.ReReleaseDate, includeReReleaseDate ? resolvedReReleaseDate : null)
|
||||
.RuleFor(x => x.ReReleaseYear, includeReReleaseYear ? resolvedReReleaseYear : 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.DurationInSeconds, _random.Next(60, 7200))
|
||||
.RuleFor(x => x.SampleRate, f => f.PickRandom(44100, 48000, 96000))
|
||||
.RuleFor(x => x.Channels, f => f.PickRandom(1, 2, 6))
|
||||
.RuleFor(x => x.BitDepth, _random.Next(8, 32))
|
||||
.RuleFor(x => x.AudioCodec, f => f.PickRandom("FLAC", "MP3", "AAC", "ALAC"))
|
||||
.RuleFor(x => x.Bitrate, _random.Next(96, 1411))
|
||||
.RuleFor(x => x.TrackNumber, f => trackNumber ?? f.Random.Int(1, 20))
|
||||
.RuleFor(x => x.DiscNumber, _random.Next(1, 3))
|
||||
.RuleFor(x => x.Script, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.Key, f => f.PickRandom<MusicKey>())
|
||||
.RuleFor(x => x.Bpm, _random.Next(40, 240))
|
||||
.RuleFor(x => x.Work, f => f.Music.Genre())
|
||||
.RuleFor(x => x.MusicBrainzRecordingId, f => f.Random.Guid())
|
||||
.RuleFor(x => x.MusicBrainzTrackId, f => f.Random.Guid())
|
||||
.RuleFor(x => x.MusicBrainzWorkId, f => f.Random.Guid())
|
||||
.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.Moods, f => includeMetadata ? _trackMoodEntityFixture.CreateMany(f.Random.Number(1, 3)) : [])
|
||||
.RuleFor(x => x.Isrcs, f => includeMetadata ? _trackIsrcEntityFixture.CreateMany(f.Random.Number(1, 3)) : [])
|
||||
.RuleFor(x => x.Contributors, f => includeMetadata ? _trackContributorEntityFixture.CreateMany(f.Random.Number(1, 3), trackId: resolvedId) : [])
|
||||
.RuleFor(x => x.Ratings, f => includeMetadata ? _audioRatingEntityFixture.CreateMany(f.Random.Number(1, 3)) : [])
|
||||
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
|
||||
.RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent())
|
||||
.Generate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="TrackEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="TrackEntity"/> instances.</returns>
|
||||
public List<TrackEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="TrackIsrcEntity"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackIsrcEntityFixture
|
||||
{
|
||||
private const string LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
private const string ALPHANUMERICS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
private const string DIGITS = "0123456789";
|
||||
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="TrackIsrcEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The value of the ISRC.</param>
|
||||
/// <returns>The created <see cref="TrackIsrcEntity"/>.</returns>
|
||||
public TrackIsrcEntity Create(string? value = null)
|
||||
{
|
||||
// ISRC codes follow the domain format: two letters, three alphanumeric characters and seven digits.
|
||||
return new TrackIsrcEntity(value ?? (
|
||||
_faker.Random.String2(2, LETTERS)
|
||||
+ _faker.Random.String2(3, ALPHANUMERICS)
|
||||
+ _faker.Random.String2(7, DIGITS)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="TrackIsrcEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<TrackIsrcEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="TrackMoodEntity"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackMoodEntityFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="TrackMoodEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional. The name of the mood.</param>
|
||||
/// <returns>The created <see cref="TrackMoodEntity"/>.</returns>
|
||||
public TrackMoodEntity Create(
|
||||
string? name = null)
|
||||
{
|
||||
return new TrackMoodEntity(name ?? _faker.Lorem.Word());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="TrackMoodEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<TrackMoodEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AddTrackCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddTrackCommandFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
private readonly MoodDtoFixture _moodDtoFixture = new();
|
||||
private readonly IsrcDtoFixture _isrcDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid command to add a track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the track belongs to, taken from the route.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the track belongs to, taken from the route.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album the track belongs to, taken from the route.</param>
|
||||
/// <param name="path">Optional. The file system path of the track.</param>
|
||||
/// <param name="metadata">Optional. The audio metadata of the track.</param>
|
||||
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
|
||||
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
|
||||
/// <param name="script">Optional. The script used by the language of the track.</param>
|
||||
/// <param name="key">Optional. The musical key of the track.</param>
|
||||
/// <param name="bpm">Optional. The tempo of the track in beats per minute.</param>
|
||||
/// <param name="work">Optional. The title of the work the track is a recording of.</param>
|
||||
/// <param name="musicBrainzRecordingId">Optional. The MusicBrainz identifier of the recording.</param>
|
||||
/// <param name="musicBrainzTrackId">Optional. The MusicBrainz identifier of the track.</param>
|
||||
/// <param name="musicBrainzWorkId">Optional. The MusicBrainz identifier of the work.</param>
|
||||
/// <param name="moods">Optional. The list of moods of the track.</param>
|
||||
/// <param name="isrcs">Optional. The list of ISRC of the track.</param>
|
||||
/// <param name="contributors">Optional. The list of media contributors that performed on the track.</param>
|
||||
/// <param name="ratings">Optional. The list of ratings for this track.</param>
|
||||
/// <param name="trackId">Optional. The Id of the track, 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="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePath">Whether the path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMetadata">Whether the metadata should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTrackNumber">Whether the track number should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, 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 add a track.</returns>
|
||||
public AddTrackCommand Create(
|
||||
string? libraryId = null,
|
||||
string? artistId = null,
|
||||
string? albumId = null,
|
||||
string? path = null,
|
||||
AudioMetadataDto? metadata = null,
|
||||
int? trackNumber = null,
|
||||
int? discNumber = null,
|
||||
string? script = null,
|
||||
MusicKey? key = null,
|
||||
int? bpm = null,
|
||||
string? work = null,
|
||||
Guid? musicBrainzRecordingId = null,
|
||||
Guid? musicBrainzTrackId = null,
|
||||
Guid? musicBrainzWorkId = null,
|
||||
List<MoodDto>? moods = null,
|
||||
List<IsrcDto>? isrcs = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
Guid? trackId = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeArtistId = true,
|
||||
bool includeAlbumId = true,
|
||||
bool includePath = true,
|
||||
bool includeMetadata = true,
|
||||
bool includeTrackNumber = true,
|
||||
bool includeOptionalProperties = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true)
|
||||
{
|
||||
return new AddTrackCommand(
|
||||
includeLibraryId ? libraryId ?? Guid.NewGuid().ToString() : null,
|
||||
includeArtistId ? artistId ?? Guid.NewGuid().ToString() : null,
|
||||
includeAlbumId ? albumId ?? Guid.NewGuid().ToString() : null,
|
||||
includePath ? path ?? Path.Combine(Path.GetTempPath(), "lumina-tracks", _faker.System.FileName()) : null,
|
||||
includeMetadata ? metadata ?? _audioMetadataDtoFixture.Create() : null,
|
||||
includeTrackNumber ? trackNumber ?? _faker.Random.Int(1, 30) : null,
|
||||
includeOptionalProperties ? discNumber ?? _faker.Random.Int(1, 3) : null,
|
||||
includeOptionalProperties ? script ?? _faker.Random.AlphaNumeric(4) : null,
|
||||
includeOptionalProperties ? key ?? _faker.PickRandom<MusicKey>() : null,
|
||||
includeOptionalProperties ? bpm ?? _faker.Random.Int(40, 220) : null,
|
||||
includeOptionalProperties ? work ?? _faker.Lorem.Sentence() : null,
|
||||
includeOptionalProperties ? musicBrainzRecordingId ?? _faker.Random.Guid() : null,
|
||||
includeOptionalProperties ? musicBrainzTrackId ?? _faker.Random.Guid() : null,
|
||||
includeOptionalProperties ? musicBrainzWorkId ?? _faker.Random.Guid() : null,
|
||||
includeOptionalProperties ? moods ?? _moodDtoFixture.CreateMany(_faker.Random.Int(1, 3)) : null,
|
||||
includeOptionalProperties ? isrcs ?? _isrcDtoFixture.CreateMany(_faker.Random.Int(1, 3)) : null,
|
||||
includeContributors ? contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3)) : null,
|
||||
includeRatings ? ratings ?? _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3)) : null,
|
||||
trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AddTrackCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<AddTrackCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="DeleteTrackCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteTrackCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="DeleteTrackCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the album of the track belongs to.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">Optional. The Id of the track to delete.</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="includeTrackId">Whether the track Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="DeleteTrackCommand"/>.</returns>
|
||||
public DeleteTrackCommand Create(
|
||||
string? libraryId = null,
|
||||
string? artistId = null,
|
||||
string? albumId = null,
|
||||
string? trackId = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeArtistId = true,
|
||||
bool includeAlbumId = true,
|
||||
bool includeTrackId = true)
|
||||
{
|
||||
return new DeleteTrackCommand(
|
||||
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeTrackId ? (trackId ?? Guid.NewGuid().ToString()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="DeleteTrackCommand"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<DeleteTrackCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.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.Tracks.Commands.UpdateTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateTrackCommand"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateTrackCommandFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
private readonly MoodDtoFixture _moodDtoFixture = new();
|
||||
private readonly IsrcDtoFixture _isrcDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid command to update a track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the track belongs to.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">Optional. The Id of the track to update.</param>
|
||||
/// <param name="path">Optional. The file system path of the track.</param>
|
||||
/// <param name="metadata">Optional. The audio metadata of the track.</param>
|
||||
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
|
||||
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
|
||||
/// <param name="script">Optional. The script used by the language of the track.</param>
|
||||
/// <param name="key">Optional. The musical key of the track.</param>
|
||||
/// <param name="bpm">Optional. The tempo of the track in beats per minute.</param>
|
||||
/// <param name="work">Optional. The title of the work the track is a recording of.</param>
|
||||
/// <param name="musicBrainzRecordingId">Optional. The MusicBrainz identifier of the recording.</param>
|
||||
/// <param name="musicBrainzTrackId">Optional. The MusicBrainz identifier of the track.</param>
|
||||
/// <param name="musicBrainzWorkId">Optional. The MusicBrainz identifier of the work.</param>
|
||||
/// <param name="moods">Optional. The moods of the track.</param>
|
||||
/// <param name="isrcs">Optional. The ISRC codes of the track.</param>
|
||||
/// <param name="contributors">Optional. The media contributors that performed on the track.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the track.</param>
|
||||
/// <param name="includeOptionalProperties">Whether the optional properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="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="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="includeTrackId">Whether the track Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePath">Whether the path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTrackNumber">Whether the track number should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created command to update a track.</returns>
|
||||
public UpdateTrackCommand Create(
|
||||
string? libraryId = null,
|
||||
string? artistId = null,
|
||||
string? albumId = null,
|
||||
string? trackId = null,
|
||||
string? path = null,
|
||||
AudioMetadataDto? metadata = null,
|
||||
int? trackNumber = null,
|
||||
int? discNumber = null,
|
||||
string? script = null,
|
||||
MusicKey? key = null,
|
||||
int? bpm = null,
|
||||
string? work = null,
|
||||
Guid? musicBrainzRecordingId = null,
|
||||
Guid? musicBrainzTrackId = null,
|
||||
Guid? musicBrainzWorkId = null,
|
||||
List<MoodDto>? moods = null,
|
||||
List<IsrcDto>? isrcs = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
bool includeOptionalProperties = true,
|
||||
bool includeMetadata = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true,
|
||||
bool includeLibraryId = true,
|
||||
bool includeArtistId = true,
|
||||
bool includeAlbumId = true,
|
||||
bool includeTrackId = true,
|
||||
bool includePath = true,
|
||||
bool includeTrackNumber = true)
|
||||
{
|
||||
return new UpdateTrackCommand(
|
||||
includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null,
|
||||
includeArtistId ? (artistId ?? _faker.Random.Guid().ToString()) : null,
|
||||
includeAlbumId ? (albumId ?? _faker.Random.Guid().ToString()) : null,
|
||||
includeTrackId ? (trackId ?? _faker.Random.Guid().ToString()) : null,
|
||||
includePath ? (path ?? _faker.System.FilePath()) : null,
|
||||
includeMetadata ? (metadata ?? _audioMetadataDtoFixture.Create()) : null,
|
||||
includeTrackNumber ? (trackNumber ?? _faker.Random.Int(1, 20)) : null,
|
||||
includeOptionalProperties ? (discNumber ?? _faker.Random.Int(1, 3)) : null,
|
||||
includeOptionalProperties ? (script ?? _faker.Random.String2(_faker.Random.Number(1, 50))) : null,
|
||||
includeOptionalProperties ? (key ?? _faker.PickRandom<MusicKey>()) : null,
|
||||
includeOptionalProperties ? (bpm ?? _faker.Random.Int(40, 240)) : null,
|
||||
includeOptionalProperties ? (work ?? _faker.Music.Genre()) : null,
|
||||
includeOptionalProperties ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null,
|
||||
includeOptionalProperties ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null,
|
||||
includeOptionalProperties ? (musicBrainzWorkId ?? _faker.Random.Guid()) : null,
|
||||
includeOptionalProperties ? (moods ?? [.. _moodDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
|
||||
includeOptionalProperties ? (isrcs ?? [.. _isrcDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
|
||||
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="UpdateTrackCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<UpdateTrackCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetTrackQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTrackQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetTrackQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the album of the track belongs to.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">Optional. The Id of the track to get.</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="includeTrackId">Whether the track Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetTrackQuery"/>.</returns>
|
||||
public GetTrackQuery Create(
|
||||
string? libraryId = null,
|
||||
string? artistId = null,
|
||||
string? albumId = null,
|
||||
string? trackId = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeArtistId = true,
|
||||
bool includeAlbumId = true,
|
||||
bool includeTrackId = true)
|
||||
{
|
||||
return new GetTrackQuery(
|
||||
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeTrackId ? (trackId ?? Guid.NewGuid().ToString()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetTrackQuery"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetTrackQuery"/> instances.</returns>
|
||||
public List<GetTrackQuery> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MoodDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MoodDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="MoodDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional. The name of the mood.</param>
|
||||
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="MoodDto"/>.</returns>
|
||||
public MoodDto Create(
|
||||
string? name = null,
|
||||
bool includeName = true)
|
||||
{
|
||||
return new MoodDto(includeName ? name ?? _faker.Lorem.Word() : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="MoodDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<MoodDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
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.DTO.MediaLibrary.AudioLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AudioRatingDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AudioRatingDtoFixture
|
||||
{
|
||||
private readonly Fixture _fixture = new();
|
||||
private readonly Random _random = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="AudioRatingDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The rating value.</param>
|
||||
/// <param name="maxValue">Optional. The maximum possible rating value.</param>
|
||||
/// <param name="source">Optional. The rating source.</param>
|
||||
/// <param name="voteCount">Optional. The number of votes.</param>
|
||||
/// <param name="includeSource">Whether the rating source should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeVoteCount">Whether the number of votes should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="AudioRatingDto"/>.</returns>
|
||||
public AudioRatingDto Create(
|
||||
decimal? value = null,
|
||||
decimal? maxValue = null,
|
||||
AudioRatingSource? source = null,
|
||||
int? voteCount = null,
|
||||
bool includeSource = true,
|
||||
bool includeVoteCount = true)
|
||||
{
|
||||
return new AudioRatingDto(
|
||||
value ?? _random.Next(1, 5),
|
||||
maxValue ?? 5,
|
||||
includeSource ? (source ?? _fixture.Create<AudioRatingSource>()) : null,
|
||||
includeVoteCount ? (voteCount ?? _random.Next(1, 1000)) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AudioRatingDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<AudioRatingDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
#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.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="AudioMetadataDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AudioMetadataDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly Random _random = 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="AudioMetadataDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="title">Optional. The title of the audio.</param>
|
||||
/// <param name="originalTitle">Optional. The original title of the audio.</param>
|
||||
/// <param name="description">Optional. A brief description or summary of the audio.</param>
|
||||
/// <param name="releaseInfo">Optional. The release information of the audio.</param>
|
||||
/// <param name="language">Optional. The language of the audio.</param>
|
||||
/// <param name="originalLanguage">Optional. The original language of the audio.</param>
|
||||
/// <param name="tags">Optional. The tags that describe or categorize the audio.</param>
|
||||
/// <param name="genres">Optional. The genres associated with the audio.</param>
|
||||
/// <param name="durationInSeconds">Optional. The duration of the audio, in seconds.</param>
|
||||
/// <param name="sampleRate">Optional. The sample rate of the audio, in Hz.</param>
|
||||
/// <param name="channels">Optional. The number of audio channels.</param>
|
||||
/// <param name="bitDepth">Optional. The bit depth of the audio.</param>
|
||||
/// <param name="audioCodec">Optional. The audio codec used.</param>
|
||||
/// <param name="bitrate">Optional. The bitrate of the audio, in kbps.</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="includeDurationInSeconds">Whether the duration should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeSampleRate">Whether the sample rate should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeChannels">Whether the channels should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeBitDepth">Whether the bit depth should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeAudioCodec">Whether the audio codec should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeBitrate">Whether the bitrate should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="AudioMetadataDto"/>.</returns>
|
||||
public AudioMetadataDto 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,
|
||||
int? durationInSeconds = null,
|
||||
int? sampleRate = null,
|
||||
int? channels = null,
|
||||
int? bitDepth = null,
|
||||
string? audioCodec = null,
|
||||
int? bitrate = 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 includeDurationInSeconds = true,
|
||||
bool includeSampleRate = true,
|
||||
bool includeChannels = true,
|
||||
bool includeBitDepth = true,
|
||||
bool includeAudioCodec = true,
|
||||
bool includeBitrate = true)
|
||||
{
|
||||
return new AudioMetadataDto(
|
||||
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,
|
||||
includeDurationInSeconds ? (durationInSeconds ?? _faker.Random.Int(60, 7200)) : null,
|
||||
includeSampleRate ? (sampleRate ?? _faker.Random.Int(8000, 192000)) : null,
|
||||
includeChannels ? (channels ?? _faker.Random.Int(1, 8)) : null,
|
||||
includeBitDepth ? (bitDepth ?? _faker.Random.Int(8, 32)) : null,
|
||||
includeAudioCodec ? (audioCodec ?? _faker.Random.ArrayElement(["FLAC", "MP3", "AAC", "ALAC"])) : null,
|
||||
includeBitrate ? (bitrate ?? _faker.Random.Int(96, 1411)) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AudioMetadataDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<AudioMetadataDto> 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.Next(1900, 2026);
|
||||
int reReleaseYear = _random.Next(originalReleaseYear, 2026);
|
||||
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}";
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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="IsrcDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsrcDtoFixture
|
||||
{
|
||||
private const string LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
private const string ALPHANUMERICS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
private const string DIGITS = "0123456789";
|
||||
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="IsrcDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The value of the ISRC.</param>
|
||||
/// <param name="includeValue">Whether the value should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="IsrcDto"/>.</returns>
|
||||
public IsrcDto Create(
|
||||
string? value = null,
|
||||
bool includeValue = true)
|
||||
{
|
||||
return new IsrcDto(includeValue ? value ?? GenerateValidIsrc() : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="IsrcDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<IsrcDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a random ISRC that satisfies the domain format: two letters, three alphanumeric characters and seven digits.
|
||||
/// </summary>
|
||||
/// <returns>The generated ISRC value.</returns>
|
||||
private string GenerateValidIsrc()
|
||||
{
|
||||
return _faker.Random.String2(2, LETTERS)
|
||||
+ _faker.Random.String2(3, ALPHANUMERICS)
|
||||
+ _faker.Random.String2(7, DIGITS);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
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="GetAlbumTracksLiteRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksLiteRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="GetAlbumTracksLiteRequest"/> with default or random values.
|
||||
/// </summary>
|
||||
/// <param name="currentPage">Optional. The page of results to retrieve.</param>
|
||||
/// <param name="perPage">Optional. The maximum number of tracks to retrieve per page.</param>
|
||||
/// <param name="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePerPage">Whether the per page count should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetAlbumTracksLiteRequest"/>.</returns>
|
||||
public GetAlbumTracksLiteRequest Create(
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
bool includeCurrentPage = true,
|
||||
bool includePerPage = true)
|
||||
{
|
||||
return new GetAlbumTracksLiteRequest(
|
||||
CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null,
|
||||
PerPage: includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetAlbumTracksLiteRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<GetAlbumTracksLiteRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateArtistTrackRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateArtistTrackRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
private readonly MoodDtoFixture _moodDtoFixture = new();
|
||||
private readonly IsrcDtoFixture _isrcDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid request to update a track of an album of an artist.
|
||||
/// </summary>
|
||||
/// <param name="trackId">Optional. The Id of the track, when the track already exists.</param>
|
||||
/// <param name="path">Optional. The file system path of the track.</param>
|
||||
/// <param name="metadata">Optional. The audio metadata of the track.</param>
|
||||
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
|
||||
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
|
||||
/// <param name="script">Optional. The script used by the language of the track.</param>
|
||||
/// <param name="key">Optional. The musical key of the track.</param>
|
||||
/// <param name="bpm">Optional. The tempo of the track in beats per minute.</param>
|
||||
/// <param name="work">Optional. The title of the work the track is a recording of.</param>
|
||||
/// <param name="musicBrainzRecordingId">Optional. The MusicBrainz identifier of the recording.</param>
|
||||
/// <param name="musicBrainzTrackId">Optional. The MusicBrainz identifier of the track.</param>
|
||||
/// <param name="musicBrainzWorkId">Optional. The MusicBrainz identifier of the work.</param>
|
||||
/// <param name="moods">Optional. The moods of the track.</param>
|
||||
/// <param name="isrcs">Optional. The ISRC codes of the track.</param>
|
||||
/// <param name="contributors">Optional. The media contributors that performed on the track.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the track.</param>
|
||||
/// <param name="includeTrackId">Whether the track Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePath">Whether the path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMetadata">Whether the metadata should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTrackNumber">Whether the track number should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeOptionalProperties">Whether the optional properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeContributors">Whether the contributors list should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeRatings">Whether the ratings list should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created request to update a track of an album of an artist.</returns>
|
||||
public UpdateArtistTrackRequest Create(
|
||||
Guid? trackId = null,
|
||||
string? path = null,
|
||||
AudioMetadataDto? metadata = null,
|
||||
int? trackNumber = null,
|
||||
int? discNumber = null,
|
||||
string? script = null,
|
||||
MusicKey? key = null,
|
||||
int? bpm = null,
|
||||
string? work = null,
|
||||
Guid? musicBrainzRecordingId = null,
|
||||
Guid? musicBrainzTrackId = null,
|
||||
Guid? musicBrainzWorkId = null,
|
||||
List<MoodDto>? moods = null,
|
||||
List<IsrcDto>? isrcs = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
bool includeTrackId = true,
|
||||
bool includePath = true,
|
||||
bool includeMetadata = true,
|
||||
bool includeTrackNumber = true,
|
||||
bool includeOptionalProperties = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true)
|
||||
{
|
||||
return new UpdateArtistTrackRequest(
|
||||
includeTrackId ? (trackId ?? _faker.Random.Guid()) : null,
|
||||
includePath ? (path ?? Path.Combine(Path.GetTempPath(), "lumina-tracks", _faker.System.FileName())) : null,
|
||||
includeMetadata ? (metadata ?? _audioMetadataDtoFixture.Create()) : null,
|
||||
includeTrackNumber ? (trackNumber ?? _faker.Random.Int(1, 30)) : null,
|
||||
includeOptionalProperties ? (discNumber ?? _faker.Random.Int(1, 3)) : null,
|
||||
includeOptionalProperties ? (script ?? _faker.Random.AlphaNumeric(4)) : null,
|
||||
includeOptionalProperties ? (key ?? _faker.PickRandom<MusicKey>()) : null,
|
||||
includeOptionalProperties ? (bpm ?? _faker.Random.Int(40, 220)) : null,
|
||||
includeOptionalProperties ? (work ?? _faker.Lorem.Sentence()) : null,
|
||||
includeOptionalProperties ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null,
|
||||
includeOptionalProperties ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null,
|
||||
includeOptionalProperties ? (musicBrainzWorkId ?? _faker.Random.Guid()) : null,
|
||||
includeOptionalProperties ? (moods ?? [.. _moodDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
|
||||
includeOptionalProperties ? (isrcs ?? [.. _isrcDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
|
||||
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="UpdateArtistTrackRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<UpdateArtistTrackRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.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.IO;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AddTrackRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddTrackRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
private readonly MoodDtoFixture _moodDtoFixture = new();
|
||||
private readonly IsrcDtoFixture _isrcDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid request to add a track.
|
||||
/// </summary>
|
||||
/// <param name="path">Optional. The file system path of the track.</param>
|
||||
/// <param name="metadata">Optional. The audio metadata of the track.</param>
|
||||
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
|
||||
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
|
||||
/// <param name="script">Optional. The script used by the language of the track.</param>
|
||||
/// <param name="key">Optional. The musical key of the track.</param>
|
||||
/// <param name="bpm">Optional. The tempo of the track in beats per minute.</param>
|
||||
/// <param name="work">Optional. The title of the work the track is a recording of.</param>
|
||||
/// <param name="musicBrainzRecordingId">Optional. The MusicBrainz identifier of the recording.</param>
|
||||
/// <param name="musicBrainzTrackId">Optional. The MusicBrainz identifier of the track.</param>
|
||||
/// <param name="musicBrainzWorkId">Optional. The MusicBrainz identifier of the work.</param>
|
||||
/// <param name="moods">Optional. The list of moods of the track.</param>
|
||||
/// <param name="isrcs">Optional. The list of ISRC of the track.</param>
|
||||
/// <param name="contributors">Optional. The list of media contributors that performed on the track.</param>
|
||||
/// <param name="ratings">Optional. The list of ratings for this track.</param>
|
||||
/// <param name="includePath">Whether the path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMetadata">Whether the metadata should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTrackNumber">Whether the track number should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, 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 request to add a track.</returns>
|
||||
public AddTrackRequest Create(
|
||||
string? path = null,
|
||||
AudioMetadataDto? metadata = null,
|
||||
int? trackNumber = null,
|
||||
int? discNumber = null,
|
||||
string? script = null,
|
||||
MusicKey? key = null,
|
||||
int? bpm = null,
|
||||
string? work = null,
|
||||
Guid? musicBrainzRecordingId = null,
|
||||
Guid? musicBrainzTrackId = null,
|
||||
Guid? musicBrainzWorkId = null,
|
||||
List<MoodDto>? moods = null,
|
||||
List<IsrcDto>? isrcs = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
bool includePath = true,
|
||||
bool includeMetadata = true,
|
||||
bool includeTrackNumber = true,
|
||||
bool includeOptionalProperties = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true)
|
||||
{
|
||||
return new AddTrackRequest(
|
||||
includePath ? path ?? Path.Combine(Path.GetTempPath(), "lumina-tracks", _faker.System.FileName()) : null,
|
||||
includeMetadata ? metadata ?? _audioMetadataDtoFixture.Create() : null,
|
||||
includeTrackNumber ? trackNumber ?? _faker.Random.Int(1, 30) : null,
|
||||
includeOptionalProperties ? discNumber ?? _faker.Random.Int(1, 3) : null,
|
||||
includeOptionalProperties ? script ?? _faker.Random.AlphaNumeric(4) : null,
|
||||
includeOptionalProperties ? key ?? _faker.PickRandom<MusicKey>() : null,
|
||||
includeOptionalProperties ? bpm ?? _faker.Random.Int(40, 220) : null,
|
||||
includeOptionalProperties ? work ?? _faker.Lorem.Sentence() : null,
|
||||
includeOptionalProperties ? musicBrainzRecordingId ?? _faker.Random.Guid() : null,
|
||||
includeOptionalProperties ? musicBrainzTrackId ?? _faker.Random.Guid() : null,
|
||||
includeOptionalProperties ? musicBrainzWorkId ?? _faker.Random.Guid() : null,
|
||||
includeOptionalProperties ? moods ?? _moodDtoFixture.CreateMany(_faker.Random.Int(1, 3)) : null,
|
||||
includeOptionalProperties ? isrcs ?? _isrcDtoFixture.CreateMany(_faker.Random.Int(1, 3)) : null,
|
||||
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="AddTrackRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<AddTrackRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.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.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateTrackRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateTrackRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
private readonly MoodDtoFixture _moodDtoFixture = new();
|
||||
private readonly IsrcDtoFixture _isrcDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid request to update a track.
|
||||
/// </summary>
|
||||
/// <param name="path">Optional. The file system path of the track.</param>
|
||||
/// <param name="metadata">Optional. The audio metadata of the track.</param>
|
||||
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
|
||||
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
|
||||
/// <param name="script">Optional. The script used by the language of the track.</param>
|
||||
/// <param name="key">Optional. The musical key of the track.</param>
|
||||
/// <param name="bpm">Optional. The tempo of the track in beats per minute.</param>
|
||||
/// <param name="work">Optional. The title of the work the track is a recording of.</param>
|
||||
/// <param name="musicBrainzRecordingId">Optional. The MusicBrainz identifier of the recording.</param>
|
||||
/// <param name="musicBrainzTrackId">Optional. The MusicBrainz identifier of the track.</param>
|
||||
/// <param name="musicBrainzWorkId">Optional. The MusicBrainz identifier of the work.</param>
|
||||
/// <param name="moods">Optional. The moods of the track.</param>
|
||||
/// <param name="isrcs">Optional. The ISRC codes of the track.</param>
|
||||
/// <param name="contributors">Optional. The media contributors that performed on the track.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the track.</param>
|
||||
/// <param name="includeOptionalProperties">Whether the optional properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="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="includePath">Whether the path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMetadata">Whether the metadata should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTrackNumber">Whether the track number should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created request to update a track.</returns>
|
||||
public UpdateTrackRequest Create(
|
||||
string? path = null,
|
||||
AudioMetadataDto? metadata = null,
|
||||
int? trackNumber = null,
|
||||
int? discNumber = null,
|
||||
string? script = null,
|
||||
MusicKey? key = null,
|
||||
int? bpm = null,
|
||||
string? work = null,
|
||||
Guid? musicBrainzRecordingId = null,
|
||||
Guid? musicBrainzTrackId = null,
|
||||
Guid? musicBrainzWorkId = null,
|
||||
List<MoodDto>? moods = null,
|
||||
List<IsrcDto>? isrcs = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
bool includeOptionalProperties = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true,
|
||||
bool includePath = true,
|
||||
bool includeMetadata = true,
|
||||
bool includeTrackNumber = true)
|
||||
{
|
||||
return new UpdateTrackRequest(
|
||||
includePath ? (path ?? _faker.System.FilePath()) : null,
|
||||
includeMetadata ? (metadata ?? _audioMetadataDtoFixture.Create()) : null,
|
||||
includeTrackNumber ? (trackNumber ?? _faker.Random.Int(1, 20)) : null,
|
||||
includeOptionalProperties ? (discNumber ?? _faker.Random.Int(1, 3)) : null,
|
||||
includeOptionalProperties ? (script ?? _faker.Random.String2(_faker.Random.Number(1, 50))) : null,
|
||||
includeOptionalProperties ? (key ?? _faker.PickRandom<MusicKey>()) : null,
|
||||
includeOptionalProperties ? (bpm ?? _faker.Random.Int(40, 240)) : null,
|
||||
includeOptionalProperties ? (work ?? _faker.Music.Genre()) : null,
|
||||
includeOptionalProperties ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null,
|
||||
includeOptionalProperties ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null,
|
||||
includeOptionalProperties ? (musicBrainzWorkId ?? _faker.Random.Guid()) : null,
|
||||
includeOptionalProperties ? (moods ?? [.. _moodDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
|
||||
includeOptionalProperties ? (isrcs ?? [.. _isrcDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
|
||||
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="UpdateTrackRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<UpdateTrackRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.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.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="TrackResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
private readonly MoodDtoFixture _moodDtoFixture = new();
|
||||
private readonly IsrcDtoFixture _isrcDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="TrackResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the track.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library this track belongs to.</param>
|
||||
/// <param name="path">Optional. The file system path of the track.</param>
|
||||
/// <param name="metadata">Optional. The audio metadata of the track.</param>
|
||||
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
|
||||
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
|
||||
/// <param name="script">Optional. The script used by the language of the track.</param>
|
||||
/// <param name="key">Optional. The musical key of the track.</param>
|
||||
/// <param name="bpm">Optional. The tempo of the track in beats per minute.</param>
|
||||
/// <param name="work">Optional. The title of the work the track is a recording of.</param>
|
||||
/// <param name="musicBrainzRecordingId">Optional. The MusicBrainz recording Id of the track.</param>
|
||||
/// <param name="musicBrainzTrackId">Optional. The MusicBrainz track Id of the track.</param>
|
||||
/// <param name="musicBrainzWorkId">Optional. The MusicBrainz work Id of the track.</param>
|
||||
/// <param name="createdOnUtc">Optional. The date and time when the track was created.</param>
|
||||
/// <param name="updatedOnUtc">Optional. The date and time when the track was updated.</param>
|
||||
/// <param name="moods">Optional. The list of moods of the track.</param>
|
||||
/// <param name="isrcs">Optional. The list of ISRCs of the track.</param>
|
||||
/// <param name="contributors">Optional. The list of contributor references of the track.</param>
|
||||
/// <param name="ratings">Optional. The list of ratings of the track.</param>
|
||||
/// <param name="includeMusicBrainzRecordingId">Whether the MusicBrainz recording Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzTrackId">Whether the MusicBrainz track Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzWorkId">Whether the MusicBrainz work Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="TrackResponse"/>.</returns>
|
||||
public TrackResponse Create(
|
||||
Guid? id = null,
|
||||
Guid? albumId = null,
|
||||
Guid? libraryId = null,
|
||||
string? path = null,
|
||||
AudioMetadataDto? metadata = null,
|
||||
int? trackNumber = null,
|
||||
int? discNumber = null,
|
||||
string? script = null,
|
||||
MusicKey? key = null,
|
||||
int? bpm = null,
|
||||
string? work = null,
|
||||
Guid? musicBrainzRecordingId = null,
|
||||
Guid? musicBrainzTrackId = null,
|
||||
Guid? musicBrainzWorkId = null,
|
||||
DateTime? createdOnUtc = null,
|
||||
DateTime? updatedOnUtc = null,
|
||||
List<MoodDto>? moods = null,
|
||||
List<IsrcDto>? isrcs = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
bool includeMusicBrainzRecordingId = true,
|
||||
bool includeMusicBrainzTrackId = true,
|
||||
bool includeMusicBrainzWorkId = true)
|
||||
{
|
||||
return new TrackResponse(
|
||||
id ?? Guid.NewGuid(),
|
||||
albumId ?? Guid.NewGuid(),
|
||||
libraryId ?? Guid.NewGuid(),
|
||||
path ?? _faker.System.FilePath(),
|
||||
metadata ?? _audioMetadataDtoFixture.Create(),
|
||||
trackNumber ?? _faker.Random.Int(1, 30),
|
||||
discNumber ?? (_faker.Random.Bool() ? _faker.Random.Int(1, 3) : null),
|
||||
script ?? (_faker.Random.Bool() ? _faker.Random.AlphaNumeric(4) : null),
|
||||
key ?? (_faker.Random.Bool() ? _faker.PickRandom<MusicKey>() : null),
|
||||
bpm ?? (_faker.Random.Bool() ? _faker.Random.Int(40, 220) : null),
|
||||
work ?? (_faker.Random.Bool() ? _faker.Lorem.Sentence() : null),
|
||||
includeMusicBrainzRecordingId ? (musicBrainzRecordingId ?? Guid.NewGuid()) : null,
|
||||
includeMusicBrainzTrackId ? (musicBrainzTrackId ?? Guid.NewGuid()) : null,
|
||||
includeMusicBrainzWorkId ? (musicBrainzWorkId ?? Guid.NewGuid()) : null,
|
||||
createdOnUtc ?? _faker.Date.Past().ToUniversalTime(),
|
||||
updatedOnUtc ?? (_faker.Random.Bool() ? _faker.Date.Recent().ToUniversalTime() : null),
|
||||
moods ?? _moodDtoFixture.CreateMany(1),
|
||||
isrcs ?? _isrcDtoFixture.CreateMany(1),
|
||||
contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(1),
|
||||
ratings ?? _audioRatingDtoFixture.CreateMany(1));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="TrackResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<TrackResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="Mood"/> domain value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MoodFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="Mood"/>.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional. The name of the mood. If not provided, a random name is generated.</param>
|
||||
/// <returns>The created <see cref="Mood"/>.</returns>
|
||||
public Mood Create(
|
||||
string? name = null)
|
||||
{
|
||||
Result<Mood> moodResult = Mood.Create(name ?? _faker.Lorem.Word());
|
||||
|
||||
if (moodResult.IsFailure)
|
||||
throw new InvalidOperationException("Failed to create Mood: " + string.Join(", ", moodResult.Errors));
|
||||
return moodResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="Mood"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="Mood"/> instances.</returns>
|
||||
public List<Mood> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="LibraryId"/> domain value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryIdFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="LibraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The raw value of the library Id.</param>
|
||||
/// <returns>The created <see cref="LibraryId"/>.</returns>
|
||||
public LibraryId Create(
|
||||
Guid? value = null)
|
||||
{
|
||||
return value is null ? LibraryId.CreateUnique() : LibraryId.Create(value.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="LibraryId"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="LibraryId"/> instances.</returns>
|
||||
public List<LibraryId> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MediaContributorId"/> domain value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorIdFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="MediaContributorId"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The raw value of the media contributor Id.</param>
|
||||
/// <returns>The created <see cref="MediaContributorId"/>.</returns>
|
||||
public MediaContributorId Create(
|
||||
Guid? value = null)
|
||||
{
|
||||
return value is null ? MediaContributorId.CreateUnique() : MediaContributorId.Create(value.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="MediaContributorId"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MediaContributorId"/> instances.</returns>
|
||||
public List<MediaContributorId> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="Artist"/> domain aggregate root.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ArtistFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly AlbumFixture _albumFixture = new();
|
||||
private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new();
|
||||
private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="Artist"/> domain aggregate root.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library this artist belongs to.</param>
|
||||
/// <param name="name">Optional. The name of the artist.</param>
|
||||
/// <param name="website">Optional. The website of the artist.</param>
|
||||
/// <param name="musicBrainzArtistId">Optional. The MusicBrainz identifier of the artist.</param>
|
||||
/// <param name="contributors">Optional. The media contributors that make up the artist.</param>
|
||||
/// <param name="albums">Optional. The albums of the artist. Defaults to a single random album, since an artist must have at least one.</param>
|
||||
/// <returns>The created <see cref="Artist"/> domain aggregate root.</returns>
|
||||
public Artist Create(
|
||||
LibraryId? libraryId = null,
|
||||
string? name = null,
|
||||
Optional<string>? website = null,
|
||||
Optional<MusicBrainzId>? musicBrainzArtistId = null,
|
||||
List<MusicMediaContributor>? contributors = null,
|
||||
List<Album>? albums = null)
|
||||
{
|
||||
Result<Artist> artistResult = Artist.Create(
|
||||
libraryId ?? _libraryIdFixture.Create(),
|
||||
name ?? _faker.Name.FullName(),
|
||||
website ?? Optional<string>.Some(_faker.Internet.Url()),
|
||||
musicBrainzArtistId ?? Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create()),
|
||||
contributors ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _musicMediaContributorFixture.Create())],
|
||||
albums ?? [_albumFixture.Create()]);
|
||||
|
||||
if (artistResult.IsFailure)
|
||||
throw new InvalidOperationException("Failed to create Artist: " + string.Join(", ", artistResult.Errors));
|
||||
return artistResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="Artist"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="Artist"/> instances.</returns>
|
||||
public List<Artist> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
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.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.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="Album"/> domain entity.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumFixture
|
||||
{
|
||||
private readonly Faker _faker = 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();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="Album"/> domain entity.
|
||||
/// </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 of the album.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the album.</param>
|
||||
/// <param name="tracks">Optional. The tracks of the album. Defaults to an empty list so callers can control the initial tracks.</param>
|
||||
/// <returns>The created <see cref="Album"/> domain entity.</returns>
|
||||
public Album Create(
|
||||
AlbumMetadata? metadata = null,
|
||||
Optional<MusicMediaFormat>? mediaFormat = null,
|
||||
Optional<Barcode>? barcode = null,
|
||||
Optional<string>? catalogNumber = null,
|
||||
Optional<MusicBrainzId>? musicBrainzReleaseId = null,
|
||||
Optional<MusicBrainzId>? musicBrainzReleaseGroupId = null,
|
||||
Optional<MusicBrainzId>? musicBrainzReleaseArtistId = null,
|
||||
List<MusicMediaContributor>? contributors = null,
|
||||
List<AudioRating>? ratings = null,
|
||||
List<Track>? tracks = null)
|
||||
{
|
||||
Result<Album> albumResult = Album.Create(
|
||||
metadata ?? _albumMetadataFixture.Create(),
|
||||
mediaFormat ?? Optional<MusicMediaFormat>.Some(_faker.PickRandom<MusicMediaFormat>()),
|
||||
barcode ?? Optional<Barcode>.Some(_barcodeFixture.Create()),
|
||||
catalogNumber ?? Optional<string>.Some(_faker.Random.String2(_faker.Random.Int(5, 20))),
|
||||
musicBrainzReleaseId ?? Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create()),
|
||||
musicBrainzReleaseGroupId ?? Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create()),
|
||||
musicBrainzReleaseArtistId ?? Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create()),
|
||||
contributors ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _musicMediaContributorFixture.Create())],
|
||||
ratings ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _audioRatingFixture.Create())],
|
||||
tracks ?? []);
|
||||
|
||||
if (albumResult.IsFailure)
|
||||
throw new InvalidOperationException("Failed to create Album: " + string.Join(", ", albumResult.Errors));
|
||||
return albumResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="Album"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="Album"/> instances.</returns>
|
||||
public List<Album> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.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.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="Track"/> domain entity.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly AudioMetadataFixture _audioMetadataFixture = new();
|
||||
private readonly MoodFixture _moodFixture = new();
|
||||
private readonly IsrcFixture _isrcFixture = new();
|
||||
private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new();
|
||||
private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new();
|
||||
private readonly AudioRatingFixture _audioRatingFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="Track"/> domain entity.
|
||||
/// </summary>
|
||||
/// <param name="path">Optional. The file system path of the track.</param>
|
||||
/// <param name="metadata">Optional. The audio metadata of the track.</param>
|
||||
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
|
||||
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
|
||||
/// <param name="moods">Optional. The moods of the track.</param>
|
||||
/// <param name="script">Optional. The script used by the language of the track.</param>
|
||||
/// <param name="key">Optional. The musical key of the track.</param>
|
||||
/// <param name="bpm">Optional. The tempo of the track in beats per minute.</param>
|
||||
/// <param name="isrcs">Optional. The ISRCs of the track.</param>
|
||||
/// <param name="work">Optional. The title of the work the track is a recording of.</param>
|
||||
/// <param name="musicBrainzRecordingId">Optional. The MusicBrainz identifier of the recording.</param>
|
||||
/// <param name="musicBrainzTrackId">Optional. The MusicBrainz identifier of the track.</param>
|
||||
/// <param name="musicBrainzWorkId">Optional. The MusicBrainz identifier of the work.</param>
|
||||
/// <param name="contributors">Optional. The media contributors of the track.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the track.</param>
|
||||
/// <returns>The created <see cref="Track"/> domain entity.</returns>
|
||||
public Track Create(
|
||||
string? path = null,
|
||||
AudioMetadata? metadata = null,
|
||||
int? trackNumber = null,
|
||||
Optional<int>? discNumber = null,
|
||||
List<Mood>? moods = null,
|
||||
Optional<string>? script = null,
|
||||
Optional<MusicKey>? key = null,
|
||||
Optional<int>? bpm = null,
|
||||
List<Isrc>? isrcs = null,
|
||||
Optional<string>? work = null,
|
||||
Optional<MusicBrainzId>? musicBrainzRecordingId = null,
|
||||
Optional<MusicBrainzId>? musicBrainzTrackId = null,
|
||||
Optional<MusicBrainzId>? musicBrainzWorkId = null,
|
||||
List<MusicMediaContributor>? contributors = null,
|
||||
List<AudioRating>? ratings = null)
|
||||
{
|
||||
Result<Track> trackResult = Track.Create(
|
||||
path ?? _faker.System.FilePath(),
|
||||
metadata ?? _audioMetadataFixture.Create(),
|
||||
trackNumber ?? _faker.Random.Int(1, 30),
|
||||
discNumber ?? Optional<int>.Some(_faker.Random.Int(1, 2)),
|
||||
moods ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _moodFixture.Create())],
|
||||
script ?? Optional<string>.Some(_faker.Lorem.Word()),
|
||||
key ?? Optional<MusicKey>.Some(_faker.PickRandom<MusicKey>()),
|
||||
bpm ?? Optional<int>.Some(_faker.Random.Int(60, 220)),
|
||||
isrcs ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _isrcFixture.Create())],
|
||||
work ?? Optional<string>.Some(_faker.Lorem.Sentence()),
|
||||
musicBrainzRecordingId ?? Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create()),
|
||||
musicBrainzTrackId ?? Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create()),
|
||||
musicBrainzWorkId ?? Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create()),
|
||||
contributors ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _musicMediaContributorFixture.Create())],
|
||||
ratings ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _audioRatingFixture.Create())]);
|
||||
|
||||
if (trackResult.IsFailure)
|
||||
throw new InvalidOperationException("Failed to create Track: " + string.Join(", ", trackResult.Errors));
|
||||
return trackResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="Track"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="Track"/> instances.</returns>
|
||||
public List<Track> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AlbumId"/> domain value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumIdFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="AlbumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The value used to create the <see cref="AlbumId"/>. If not provided, a random value is generated.</param>
|
||||
/// <returns>The created <see cref="AlbumId"/>.</returns>
|
||||
public AlbumId Create(Guid? value = null)
|
||||
{
|
||||
return value is null ? AlbumId.CreateUnique() : AlbumId.Create(value.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="AlbumId"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="AlbumId"/> instances.</returns>
|
||||
public List<AlbumId> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
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.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AlbumMetadata"/> domain value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumMetadataFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly GenreFixture _genreFixture = new();
|
||||
private readonly TagFixture _tagFixture = new();
|
||||
private readonly ReleaseInfoFixture _releaseInfoFixture = new();
|
||||
private readonly LanguageInfoFixture _languageInfoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="AlbumMetadata"/>.
|
||||
/// </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. The description of the album.</param>
|
||||
/// <param name="releaseInfo">Optional. The release information of the album.</param>
|
||||
/// <param name="genres">Optional. The genres of the album.</param>
|
||||
/// <param name="tags">Optional. The tags associated with 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="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>
|
||||
/// <returns>The created <see cref="AlbumMetadata"/>.</returns>
|
||||
public AlbumMetadata Create(
|
||||
string? title = null,
|
||||
Optional<string>? originalTitle = null,
|
||||
Optional<string>? description = null,
|
||||
ReleaseInfo? releaseInfo = null,
|
||||
List<Genre>? genres = null,
|
||||
List<Tag>? tags = null,
|
||||
Optional<LanguageInfo>? language = null,
|
||||
Optional<LanguageInfo>? originalLanguage = null,
|
||||
Optional<MusicReleaseType>? releaseType = null,
|
||||
Optional<MusicReleaseStatus>? releaseStatus = null,
|
||||
Optional<int>? totalDiscs = null,
|
||||
int? totalTracks = null)
|
||||
{
|
||||
Result<AlbumMetadata> metadataResult = AlbumMetadata.Create(
|
||||
title ?? _faker.Commerce.ProductName(),
|
||||
originalTitle ?? Optional<string>.None(),
|
||||
description ?? Optional<string>.Some(_faker.Lorem.Sentence()),
|
||||
releaseInfo ?? _releaseInfoFixture.Create(),
|
||||
genres ?? [_genreFixture.Create(), _genreFixture.Create()],
|
||||
tags ?? [_tagFixture.Create(), _tagFixture.Create()],
|
||||
language ?? Optional<LanguageInfo>.Some(_languageInfoFixture.Create()),
|
||||
originalLanguage ?? Optional<LanguageInfo>.None(),
|
||||
releaseType ?? Optional<MusicReleaseType>.Some(_faker.PickRandom<MusicReleaseType>()),
|
||||
releaseStatus ?? Optional<MusicReleaseStatus>.Some(_faker.PickRandom<MusicReleaseStatus>()),
|
||||
totalDiscs ?? Optional<int>.Some(_faker.Random.Int(1, 4)),
|
||||
totalTracks ?? _faker.Random.Int(1, 50));
|
||||
|
||||
if (metadataResult.IsFailure)
|
||||
throw new InvalidOperationException("Failed to create AlbumMetadata: " + string.Join(", ", metadataResult.Errors));
|
||||
return metadataResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="AlbumMetadata"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="AlbumMetadata"/> instances.</returns>
|
||||
public List<AlbumMetadata> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ArtistId"/> domain value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ArtistIdFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ArtistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The value used to create the <see cref="ArtistId"/>. If not provided, a random value is generated.</param>
|
||||
/// <returns>The created <see cref="ArtistId"/>.</returns>
|
||||
public ArtistId Create(
|
||||
Guid? value = null)
|
||||
{
|
||||
return value is null ? ArtistId.CreateUnique() : ArtistId.Create(value.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="ArtistId"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ArtistId"/> instances.</returns>
|
||||
public List<ArtistId> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="Barcode"/> domain value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BarcodeFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="Barcode"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The value of the barcode. If not provided, a random valid barcode is generated.</param>
|
||||
/// <returns>The created <see cref="Barcode"/>.</returns>
|
||||
public Barcode Create(
|
||||
string? value = null)
|
||||
{
|
||||
Result<Barcode> barcodeResult = Barcode.Create(value ?? GenerateRandomValue());
|
||||
|
||||
if (barcodeResult.IsFailure)
|
||||
throw new InvalidOperationException("Failed to create Barcode: " + string.Join(", ", barcodeResult.Errors));
|
||||
return barcodeResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="Barcode"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="Barcode"/> instances.</returns>
|
||||
public List<Barcode> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a random value matching the <c>^\d{12,13}$</c> barcode format.
|
||||
/// </summary>
|
||||
/// <returns>The generated barcode value.</returns>
|
||||
private string GenerateRandomValue()
|
||||
{
|
||||
int digitCount = _faker.Random.Int(12, 13);
|
||||
return _faker.Random.String2(digitCount, "0123456789");
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="Isrc"/> domain value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsrcFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="Isrc"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The value of the ISRC. If not provided, a random valid ISRC is generated.</param>
|
||||
/// <returns>The created <see cref="Isrc"/>.</returns>
|
||||
public Isrc Create(
|
||||
string? value = null)
|
||||
{
|
||||
Result<Isrc> isrcResult = Isrc.Create(value ?? GenerateRandomValue());
|
||||
|
||||
if (isrcResult.IsFailure)
|
||||
throw new InvalidOperationException("Failed to create Isrc: " + string.Join(", ", isrcResult.Errors));
|
||||
return isrcResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="Isrc"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="Isrc"/> instances.</returns>
|
||||
public List<Isrc> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a random value matching the <c>^[A-Z]{2}[A-Z0-9]{3}[0-9]{7}$</c> ISRC format.
|
||||
/// </summary>
|
||||
/// <returns>The generated ISRC value.</returns>
|
||||
private string GenerateRandomValue()
|
||||
{
|
||||
string countryCode = _faker.Random.String2(2, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
|
||||
string registrantCode = _faker.Random.String2(3, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
|
||||
string yearAndDesignationCode = _faker.Random.Number(1000000, 9999999).ToString();
|
||||
return countryCode + registrantCode + yearAndDesignationCode;
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzId"/> domain value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzIdFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="MusicBrainzId"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The value used to create the <see cref="MusicBrainzId"/>. If not provided, a random value is generated.</param>
|
||||
/// <returns>The created <see cref="MusicBrainzId"/>.</returns>
|
||||
public MusicBrainzId Create(
|
||||
Guid? value = null)
|
||||
{
|
||||
return MusicBrainzId.Create(value ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzId"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzId"/> instances.</returns>
|
||||
public List<MusicBrainzId> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicMediaContributor"/> domain value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicMediaContributorFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MediaContributorIdFixture _mediaContributorIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="MusicMediaContributor"/>.
|
||||
/// </summary>
|
||||
/// <param name="contributorId">Optional. The unique identifier of the media contributor.</param>
|
||||
/// <param name="role">Optional. The role the contributor played.</param>
|
||||
/// <returns>The created <see cref="MusicMediaContributor"/>.</returns>
|
||||
public MusicMediaContributor Create(
|
||||
MediaContributorId? contributorId = null,
|
||||
MediaContributorRole? role = null)
|
||||
{
|
||||
Result<MusicMediaContributor> contributorResult = MusicMediaContributor.Create(
|
||||
contributorId ?? _mediaContributorIdFixture.Create(),
|
||||
role ?? _faker.PickRandom<MediaContributorRole>());
|
||||
|
||||
if (contributorResult.IsFailure)
|
||||
throw new InvalidOperationException("Failed to create MusicMediaContributor: " + string.Join(", ", contributorResult.Errors));
|
||||
return contributorResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicMediaContributor"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicMediaContributor"/> instances.</returns>
|
||||
public List<MusicMediaContributor> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="TrackId"/> domain value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackIdFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="TrackId"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The value used to create the <see cref="TrackId"/>. If not provided, a random value is generated.</param>
|
||||
/// <returns>The created <see cref="TrackId"/>.</returns>
|
||||
public TrackId Create(
|
||||
Guid? value = null)
|
||||
{
|
||||
return value is null ? TrackId.CreateUnique() : TrackId.Create(value.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="TrackId"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="TrackId"/> instances.</returns>
|
||||
public List<TrackId> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+749
@@ -0,0 +1,749 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
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="TrackRepository"/> class, exercising it against a real SQLite database.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackRepositoryTests
|
||||
{
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new();
|
||||
private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new();
|
||||
private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new();
|
||||
private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenCalledWithAValidTrack_ShouldPersistTheTrackAndItsChildren()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
MediaContributorEntity performer = _mediaContributorEntityFixture.Create(displayName: $"Performer {Guid.NewGuid()}");
|
||||
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false);
|
||||
track.Tags = [_tagEntityFixture.Create(name: "InsertTag")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "InsertGenre")];
|
||||
track.Moods = [_trackMoodEntityFixture.Create(name: "Calm")];
|
||||
track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")];
|
||||
track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
|
||||
track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: performer.Id, role: MediaContributorRole.Vocals)];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(track, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
TrackEntity? storedTrack = await context.Tracks
|
||||
.AsNoTracking()
|
||||
.Include(candidate => candidate.Tags)
|
||||
.Include(candidate => candidate.Genres)
|
||||
.Include(candidate => candidate.Moods)
|
||||
.Include(candidate => candidate.Isrcs)
|
||||
.Include(candidate => candidate.Ratings)
|
||||
.Include(candidate => candidate.Contributors)
|
||||
.FirstOrDefaultAsync(candidate => candidate.Id == track.Id);
|
||||
Assert.NotNull(storedTrack);
|
||||
Assert.Equal("/music/queen/bohemian-rhapsody.flac", storedTrack!.Path);
|
||||
Assert.Single(storedTrack.Tags);
|
||||
Assert.Single(storedTrack.Genres);
|
||||
Assert.Single(storedTrack.Moods);
|
||||
Assert.Single(storedTrack.Isrcs);
|
||||
Assert.Single(storedTrack.Ratings);
|
||||
TrackContributorEntity storedContributor = Assert.Single(storedTrack.Contributors);
|
||||
Assert.Equal(performer.Id, storedContributor.MediaContributorId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAnotherTrackOfTheSameLibraryHasTheSamePath_ShouldReturnTrackAlreadyExists()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-insert-conflict-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
TrackEntity existingTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/youre-my-best-friend.flac", includeMetadata: false);
|
||||
context.Tracks.Add(existingTrack);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/youre-my-best-friend.flac", includeMetadata: false);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(track, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldPersistTheTrack()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-insert-otherlibrary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid firstLibraryId = Guid.NewGuid();
|
||||
AlbumEntity firstAlbum = await SeedAlbumAsync(context, firstLibraryId);
|
||||
TrackEntity existingTrack = _trackEntityFixture.Create(albumId: firstAlbum.Id, libraryId: firstLibraryId, path: "/music/queen/we-will-rock-you.flac", includeMetadata: false);
|
||||
context.Tracks.Add(existingTrack);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
Guid secondLibraryId = Guid.NewGuid();
|
||||
AlbumEntity secondAlbum = await SeedAlbumAsync(context, secondLibraryId);
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: secondAlbum.Id, libraryId: secondLibraryId, path: "/music/queen/we-will-rock-you.flac", includeMetadata: false);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(track, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
TrackEntity? storedTrack = await context.Tracks.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == track.Id);
|
||||
Assert.NotNull(storedTrack);
|
||||
Assert.Equal(secondLibraryId, storedTrack!.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetExistingPathsAsync_WhenCalled_ShouldReturnOnlyThePathsOfTheLibraryCaseSensitively()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-existingpaths-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
TrackEntity trackOfLibrary = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/Queen/Love-Of-My-Life.flac", includeMetadata: false);
|
||||
context.Tracks.Add(trackOfLibrary);
|
||||
|
||||
Guid anotherLibraryId = Guid.NewGuid();
|
||||
AlbumEntity anotherAlbum = await SeedAlbumAsync(context, anotherLibraryId);
|
||||
TrackEntity trackOfAnotherLibrary = _trackEntityFixture.Create(albumId: anotherAlbum.Id, libraryId: anotherLibraryId, path: "/music/Queen/Love-Of-My-Life.flac", includeMetadata: false);
|
||||
context.Tracks.Add(trackOfAnotherLibrary);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyCollection<string>> result = await sut.GetExistingPathsAsync(
|
||||
libraryId, ["/music/Queen/Love-Of-My-Life.flac", "/music/queen/love-of-my-life.flac", "/music/queen/we-are-the-champions.flac"], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
string existingPath = Assert.Single(result.Value);
|
||||
// The comparison is ordinal, so neither the same path of another library nor a case variant of the path is reported as existing.
|
||||
Assert.Equal("/music/Queen/Love-Of-My-Life.flac", existingPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeAnyAuditColumn()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-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);
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
MediaContributorEntity performer = _mediaContributorEntityFixture.Create(displayName: $"Performer {Guid.NewGuid()}");
|
||||
context.MediaContributors.Add(performer);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/dont-stop-me-now.flac", includeMetadata: false);
|
||||
track.Tags = [_tagEntityFixture.Create(name: "NoopTag")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "NoopGenre")];
|
||||
track.Moods = [_trackMoodEntityFixture.Create(name: "Calm")];
|
||||
track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")];
|
||||
track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
|
||||
track.Contributors =
|
||||
[_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: performer.Id, role: MediaContributorRole.Vocals)];
|
||||
context.Tracks.Add(track);
|
||||
await context.SaveChangesAsync();
|
||||
Guid contributorId = track.Contributors[0].Id;
|
||||
DateTime contributorCreatedOnUtc = track.Contributors[0].CreatedOnUtc;
|
||||
TrackEntity incoming = await LoadDetachedTrackAsync(context, track.Id);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackEntity? storedTrack = await context.Tracks.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == track.Id);
|
||||
Assert.NotNull(storedTrack);
|
||||
Assert.Null(storedTrack!.UpdatedOnUtc);
|
||||
TrackContributorEntity storedContributor = Assert.Single(storedTrack.Contributors);
|
||||
Assert.Equal(contributorId, storedContributor.Id);
|
||||
Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc);
|
||||
Assert.Single(context.Set<TagEntity>().Where(tag => tag.Name == "NoopTag"));
|
||||
Assert.Single(context.Set<GenreEntity>().Where(genre => genre.Name == "NoopGenre"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenOnlyTheMetadataChanged_ShouldStampTheTrackAndKeepTheChildRowsUntouched()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-metadata-{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);
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
MediaContributorEntity performer = _mediaContributorEntityFixture.Create(displayName: $"Performer {Guid.NewGuid()}");
|
||||
context.MediaContributors.Add(performer);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/somebody-to-love.flac", includeMetadata: false);
|
||||
track.Contributors =
|
||||
[_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: performer.Id, role: MediaContributorRole.Vocals)];
|
||||
context.Tracks.Add(track);
|
||||
await context.SaveChangesAsync();
|
||||
Guid contributorId = track.Contributors[0].Id;
|
||||
DateTime contributorCreatedOnUtc = track.Contributors[0].CreatedOnUtc;
|
||||
TrackEntity incoming = await LoadDetachedTrackAsync(context, track.Id);
|
||||
incoming.Title = "Somebody to Love";
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackEntity? storedTrack = await context.Tracks.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == track.Id);
|
||||
Assert.NotNull(storedTrack);
|
||||
Assert.Equal("Somebody to Love", storedTrack!.Title);
|
||||
// Only the edited track is stamped, the child rows keep their identity and their audit columns.
|
||||
Assert.Equal(utcNow, storedTrack.UpdatedOnUtc);
|
||||
Assert.Equal(userId, storedTrack.UpdatedBy);
|
||||
TrackContributorEntity storedContributor = Assert.Single(storedTrack.Contributors);
|
||||
Assert.Equal(contributorId, storedContributor.Id);
|
||||
Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAContributorIsRemoved_ShouldDeleteOnlyThatParticipationAndKeepTheOtherIdentity()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-removecontributor-{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);
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
Guid keptMediaContributorId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/another-one-bites-the-dust.flac", includeMetadata: false);
|
||||
TrackContributorEntity keptContributor = _trackContributorEntityFixture.Create(
|
||||
trackId: track.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer);
|
||||
TrackContributorEntity removedContributor = _trackContributorEntityFixture.Create(
|
||||
trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer);
|
||||
track.Contributors = [keptContributor, removedContributor];
|
||||
context.Tracks.Add(track);
|
||||
await context.SaveChangesAsync();
|
||||
Guid keptContributorId = keptContributor.Id;
|
||||
TrackEntity incoming = await LoadDetachedTrackAsync(context, track.Id);
|
||||
incoming.Contributors = [incoming.Contributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId)];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
List<TrackContributorEntity> storedContributors = await context.Set<TrackContributorEntity>()
|
||||
.AsNoTracking()
|
||||
.Where(contributor => contributor.TrackId == track.Id)
|
||||
.ToListAsync();
|
||||
TrackContributorEntity storedContributor = Assert.Single(storedContributors);
|
||||
Assert.Equal(keptContributorId, storedContributor.Id);
|
||||
Assert.Equal(keptMediaContributorId, storedContributor.MediaContributorId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAContributorIsAdded_ShouldInsertOnlyTheNewParticipationAndKeepTheExistingIdentity()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-addcontributor-{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);
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
Guid keptMediaContributorId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/crazy-little-thing-called-love.flac", includeMetadata: false);
|
||||
TrackContributorEntity keptContributor = _trackContributorEntityFixture.Create(
|
||||
trackId: track.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer);
|
||||
track.Contributors = [keptContributor];
|
||||
context.Tracks.Add(track);
|
||||
await context.SaveChangesAsync();
|
||||
Guid keptContributorId = keptContributor.Id;
|
||||
Guid addedMediaContributorId = Guid.NewGuid();
|
||||
|
||||
TrackEntity incoming = await LoadDetachedTrackAsync(context, track.Id);
|
||||
incoming.Contributors.Add(_trackContributorEntityFixture.Create(
|
||||
trackId: track.Id, mediaContributorId: addedMediaContributorId, role: MediaContributorRole.Vocals));
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
List<TrackContributorEntity> storedContributors = await context.Set<TrackContributorEntity>()
|
||||
.AsNoTracking()
|
||||
.Where(contributor => contributor.TrackId == track.Id)
|
||||
.ToListAsync();
|
||||
Assert.Equal(2, storedContributors.Count);
|
||||
Assert.Equal(keptContributorId, storedContributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId).Id);
|
||||
Assert.Contains(storedContributors, contributor => contributor.MediaContributorId == addedMediaContributorId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenDataContainsExistingTagAndGenreNames_ShouldReuseTheStoredTagAndGenreEntities()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-tags-{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);
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/radio-ga-ga.flac", includeMetadata: false);
|
||||
track.Tags = [_tagEntityFixture.Create(name: "ExistingTag")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")];
|
||||
context.Tracks.Add(track);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
TrackEntity incoming = await LoadDetachedTrackAsync(context, track.Id);
|
||||
incoming.Tags = [_tagEntityFixture.Create(name: "ExistingTag")];
|
||||
incoming.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackEntity? storedTrack = await context.Tracks
|
||||
.AsNoTracking()
|
||||
.Include(candidate => candidate.Tags)
|
||||
.Include(candidate => candidate.Genres)
|
||||
.FirstOrDefaultAsync(candidate => candidate.Id == track.Id);
|
||||
Assert.NotNull(storedTrack);
|
||||
Assert.Equal("ExistingTag", Assert.Single(storedTrack!.Tags).Name);
|
||||
Assert.Equal("ExistingGenre", Assert.Single(storedTrack.Genres).Name);
|
||||
// The shared rows are reused instead of being duplicated by the update.
|
||||
Assert.Single(context.Set<TagEntity>().Where(tag => tag.Name == "ExistingTag"));
|
||||
Assert.Single(context.Set<GenreEntity>().Where(genre => genre.Name == "ExistingGenre"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenOwnedAudioCollectionsChange_ShouldReconcileRatingsMoodsAndIsrcs()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-owned-{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);
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/the-show-must-go-on.flac", includeMetadata: false);
|
||||
track.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)
|
||||
];
|
||||
track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Energetic")];
|
||||
track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")];
|
||||
context.Tracks.Add(track);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
TrackEntity incoming = await LoadDetachedTrackAsync(context, track.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.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")];
|
||||
incoming.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000002")];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackEntity? storedTrack = await context.Tracks
|
||||
.AsNoTracking()
|
||||
.Include(candidate => candidate.Ratings)
|
||||
.Include(candidate => candidate.Moods)
|
||||
.Include(candidate => candidate.Isrcs)
|
||||
.FirstOrDefaultAsync(candidate => candidate.Id == track.Id);
|
||||
Assert.NotNull(storedTrack);
|
||||
Assert.Equal(3, storedTrack!.Ratings.Count);
|
||||
Assert.Contains(storedTrack.Ratings, rating => rating.Source == AudioRatingSource.MusicBrainz && rating.Value == 3M);
|
||||
Assert.Contains(storedTrack.Ratings, rating => rating.Source == AudioRatingSource.User && rating.Value == 5M);
|
||||
Assert.Contains(storedTrack.Ratings, rating => rating.Source == AudioRatingSource.Discogs && rating.Value == 1M);
|
||||
Assert.DoesNotContain(storedTrack.Ratings, rating => rating.Source == AudioRatingSource.LastFm);
|
||||
Assert.Equal(2, storedTrack.Moods.Count);
|
||||
Assert.Single(storedTrack.Moods, mood => mood.Name == "Calm");
|
||||
Assert.Contains(storedTrack.Moods, mood => mood.Name == "Upbeat");
|
||||
Assert.Equal(2, storedTrack.Isrcs.Count);
|
||||
Assert.Single(storedTrack.Isrcs, isrc => isrc.Value == "USRC12345678");
|
||||
Assert.Contains(storedTrack.Isrcs, isrc => isrc.Value == "GBAYE0000002");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenTrackExists_ShouldIncludeTheNavigationProperties()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyid-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
ArtistEntity artist = await context.Artists.AsNoTracking().FirstAsync(candidate => candidate.Id == album.ArtistId);
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/killer-queen.flac", includeMetadata: false);
|
||||
track.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")];
|
||||
track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")];
|
||||
track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")];
|
||||
track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
|
||||
track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
|
||||
context.Tracks.Add(track);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<TrackEntity?> result = await sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackEntity retrievedTrack = result.Value!;
|
||||
Assert.NotNull(retrievedTrack.Album);
|
||||
Assert.Equal(album.Id, retrievedTrack.Album!.Id);
|
||||
Assert.NotNull(retrievedTrack.Album.Artist);
|
||||
Assert.Equal(artist.Id, retrievedTrack.Album.Artist!.Id);
|
||||
Assert.Equal(2, retrievedTrack.Tags.Count);
|
||||
Assert.Equal(2, retrievedTrack.Genres.Count);
|
||||
Assert.Equal(2, retrievedTrack.Moods.Count);
|
||||
Assert.Single(retrievedTrack.Isrcs);
|
||||
Assert.Single(retrievedTrack.Ratings);
|
||||
Assert.Single(retrievedTrack.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnAnUntrackedTrack()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyid-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/seven-seas-of-rhye.flac", includeMetadata: false);
|
||||
context.Tracks.Add(track);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<TrackEntity?> result = await sut.GetByIdAsync(
|
||||
track.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(context.ChangeTracker.Entries<TrackEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByAlbumIdAsync_WhenCalled_ShouldReturnTheAlbumTracksInOrderWithTheirCollections()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyalbum-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
TrackEntity secondDiscTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/stone-cold-crazy.flac", trackNumber: 1, includeMetadata: false);
|
||||
secondDiscTrack.DiscNumber = 2;
|
||||
TrackEntity firstDiscSecondTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/good-old-fashioned-lover-boy.flac", trackNumber: 2, includeMetadata: false);
|
||||
firstDiscSecondTrack.DiscNumber = 1;
|
||||
TrackEntity firstDiscFirstTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/tie-your-mother-down.flac", trackNumber: 1, includeMetadata: false);
|
||||
firstDiscFirstTrack.DiscNumber = 1;
|
||||
firstDiscFirstTrack.Tags = [_tagEntityFixture.Create(name: "OrderedTag")];
|
||||
firstDiscFirstTrack.Genres = [_genreEntityFixture.Create(name: "OrderedGenre")];
|
||||
firstDiscFirstTrack.Moods = [_trackMoodEntityFixture.Create(name: "Calm")];
|
||||
firstDiscFirstTrack.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")];
|
||||
firstDiscFirstTrack.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
|
||||
firstDiscFirstTrack.Contributors = [_trackContributorEntityFixture.Create(trackId: firstDiscFirstTrack.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
|
||||
context.Tracks.AddRange(secondDiscTrack, firstDiscSecondTrack, firstDiscFirstTrack);
|
||||
|
||||
AlbumEntity anotherAlbum = await SeedAlbumAsync(context, libraryId);
|
||||
TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(albumId: anotherAlbum.Id, libraryId: libraryId, path: "/music/queen/play-the-game.flac", includeMetadata: false);
|
||||
context.Tracks.Add(trackOfAnotherAlbum);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
List<TrackEntity> albumTracks = [firstDiscFirstTrack, firstDiscSecondTrack, secondDiscTrack];
|
||||
Guid[] expectedOrder = [.. albumTracks
|
||||
.OrderBy(track => track.DiscNumber)
|
||||
.ThenBy(track => track.TrackNumber)
|
||||
.ThenBy(track => track.Id)
|
||||
.Select(track => track.Id)];
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackEntity>> result = await sut.GetByAlbumIdAsync(album.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedOrder, result.Value.Select(track => track.Id));
|
||||
Assert.DoesNotContain(result.Value, track => track.Id == trackOfAnotherAlbum.Id);
|
||||
TrackEntity retrievedTrack = result.Value.First(track => track.Id == firstDiscFirstTrack.Id);
|
||||
Assert.Single(retrievedTrack.Tags);
|
||||
Assert.Single(retrievedTrack.Genres);
|
||||
Assert.Single(retrievedTrack.Moods);
|
||||
Assert.Single(retrievedTrack.Isrcs);
|
||||
Assert.Single(retrievedTrack.Ratings);
|
||||
Assert.Single(retrievedTrack.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTracksLiteByAlbumIdAsync_WhenPaginationDataIsNull_ShouldReturnAllTracksOfTheAlbum()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-lite-null-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
List<TrackEntity> tracks = _trackEntityFixture.CreateMany(3);
|
||||
for (int index = 0; index < tracks.Count; index++)
|
||||
{
|
||||
tracks[index].AlbumId = album.Id;
|
||||
tracks[index].LibraryId = libraryId;
|
||||
tracks[index].Path = $"/music/queen/track-{index}.flac";
|
||||
tracks[index].DiscNumber = 1;
|
||||
tracks[index].TrackNumber = index + 1;
|
||||
tracks[index].Tags = [];
|
||||
tracks[index].Genres = [];
|
||||
tracks[index].Moods = [];
|
||||
tracks[index].Isrcs = [];
|
||||
tracks[index].Ratings = [];
|
||||
tracks[index].Contributors = [];
|
||||
}
|
||||
context.Tracks.AddRange(tracks);
|
||||
|
||||
AlbumEntity anotherAlbum = await SeedAlbumAsync(context, libraryId);
|
||||
TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(albumId: anotherAlbum.Id, libraryId: libraryId, path: "/music/queen/save-me.flac", includeMetadata: false);
|
||||
context.Tracks.Add(trackOfAnotherAlbum);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<TrackLiteRow>> result = await sut.GetTracksLiteByAlbumIdAsync(album.Id, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
PaginatedResultDto<TrackLiteRow> page = result.Value;
|
||||
Assert.Equal(3, page.Count);
|
||||
Assert.Equal(3, page.Data.Count);
|
||||
Assert.Equal(1, page.CurrentPage);
|
||||
Assert.Equal(3, page.PerPage);
|
||||
Assert.Equal(1, page.NumberOfPages);
|
||||
Assert.DoesNotContain(page.Data, row => row.Id == trackOfAnotherAlbum.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 GetTracksLiteByAlbumIdAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage(
|
||||
int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount)
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-lite-page-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
TrackRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
List<TrackEntity> tracks = _trackEntityFixture.CreateMany(5);
|
||||
for (int index = 0; index < tracks.Count; index++)
|
||||
{
|
||||
tracks[index].AlbumId = album.Id;
|
||||
tracks[index].LibraryId = libraryId;
|
||||
tracks[index].Path = $"/music/queen/song-{index}.flac";
|
||||
tracks[index].DiscNumber = 1;
|
||||
tracks[index].TrackNumber = index + 1;
|
||||
tracks[index].Tags = [];
|
||||
tracks[index].Genres = [];
|
||||
tracks[index].Moods = [];
|
||||
tracks[index].Isrcs = [];
|
||||
tracks[index].Ratings = [];
|
||||
tracks[index].Contributors = [];
|
||||
}
|
||||
context.Tracks.AddRange(tracks);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<TrackLiteRow>> result = await sut.GetTracksLiteByAlbumIdAsync(album.Id, paginationData, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
PaginatedResultDto<TrackLiteRow> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist and the album that owns the tracks of the library identified by <paramref name="libraryId"/>, so that the required foreign keys of a track are satisfied.
|
||||
/// </summary>
|
||||
/// <param name="context">The context the artist and album are persisted through.</param>
|
||||
/// <param name="libraryId">The Id of the library the album belongs to.</param>
|
||||
/// <returns>The persisted album.</returns>
|
||||
private async Task<AlbumEntity> SeedAlbumAsync(LuminaDbContext context, Guid libraryId)
|
||||
{
|
||||
ArtistEntity? artist = await context.Artists.FirstOrDefaultAsync(existing => existing.LibraryId == libraryId);
|
||||
if (artist is null)
|
||||
{
|
||||
artist = _artistEntityFixture.Create(
|
||||
libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
|
||||
context.Artists.Add(artist);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(album);
|
||||
await context.SaveChangesAsync();
|
||||
return album;
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads a detached copy of a stored track, with its children, 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 track.</param>
|
||||
/// <param name="trackId">The Id of the track to load.</param>
|
||||
/// <returns>The detached copy of the track.</returns>
|
||||
private static async Task<TrackEntity> LoadDetachedTrackAsync(LuminaDbContext context, Guid trackId)
|
||||
{
|
||||
return await context.Tracks
|
||||
.AsNoTracking()
|
||||
.Include(track => track.Tags)
|
||||
.Include(track => track.Genres)
|
||||
.Include(track => track.Ratings)
|
||||
.Include(track => track.Contributors)
|
||||
.Include(track => track.Moods)
|
||||
.Include(track => track.Isrcs)
|
||||
.FirstAsync(track => track.Id == trackId);
|
||||
}
|
||||
}
|
||||
+1295
File diff suppressed because it is too large.
Load diff
+446
@@ -0,0 +1,446 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
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.Tracks.DeleteTrack;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
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.Tracks.DeleteTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteTrackEndpointTests : 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="DeleteTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteTrackEndpointTests(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 DeleteTrack_WhenTrackBelongsToAnOwnedLibrary_ShouldDeleteTheTrack()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Bohemian Rhapsody", "/music/queen/bohemian-rhapsody.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Null(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId));
|
||||
// The album and the artist that contained the track are preserved.
|
||||
Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId));
|
||||
Assert.NotNull(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("ArtistNotFound", problemDetails.Detail);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("AlbumNotFound", problemDetails.Detail);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackDoesNotExist_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackNotFound", problemDetails.Detail);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackRequestedThroughDifferentAlbum_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
Guid otherAlbumId = await SeedAlbumAsync(libraryId, artistId, "News of the World");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{otherAlbumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
// The route album id is enforced, so a track of another album is reported as not found, without disclosing that the track exists.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackRequestedThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
Guid otherArtistId = await SeedArtistAsync(libraryId, "Freddie Mercury");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{otherArtistId}/albums/{albumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
// The route artist id is enforced, so an album of another artist is reported as not found, without disclosing that it exists.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("AlbumNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
// The route library id is enforced, so an artist of another library is reported as not found, without disclosing that it exists.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("ArtistNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, Guid otherTrackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, "We Are the Champions", "/music/queen/news-of-the-world/we-are-the-champions.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks/{otherTrackId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id reaches the command validator, which reports a clean validation error instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("ArtistIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("AlbumIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/not-a-guid");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("TrackIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="trackTitle">The title of the seeded track.</param>
|
||||
/// <param name="path">The file system path of the seeded track.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackTitle, string path)
|
||||
{
|
||||
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();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
|
||||
dbContext.Albums.Add(CreateSeededAlbum(libraryId, artistId, albumId, "A Night at the Opera"));
|
||||
dbContext.Tracks.Add(CreateSeededTrack(libraryId, albumId, trackId, path, trackTitle));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an additional album belonging to the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the seeded album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
dbContext.Albums.Add(CreateSeededAlbum(libraryId, artistId, albumId, title));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an album to be seeded into the database.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The created album entity.</returns>
|
||||
private AlbumEntity CreateSeededAlbum(Guid libraryId, Guid artistId, Guid albumId, string title)
|
||||
{
|
||||
return _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a track to be seeded into the database.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <param name="path">The file system path of the track.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <returns>The created track entity.</returns>
|
||||
private TrackEntity CreateSeededTrack(Guid libraryId, Guid albumId, Guid trackId, string path, string title)
|
||||
{
|
||||
return _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
path: path,
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an additional artist belonging to the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the seeded artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: name));
|
||||
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 and its username.</returns>
|
||||
private async Task<(Guid userId, string username)> 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();
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
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.Tracks.GetTrack;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
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.Tracks.GetTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTrackEndpointTests : 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="GetTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetTrackEndpointTests(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 GetTrack_WhenTrackBelongsToAnOwnedLibrary_ShouldReturnTrackDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Bohemian Rhapsody", "/music/queen/bohemian-rhapsody.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
TrackResponse? track = JsonSerializer.Deserialize<TrackResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(track);
|
||||
Assert.Equal(trackId, track!.Id);
|
||||
Assert.Equal(albumId, track.AlbumId);
|
||||
Assert.Equal(libraryId, track.LibraryId);
|
||||
Assert.Equal("/music/queen/bohemian-rhapsody.flac", track.Path);
|
||||
Assert.Equal("Bohemian Rhapsody", track.Metadata.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenTrackDoesNotExist_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackNotFound", problemDetails.Detail);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("AlbumNotFound", problemDetails.Detail);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenTrackRequestedThroughDifferentAlbum_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
Guid otherAlbumId = await SeedAlbumAsync(libraryId, artistId, "News of the World");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{otherAlbumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
// The route album id is enforced, so a track of another album is reported as not found, without disclosing that the track exists.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenTrackRequestedThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
// The route artist id is enforced, so an album of another artist is reported as not found, without disclosing that it exists.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("AlbumNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenTrackRequestedThroughDifferentLibrary_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
// The route library id is enforced, so an album of another library is reported as not found, without disclosing that it exists.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("AlbumNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, Guid otherTrackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, "We Are the Champions", "/music/queen/news-of-the-world/we-are-the-champions.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks/{otherTrackId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("ArtistIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("AlbumIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenTrackIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/not-a-guid");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("TrackIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="trackTitle">The title of the seeded track.</param>
|
||||
/// <param name="path">The file system path of the seeded track.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackTitle, string path)
|
||||
{
|
||||
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();
|
||||
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"));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera"));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: path, title: trackTitle, includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an additional album belonging to the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the seeded album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: title));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user and its username.</returns>
|
||||
private async Task<(Guid userId, string username)> 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();
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+1221
File diff suppressed because it is too large.
Load diff
+275
@@ -0,0 +1,275 @@
|
||||
#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.Tracks;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
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.IO;
|
||||
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.Tracks.AddTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="AddTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly AddTrackRequestFixture _addTrackRequestFixture = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = 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 string _libraryContentLocation = Path.GetTempPath();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddTrackEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", 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/{albumId}/tracks", problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddTrack_WhenUnauthorized_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", 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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddTrack_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(ownerId);
|
||||
|
||||
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", 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("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
await _apiFactory.RemoveTestUserAsync(requesterUsername);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddTrack_WhenArtistBelongsToAnotherLibrary_ShouldNotDiscloseCrossLibraryData()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
(Guid ownerLibraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(ownerId);
|
||||
|
||||
(Guid attackerId, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
Guid attackerLibraryId = Guid.NewGuid();
|
||||
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
seedDbContext.Libraries.Add(_libraryEntityFixture.Create(id: attackerLibraryId, userId: attackerId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [_libraryContentLocation]));
|
||||
await seedDbContext.SaveChangesAsync();
|
||||
}
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{attackerLibraryId}/artists/{artistId}/albums/{albumId}/tracks", request);
|
||||
|
||||
// Assert
|
||||
// The artist exists in another library, but the mismatch is reported as not found, without disclosing that it exists elsewhere.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("ArtistNotFound", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(ownerLibraryId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
await _apiFactory.RemoveTestUserAsync(attackerUsername);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task AddTrack_WithSQLInjectionInPath_ShouldNotCorruptOrDeleteData(string maliciousPath)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
|
||||
string injectedPath = Path.Combine(_libraryContentLocation, $"{maliciousPath}.flac");
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create(path: injectedPath, contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", request);
|
||||
|
||||
// Assert
|
||||
// The malicious path passes the authenticated handler, reaches the parameterized insert, and is persisted
|
||||
// verbatim: if it were concatenated into raw SQL, the insert would fail and the track would not be created.
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.Libraries.CountAsync(library => library.Id == libraryId));
|
||||
TrackEntity storedTrack = await dbContext.Tracks.SingleAsync(track => track.LibraryId == libraryId);
|
||||
Assert.Equal(injectedPath, storedTrack.Path);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task AddTrack_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousTitle)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create(
|
||||
path: Path.Combine(_libraryContentLocation, $"{Guid.NewGuid():N}.flac"),
|
||||
metadata: _audioMetadataDtoFixture.Create(title: maliciousTitle),
|
||||
contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", request);
|
||||
|
||||
// Assert
|
||||
// The malicious title passes the authenticated handler, reaches the parameterized insert, and is persisted
|
||||
// verbatim: if it were concatenated into raw SQL, the insert would fail and the track 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>();
|
||||
TrackEntity storedTrack = await dbContext.Tracks.SingleAsync(track => track.LibraryId == libraryId);
|
||||
Assert.Equal(maliciousTitle, storedTrack.Title);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task AddTrack_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", request);
|
||||
|
||||
// Assert
|
||||
// The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the command
|
||||
// validator, which reports it as a clean validation error. The response must not leak stack traces, database details,
|
||||
// or the injected payload.
|
||||
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);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, along with one artist and one album of that library.
|
||||
/// </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();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [_libraryContentLocation]));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
// Nothing to clean up: each test removes its own seeded rows.
|
||||
}
|
||||
}
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
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.Tracks.DeleteTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="DeleteTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteTrackEndpointTests : 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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteTrackEndpointTests(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 DeleteTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{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(url, problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].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 DeleteTrack_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id reaches the command validator, which reports a clean
|
||||
// validation error instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[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 DeleteTrack_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[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 DeleteTrack_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[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 DeleteTrack_WithSQLInjectionInTrackId_ShouldNotCorruptOrLeakData(string maliciousTrackId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("..%2F..%2Fevil")] // encoded slash traversal
|
||||
[InlineData("%2e%2e%2f%2e%2e%2fevil")] // encoded dot-slash traversal
|
||||
[InlineData("..%5Cevil")] // encoded backslash traversal
|
||||
[InlineData("..%2F")] // encoded trailing slash traversal
|
||||
public async Task DeleteTrack_WithPathTraversalInTrackId_ShouldReturnCleanProblemDetails(string maliciousTrackId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{maliciousTrackId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// Note: some payloads are normalized away by the server before routing, producing an empty-body 404;
|
||||
// when the value reaches the handler, the failure must still be a clean, generic problem.
|
||||
if (!string.IsNullOrWhiteSpace(content))
|
||||
{
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.True(response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.UnprocessableEntity);
|
||||
Assert.NotEqual(StatusCodes.Status500InternalServerError, (int)response.StatusCode);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
/// <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();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </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)> SeedLibraryArtistAlbumAndTrackAsync(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();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
|
||||
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);
|
||||
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);
|
||||
dbContext.Albums.Add(album);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
}
|
||||
}
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
#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.Tracks.GetTrack;
|
||||
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.Tracks.GetTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTrackEndpointTests : 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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetTrackEndpointTests(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 GetTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{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(url, problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].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 GetTrack_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[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 GetTrack_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[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 GetTrack_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean
|
||||
// validation error instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[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 GetTrack_WithSQLInjectionInTrackId_ShouldNotCorruptOrLeakData(string maliciousTrackId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}");
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
/// <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();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </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)> SeedLibraryArtistAlbumAndTrackAsync(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();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
|
||||
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);
|
||||
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);
|
||||
dbContext.Albums.Add(album);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
}
|
||||
}
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Requests.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.Tracks.UpdateTrack;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
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.Tracks.UpdateTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="UpdateTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private static readonly string s_contentRootPath = Path.Combine(Path.GetTempPath(), "lumina-security-update-track-tests");
|
||||
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly UpdateTrackRequestFixture _updateTrackRequestFixture = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateTrackEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateTrack_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();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", 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}/tracks/{trackId}", problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateTrack_WithSQLInjectionInBody_ShouldNotCorruptOrLeakData(string maliciousTitle)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: maliciousTitle));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", request);
|
||||
|
||||
// Assert
|
||||
// The injected title is validated and handled by the parameterized update flow: the route artist does not exist, so the
|
||||
// request fails with a clean not found response and the injected payload is never executed as SQL.
|
||||
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(maliciousTitle, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateTrack_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", request);
|
||||
|
||||
// Assert
|
||||
await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateTrack_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", request);
|
||||
|
||||
// Assert
|
||||
await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateTrack_WithSQLInjectionInAlbumRouteId_ShouldRemainSecure(string maliciousAlbumId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}", request);
|
||||
|
||||
// Assert
|
||||
await AssertCleanValidationErrorAsync(response, maliciousAlbumId, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateTrack_WithSQLInjectionInTrackRouteId_ShouldRemainSecure(string maliciousTrackId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}", request);
|
||||
|
||||
// Assert
|
||||
await AssertCleanValidationErrorAsync(response, maliciousTrackId, "TrackIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateTrack_WhenArtistDoesNotExist_ShouldReturnNotFoundWithoutLeakingInternals()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateTrack_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
_seededUsernames.Add(ownerUsername);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
SeedLibrary(libraryId, ownerId);
|
||||
(Guid artistId, Guid albumId, Guid trackId) = SeedArtistGraph(libraryId);
|
||||
|
||||
HttpClient requesterClient = _apiFactory.CreateClient();
|
||||
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
|
||||
_seededUsernames.Add(requesterUsername);
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", 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);
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(403, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
/// <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 media library of type music owned by <paramref name="userId"/>, whose single content location is the test content root path.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library to seed.</param>
|
||||
/// <param name="userId">The Id of the user that owns the media library.</param>
|
||||
private void SeedLibrary(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: [s_contentRootPath]));
|
||||
dbContext.SaveChanges();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist that owns a single album, which in turn owns a single track, all belonging to <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <returns>The Ids of the seeded artist, album and track.</returns>
|
||||
private (Guid artistId, Guid albumId, Guid trackId) SeedArtistGraph(Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: Path.Combine(s_contentRootPath, "bohemian-rhapsody.flac"), includeMetadata: false);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, libraryId: libraryId, tracks: [track], includeMetadata: false);
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, albums: [album], includeContributors: false);
|
||||
dbContext.Artists.Add(artist);
|
||||
dbContext.SaveChanges();
|
||||
return (artist.Id, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<ArtistEntity> artists = [.. dbContext.Artists.Where(artist => _seededLibraryIds.Contains(artist.LibraryId))];
|
||||
dbContext.Artists.RemoveRange(artists);
|
||||
List<LibraryEntity> libraries = [.. dbContext.Libraries.Where(library => _seededLibraryIds.Contains(library.Id))];
|
||||
dbContext.Libraries.RemoveRange(libraries);
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUserAsync(username).GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite;
|
||||
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="GetAlbumTracksLiteRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksLiteRequestMappingTests
|
||||
{
|
||||
private readonly GetAlbumTracksLiteRequestFixture _getAlbumTracksLiteRequestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenCalledWithRouteIds_ShouldMapRouteIdsFromArguments()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetAlbumTracksLiteQuery result = request.ToQuery("library-route", "artist-route", "album-route");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("library-route", result.LibraryId);
|
||||
Assert.Equal("artist-route", result.ArtistId);
|
||||
Assert.Equal("album-route", result.AlbumId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenNoPaginationValuesAreProvided_ShouldMapNullPaginationData()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false);
|
||||
|
||||
// Act
|
||||
GetAlbumTracksLiteQuery result = request.ToQuery("library-route", "artist-route", "album-route");
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.PaginationData);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenOnlyCurrentPageIsProvided_ShouldDefaultPerPageToTwoHundred()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(currentPage: 3, includePerPage: false);
|
||||
|
||||
// Act
|
||||
GetAlbumTracksLiteQuery result = request.ToQuery("library-route", "artist-route", "album-route");
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result.PaginationData);
|
||||
Assert.Equal(3, result.PaginationData.CurrentPage);
|
||||
Assert.Equal(200, result.PaginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenOnlyPerPageIsProvided_ShouldDefaultCurrentPageToOne()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(perPage: 50, includeCurrentPage: false);
|
||||
|
||||
// Act
|
||||
GetAlbumTracksLiteQuery result = request.ToQuery("library-route", "artist-route", "album-route");
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result.PaginationData);
|
||||
Assert.Equal(1, result.PaginationData.CurrentPage);
|
||||
Assert.Equal(50, result.PaginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenBothPaginationValuesAreProvided_ShouldMapThem()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(currentPage: 2, perPage: 25);
|
||||
|
||||
// Act
|
||||
GetAlbumTracksLiteQuery result = request.ToQuery("library-route", "artist-route", "album-route");
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result.PaginationData);
|
||||
Assert.Equal(2, result.PaginationData.CurrentPage);
|
||||
Assert.Equal(25, result.PaginationData.PerPage);
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateArtistTrackRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateArtistTrackRequestMappingTests
|
||||
{
|
||||
private readonly UpdateArtistTrackRequestFixture _updateArtistTrackRequestFixture = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateArtistTrackRequest request = _updateArtistTrackRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
AddTrackCommand 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.Path, result.Path);
|
||||
Assert.Equal(request.Metadata, result.Metadata);
|
||||
Assert.Equal(request.TrackNumber, result.TrackNumber);
|
||||
Assert.Equal(request.DiscNumber, result.DiscNumber);
|
||||
Assert.Equal(request.Script, result.Script);
|
||||
Assert.Equal(request.Key, result.Key);
|
||||
Assert.Equal(request.Bpm, result.Bpm);
|
||||
Assert.Equal(request.Work, result.Work);
|
||||
Assert.Equal(request.MusicBrainzRecordingId, result.MusicBrainzRecordingId);
|
||||
Assert.Equal(request.MusicBrainzTrackId, result.MusicBrainzTrackId);
|
||||
Assert.Equal(request.MusicBrainzWorkId, result.MusicBrainzWorkId);
|
||||
Assert.Equal(request.Moods, result.Moods);
|
||||
Assert.Equal(request.Isrcs, result.Isrcs);
|
||||
Assert.Equal(request.Contributors, result.Contributors);
|
||||
Assert.Equal(request.Ratings, result.Ratings);
|
||||
Assert.Equal(request.TrackId, result.TrackId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredPropertiesAndNulls()
|
||||
{
|
||||
// Arrange
|
||||
UpdateArtistTrackRequest request = _updateArtistTrackRequestFixture.Create(
|
||||
path: "/music/queen/bohemian-rhapsody.flac",
|
||||
metadata: _audioMetadataDtoFixture.Create(title: "Love of My Life"),
|
||||
includeOptionalProperties: false,
|
||||
includeTrackId: false);
|
||||
|
||||
// Act
|
||||
AddTrackCommand result = request.ToCommand(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("/music/queen/bohemian-rhapsody.flac", result.Path);
|
||||
Assert.Equal("Love of My Life", result.Metadata!.Title);
|
||||
Assert.Null(result.DiscNumber);
|
||||
Assert.Null(result.Script);
|
||||
Assert.Null(result.Key);
|
||||
Assert.Null(result.Bpm);
|
||||
Assert.Null(result.Work);
|
||||
Assert.Null(result.MusicBrainzRecordingId);
|
||||
Assert.Null(result.MusicBrainzTrackId);
|
||||
Assert.Null(result.MusicBrainzWorkId);
|
||||
Assert.Null(result.Moods);
|
||||
Assert.Null(result.Isrcs);
|
||||
Assert.Null(result.TrackId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenRouteIdentifiersAreNull_ShouldMapNullRouteIdentifiers()
|
||||
{
|
||||
// Arrange
|
||||
UpdateArtistTrackRequest request = _updateArtistTrackRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
AddTrackCommand result = request.ToCommand(null, null, null);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.LibraryId);
|
||||
Assert.Null(result.ArtistId);
|
||||
Assert.Null(result.AlbumId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommands_WhenMappingMultipleRequests_ShouldMapEachRequest()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
List<UpdateArtistTrackRequest> requests = _updateArtistTrackRequestFixture.CreateMany(3);
|
||||
|
||||
// Act
|
||||
List<AddTrackCommand> result = [.. requests.ToCommands(libraryId.ToString(), artistId.ToString(), albumId.ToString())];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(requests.Count, result.Count);
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
{
|
||||
Assert.Equal(requests[i].Path, result[i].Path);
|
||||
Assert.Equal(requests[i].TrackNumber, result[i].TrackNumber);
|
||||
Assert.Equal(requests[i].TrackId, result[i].TrackId);
|
||||
Assert.Equal(libraryId.ToString(), result[i].LibraryId);
|
||||
Assert.Equal(artistId.ToString(), result[i].ArtistId);
|
||||
Assert.Equal(albumId.ToString(), result[i].AlbumId);
|
||||
}
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AudioRatingDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AudioRatingDtoMappingTests
|
||||
{
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingCompleteAudioRatingDto_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AudioRatingDto dto = _audioRatingDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<AudioRating> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(dto.Value, result.Value.Value);
|
||||
Assert.Equal(dto.MaxValue, result.Value.MaxValue);
|
||||
Assert.True(result.Value.Source.HasValue);
|
||||
Assert.Equal(dto.Source, result.Value.Source.Value);
|
||||
Assert.True(result.Value.VoteCount.HasValue);
|
||||
Assert.Equal(dto.VoteCount, result.Value.VoteCount.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNones()
|
||||
{
|
||||
// Arrange
|
||||
AudioRatingDto dto = _audioRatingDtoFixture.Create(includeSource: false, includeVoteCount: false);
|
||||
|
||||
// Act
|
||||
Result<AudioRating> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(dto.Value, result.Value.Value);
|
||||
Assert.Equal(dto.MaxValue, result.Value.MaxValue);
|
||||
Assert.False(result.Value.Source.HasValue);
|
||||
Assert.False(result.Value.VoteCount.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenValueIsGreaterThanMaxValue_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AudioRatingDto dto = _audioRatingDtoFixture.Create(value: 10, maxValue: 5);
|
||||
|
||||
// Act
|
||||
Result<AudioRating> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMultipleValidAudioRatingDtos_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<AudioRatingDto> dtos = _audioRatingDtoFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
List<Result<AudioRating>> results = [.. dtos.ToDomainEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(dtos.Count, results.Count);
|
||||
for (int i = 0; i < dtos.Count; i++)
|
||||
{
|
||||
Assert.False(results[i].IsFailure);
|
||||
Assert.Equal(dtos[i].Value, results[i].Value.Value);
|
||||
Assert.Equal(dtos[i].MaxValue, results[i].Value.MaxValue);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMixedValidAndInvalidAudioRatingDtos_ShouldReturnMixedResults()
|
||||
{
|
||||
// Arrange
|
||||
List<AudioRatingDto> dtos =
|
||||
[
|
||||
_audioRatingDtoFixture.Create(value: 4, maxValue: 5),
|
||||
_audioRatingDtoFixture.Create(value: 10, maxValue: 5),
|
||||
_audioRatingDtoFixture.Create(value: 3, maxValue: 5)
|
||||
];
|
||||
|
||||
// Act
|
||||
List<Result<AudioRating>> results = [.. dtos.ToDomainEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(dtos.Count, results.Count);
|
||||
Assert.False(results[0].IsFailure);
|
||||
Assert.True(results[1].IsFailure);
|
||||
Assert.False(results[2].IsFailure);
|
||||
}
|
||||
}
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AudioRatingEntityMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AudioRatingEntityMappingTests
|
||||
{
|
||||
private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidAudioRatingEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AudioRatingEntity entity = _audioRatingEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
AudioRatingDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(entity.Value, result.Value);
|
||||
Assert.Equal(entity.MaxValue, result.MaxValue);
|
||||
Assert.Equal(entity.Source, result.Source);
|
||||
Assert.Equal(entity.VoteCount, result.VoteCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingAudioRatingEntityWithNulls_ShouldMapToDefaults()
|
||||
{
|
||||
// Arrange
|
||||
AudioRatingEntity entity = _audioRatingEntityFixture.Create(includeValue: false, includeMaxValue: false, includeSource: false, includeVoteCount: false);
|
||||
|
||||
// Act
|
||||
AudioRatingDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(0, result.Value);
|
||||
Assert.Equal(0, result.MaxValue);
|
||||
Assert.Null(result.Source);
|
||||
Assert.Null(result.VoteCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleAudioRatingEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<AudioRatingEntity> entities = _audioRatingEntityFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
List<AudioRatingDto> results = [.. entities.ToResponses()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(entities.Count, results.Count);
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
{
|
||||
Assert.Equal(entities[i].Value, results[i].Value);
|
||||
Assert.Equal(entities[i].MaxValue, results[i].MaxValue);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidAudioRatingEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AudioRatingEntity entity = _audioRatingEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<AudioRating> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(entity.Value, result.Value.Value);
|
||||
Assert.Equal(entity.MaxValue, result.Value.MaxValue);
|
||||
Assert.True(result.Value.Source.HasValue);
|
||||
Assert.Equal(entity.Source, result.Value.Source.Value);
|
||||
Assert.True(result.Value.VoteCount.HasValue);
|
||||
Assert.Equal(entity.VoteCount, result.Value.VoteCount.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingAudioRatingEntityWithNulls_ShouldMapToDefaults()
|
||||
{
|
||||
// Arrange
|
||||
AudioRatingEntity entity = _audioRatingEntityFixture.Create(includeValue: false, includeMaxValue: false, includeSource: false, includeVoteCount: false);
|
||||
|
||||
// Act
|
||||
Result<AudioRating> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(0, result.Value.Value);
|
||||
Assert.Equal(0, result.Value.MaxValue);
|
||||
Assert.False(result.Value.Source.HasValue);
|
||||
Assert.False(result.Value.VoteCount.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenValueIsGreaterThanMaxValue_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AudioRatingEntity entity = _audioRatingEntityFixture.Create(value: 6, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 10);
|
||||
|
||||
// Act
|
||||
Result<AudioRating> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMultipleValidAudioRatingEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<AudioRatingEntity> entities = _audioRatingEntityFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
List<Result<AudioRating>> results = [.. entities.ToDomainEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(entities.Count, results.Count);
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
{
|
||||
Assert.False(results[i].IsFailure);
|
||||
Assert.Equal(entities[i].Value, results[i].Value.Value);
|
||||
Assert.Equal(entities[i].MaxValue, results[i].Value.MaxValue);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMixedValidAndInvalidAudioRatingEntities_ShouldReturnMixedResults()
|
||||
{
|
||||
// Arrange
|
||||
List<AudioRatingEntity> entities =
|
||||
[
|
||||
_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
|
||||
_audioRatingEntityFixture.Create(value: 6, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
|
||||
_audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)
|
||||
];
|
||||
|
||||
// Act
|
||||
List<Result<AudioRating>> results = [.. entities.ToDomainEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(entities.Count, results.Count);
|
||||
Assert.False(results[0].IsFailure);
|
||||
Assert.True(results[1].IsFailure);
|
||||
Assert.False(results[2].IsFailure);
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AudioRatingMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AudioRatingMappingTests
|
||||
{
|
||||
private readonly AudioRatingFixture _audioRatingFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingCompleteAudioRating_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AudioRating audioRating = _audioRatingFixture.Create();
|
||||
|
||||
// Act
|
||||
AudioRatingEntity result = audioRating.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(audioRating.Value, result.Value);
|
||||
Assert.Equal(audioRating.MaxValue, result.MaxValue);
|
||||
Assert.Equal(audioRating.Source.Value, result.Source);
|
||||
Assert.Equal(audioRating.VoteCount.Value, result.VoteCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingAudioRatingWithoutSource_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AudioRating audioRating = _audioRatingFixture.Create(source: Optional<AudioRatingSource>.None());
|
||||
|
||||
// Act
|
||||
AudioRatingEntity result = audioRating.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(audioRating.Value, result.Value);
|
||||
Assert.Equal(audioRating.MaxValue, result.MaxValue);
|
||||
Assert.Null(result.Source);
|
||||
Assert.Equal(audioRating.VoteCount.Value, result.VoteCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingAudioRatingWithoutVoteCount_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AudioRating audioRating = _audioRatingFixture.Create(voteCount: Optional<int>.None());
|
||||
|
||||
// Act
|
||||
AudioRatingEntity result = audioRating.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(audioRating.Value, result.Value);
|
||||
Assert.Equal(audioRating.MaxValue, result.MaxValue);
|
||||
Assert.Equal(audioRating.Source.Value, result.Source);
|
||||
Assert.Null(result.VoteCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntities_WhenMappingMultipleAudioRatings_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<AudioRating> audioRatings = _audioRatingFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
List<AudioRatingEntity> results = [.. audioRatings.ToRepositoryEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(audioRatings.Count, results.Count);
|
||||
for (int i = 0; i < audioRatings.Count; i++)
|
||||
{
|
||||
Assert.Equal(audioRatings[i].Value, results[i].Value);
|
||||
Assert.Equal(audioRatings[i].MaxValue, results[i].MaxValue);
|
||||
Assert.Equal(audioRatings[i].Source.Value, results[i].Source);
|
||||
Assert.Equal(audioRatings[i].VoteCount.Value, results[i].VoteCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="IsrcDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsrcDtoMappingTests
|
||||
{
|
||||
private readonly IsrcDtoFixture _isrcDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidIsrcDto_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
IsrcDto dto = _isrcDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Isrc> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(dto.Value!.Trim().ToUpperInvariant(), result.Value.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingLowercaseIsrcDto_ShouldNormalizeTheValue()
|
||||
{
|
||||
// Arrange
|
||||
IsrcDto dto = _isrcDtoFixture.Create(value: "gbum71029604");
|
||||
|
||||
// Act
|
||||
Result<Isrc> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("GBUM71029604", result.Value.Value);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing value
|
||||
[InlineData("")] // empty value
|
||||
[InlineData(" ")] // whitespace value
|
||||
public void ToDomainEntity_WhenValueIsNullOrWhitespace_ShouldReturnError(string? value)
|
||||
{
|
||||
// Arrange
|
||||
IsrcDto dto = _isrcDtoFixture.Create(value: value, includeValue: value is not null);
|
||||
|
||||
// Act
|
||||
Result<Isrc> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.IsrcValueCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("invalid")] // not an ISRC at all
|
||||
[InlineData("GBUM7102960")] // too short
|
||||
[InlineData("GBUM71029604X")] // too long
|
||||
[InlineData("1BUM71029604")] // country code is not two letters
|
||||
[InlineData("GBUM7102960A")] // designation code is not all digits
|
||||
public void ToDomainEntity_WhenValueIsMalformed_ShouldReturnError(string value)
|
||||
{
|
||||
// Arrange
|
||||
IsrcDto dto = _isrcDtoFixture.Create(value: value);
|
||||
|
||||
// Act
|
||||
Result<Isrc> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.IsrcInvalidFormat, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMultipleValidIsrcDtos_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<IsrcDto> dtos = _isrcDtoFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
List<Result<Isrc>> results = [.. dtos.ToDomainEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(dtos.Count, results.Count);
|
||||
for (int i = 0; i < dtos.Count; i++)
|
||||
{
|
||||
Assert.False(results[i].IsFailure);
|
||||
Assert.Equal(dtos[i].Value!.Trim().ToUpperInvariant(), results[i].Value.Value);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMixedValidAndInvalidIsrcDtos_ShouldReturnMixedResults()
|
||||
{
|
||||
// Arrange
|
||||
List<IsrcDto> dtos =
|
||||
[
|
||||
_isrcDtoFixture.Create(value: "GBUM71029604"),
|
||||
_isrcDtoFixture.Create(value: "invalid"),
|
||||
_isrcDtoFixture.Create(value: "USRC17607839")
|
||||
];
|
||||
|
||||
// Act
|
||||
List<Result<Isrc>> results = [.. dtos.ToDomainEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(dtos.Count, results.Count);
|
||||
Assert.False(results[0].IsFailure);
|
||||
Assert.True(results[1].IsFailure);
|
||||
Assert.False(results[2].IsFailure);
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="IsrcEntityMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsrcEntityMappingTests
|
||||
{
|
||||
private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidTrackIsrcEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TrackIsrcEntity entity = _trackIsrcEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
IsrcDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(entity.Value, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleTrackIsrcEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<TrackIsrcEntity> entities = _trackIsrcEntityFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
List<IsrcDto> results = [.. entities.ToResponses()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(entities.Count, results.Count);
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
Assert.Equal(entities[i].Value, results[i].Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidTrackIsrcEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TrackIsrcEntity entity = _trackIsrcEntityFixture.Create(value: "GBUM71029604");
|
||||
|
||||
// Act
|
||||
Result<Isrc> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(entity.Value, result.Value.Value);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // empty value
|
||||
[InlineData(" ")] // whitespace value
|
||||
public void ToDomainEntity_WhenValueIsWhitespace_ShouldReturnError(string value)
|
||||
{
|
||||
// Arrange
|
||||
TrackIsrcEntity entity = _trackIsrcEntityFixture.Create(value: value);
|
||||
|
||||
// Act
|
||||
Result<Isrc> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.IsrcValueCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenValueIsMalformed_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
TrackIsrcEntity entity = _trackIsrcEntityFixture.Create(value: "not-an-isrc");
|
||||
|
||||
// Act
|
||||
Result<Isrc> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.IsrcInvalidFormat, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMultipleValidTrackIsrcEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<TrackIsrcEntity> entities = _trackIsrcEntityFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
List<Result<Isrc>> results = [.. entities.ToDomainEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(entities.Count, results.Count);
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
{
|
||||
Assert.False(results[i].IsFailure);
|
||||
Assert.Equal(entities[i].Value, results[i].Value.Value);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMixedValidAndInvalidTrackIsrcEntities_ShouldReturnMixedResults()
|
||||
{
|
||||
// Arrange
|
||||
List<TrackIsrcEntity> entities =
|
||||
[
|
||||
_trackIsrcEntityFixture.Create(value: "GBUM71029604"),
|
||||
_trackIsrcEntityFixture.Create(value: "invalid"),
|
||||
_trackIsrcEntityFixture.Create(value: "USRC17607839")
|
||||
];
|
||||
|
||||
// Act
|
||||
List<Result<Isrc>> results = [.. entities.ToDomainEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(entities.Count, results.Count);
|
||||
Assert.False(results[0].IsFailure);
|
||||
Assert.True(results[1].IsFailure);
|
||||
Assert.False(results[2].IsFailure);
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="IsrcMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsrcMappingTests
|
||||
{
|
||||
private readonly IsrcFixture _isrcFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingIsrc_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Isrc isrc = _isrcFixture.Create();
|
||||
|
||||
// Act
|
||||
TrackIsrcEntity result = isrc.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(isrc.Value, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntities_WhenMappingMultipleIsrcs_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<Isrc> isrcs = _isrcFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
List<TrackIsrcEntity> results = [.. isrcs.ToRepositoryEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(isrcs.Count, results.Count);
|
||||
for (int i = 0; i < isrcs.Count; i++)
|
||||
Assert.Equal(isrcs[i].Value, results[i].Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntities_WhenMappingEmptyCollection_ShouldReturnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
List<Isrc> isrcs = [];
|
||||
|
||||
// Act
|
||||
IEnumerable<TrackIsrcEntity> results = isrcs.ToRepositoryEntities();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(results);
|
||||
Assert.Empty(results);
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MoodDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MoodDtoMappingTests
|
||||
{
|
||||
private readonly MoodDtoFixture _moodDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidMoodDto_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
MoodDto dto = _moodDtoFixture.Create(name: " Calm ");
|
||||
|
||||
// Act
|
||||
Result<Mood> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal("Calm", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing name
|
||||
[InlineData("")] // empty name
|
||||
[InlineData(" ")] // whitespace name
|
||||
public void ToDomainEntity_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name)
|
||||
{
|
||||
// Arrange
|
||||
MoodDto dto = _moodDtoFixture.Create(name: name, includeName: name is not null);
|
||||
|
||||
// Act
|
||||
Result<Mood> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.MoodNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMultipleValidMoodDtos_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<MoodDto> dtos = _moodDtoFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
List<Result<Mood>> results = [.. dtos.ToDomainEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(dtos.Count, results.Count);
|
||||
for (int i = 0; i < dtos.Count; i++)
|
||||
{
|
||||
Assert.False(results[i].IsFailure);
|
||||
Assert.Equal(dtos[i].Name, results[i].Value.Name);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMixedValidAndInvalidMoodDtos_ShouldReturnMixedResults()
|
||||
{
|
||||
// Arrange
|
||||
List<MoodDto> dtos =
|
||||
[
|
||||
_moodDtoFixture.Create(name: "Calm"),
|
||||
_moodDtoFixture.Create(name: string.Empty, includeName: true),
|
||||
_moodDtoFixture.Create(name: "Energetic")
|
||||
];
|
||||
|
||||
// Act
|
||||
List<Result<Mood>> results = [.. dtos.ToDomainEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(dtos.Count, results.Count);
|
||||
Assert.False(results[0].IsFailure);
|
||||
Assert.Equal("Calm", results[0].Value.Name);
|
||||
Assert.True(results[1].IsFailure);
|
||||
Assert.False(results[2].IsFailure);
|
||||
Assert.Equal("Energetic", results[2].Value.Name);
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MoodEntityMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MoodEntityMappingTests
|
||||
{
|
||||
private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidTrackMoodEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TrackMoodEntity entity = _trackMoodEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
MoodDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(entity.Name, result.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleTrackMoodEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<TrackMoodEntity> entities = _trackMoodEntityFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
List<MoodDto> results = [.. entities.ToResponses()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(entities.Count, results.Count);
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
Assert.Equal(entities[i].Name, results[i].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidTrackMoodEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TrackMoodEntity entity = _trackMoodEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Mood> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(entity.Name, result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // empty name
|
||||
[InlineData(" ")] // whitespace name
|
||||
public void ToDomainEntity_WhenNameIsWhitespace_ShouldReturnError(string name)
|
||||
{
|
||||
// Arrange
|
||||
TrackMoodEntity entity = _trackMoodEntityFixture.Create(name: name);
|
||||
|
||||
// Act
|
||||
Result<Mood> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.MoodNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMultipleValidTrackMoodEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<TrackMoodEntity> entities = _trackMoodEntityFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
List<Result<Mood>> results = [.. entities.ToDomainEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(entities.Count, results.Count);
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
{
|
||||
Assert.False(results[i].IsFailure);
|
||||
Assert.Equal(entities[i].Name, results[i].Value.Name);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMixedValidAndInvalidTrackMoodEntities_ShouldReturnMixedResults()
|
||||
{
|
||||
// Arrange
|
||||
List<TrackMoodEntity> entities =
|
||||
[
|
||||
_trackMoodEntityFixture.Create(name: "Calm"),
|
||||
_trackMoodEntityFixture.Create(name: string.Empty),
|
||||
_trackMoodEntityFixture.Create(name: "Energetic")
|
||||
];
|
||||
|
||||
// Act
|
||||
List<Result<Mood>> results = [.. entities.ToDomainEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(entities.Count, results.Count);
|
||||
Assert.False(results[0].IsFailure);
|
||||
Assert.True(results[1].IsFailure);
|
||||
Assert.False(results[2].IsFailure);
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MoodMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MoodMappingTests
|
||||
{
|
||||
private readonly MoodFixture _moodFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingMood_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Mood mood = _moodFixture.Create();
|
||||
|
||||
// Act
|
||||
TrackMoodEntity result = mood.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(mood.Name, result.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntities_WhenMappingMultipleMoods_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<Mood> moods = _moodFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
List<TrackMoodEntity> results = [.. moods.ToRepositoryEntities()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(moods.Count, results.Count);
|
||||
for (int i = 0; i < moods.Count; i++)
|
||||
Assert.Equal(moods[i].Name, results[i].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntities_WhenMappingEmptyCollection_ShouldReturnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
List<Mood> moods = [];
|
||||
|
||||
// Act
|
||||
IEnumerable<TrackMoodEntity> results = moods.ToRepositoryEntities();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(results);
|
||||
Assert.Empty(results);
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
|
||||
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.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddTrackCommandMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddTrackCommandMappingTests
|
||||
{
|
||||
private readonly AddTrackCommandFixture _addTrackCommandFixture = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly MoodDtoFixture _moodDtoFixture = new();
|
||||
private readonly IsrcDtoFixture _isrcDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Track> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(command.Path, result.Value.Path);
|
||||
Assert.Equal(command.Metadata!.Title, result.Value.Metadata.Title);
|
||||
Assert.Equal(command.TrackNumber!.Value, result.Value.TrackNumber);
|
||||
Assert.Equal(command.DiscNumber, result.Value.DiscNumber.Value);
|
||||
Assert.Equal(command.Script, result.Value.Script.Value);
|
||||
Assert.Equal(command.Key, result.Value.Key.Value);
|
||||
Assert.Equal(command.Bpm, result.Value.Bpm.Value);
|
||||
Assert.Equal(command.Work, result.Value.Work.Value);
|
||||
Assert.Equal(command.MusicBrainzRecordingId, result.Value.MusicBrainzRecordingId.Value.Value);
|
||||
Assert.Equal(command.MusicBrainzTrackId, result.Value.MusicBrainzTrackId.Value.Value);
|
||||
Assert.Equal(command.MusicBrainzWorkId, result.Value.MusicBrainzWorkId.Value.Value);
|
||||
Assert.Equal(command.Moods!.Count, result.Value.Moods.Count);
|
||||
Assert.Equal(command.Isrcs!.Count, result.Value.Isrcs.Count);
|
||||
Assert.Equal(command.Contributors!.Count, result.Value.Contributors.Count);
|
||||
Assert.Equal(command.Ratings!.Count, result.Value.Ratings.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTrackIdIsProvided_ShouldReuseTheProvidedTrackId()
|
||||
{
|
||||
// Arrange
|
||||
Guid trackId = Guid.NewGuid();
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create(trackId: trackId);
|
||||
|
||||
// Act
|
||||
Result<Track> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(trackId, result.Value.Id.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTrackIdIsNotProvided_ShouldMintANewTrackId()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Track> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotEqual(Guid.Empty, result.Value.Id.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]));
|
||||
|
||||
// Act
|
||||
Result<Track> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMoodCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(includeName: false)]);
|
||||
|
||||
// Act
|
||||
Result<Track> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.MoodNameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenIsrcCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(value: "invalid")]);
|
||||
|
||||
// Act
|
||||
Result<Track> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.Music.IsrcInvalidFormat.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)]);
|
||||
|
||||
// Act
|
||||
Result<Track> result = command.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMultipleCommands_ShouldMapEachCommand()
|
||||
{
|
||||
// Arrange
|
||||
List<AddTrackCommand> commands = _addTrackCommandFixture.CreateMany(3);
|
||||
|
||||
// Act
|
||||
List<Result<Track>> 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].Path, results[i].Value.Path);
|
||||
Assert.Equal(commands[i].Metadata!.Title, results[i].Value.Metadata.Title);
|
||||
}
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
|
||||
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.Tracks;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddTrackRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddTrackRequestMappingTests
|
||||
{
|
||||
private readonly AddTrackRequestFixture _addTrackRequestFixture = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
AddTrackCommand 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.Path, result.Path);
|
||||
Assert.Equal(request.Metadata, result.Metadata);
|
||||
Assert.Equal(request.TrackNumber, result.TrackNumber);
|
||||
Assert.Equal(request.DiscNumber, result.DiscNumber);
|
||||
Assert.Equal(request.Script, result.Script);
|
||||
Assert.Equal(request.Key, result.Key);
|
||||
Assert.Equal(request.Bpm, result.Bpm);
|
||||
Assert.Equal(request.Work, result.Work);
|
||||
Assert.Equal(request.MusicBrainzRecordingId, result.MusicBrainzRecordingId);
|
||||
Assert.Equal(request.MusicBrainzTrackId, result.MusicBrainzTrackId);
|
||||
Assert.Equal(request.MusicBrainzWorkId, result.MusicBrainzWorkId);
|
||||
Assert.Equal(request.Moods, result.Moods);
|
||||
Assert.Equal(request.Isrcs, result.Isrcs);
|
||||
Assert.Equal(request.Contributors, result.Contributors);
|
||||
Assert.Equal(request.Ratings, result.Ratings);
|
||||
Assert.Null(result.TrackId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredPropertiesAndNulls()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create(
|
||||
path: "/music/queen/bohemian-rhapsody.flac",
|
||||
metadata: _audioMetadataDtoFixture.Create(title: "Love of My Life"),
|
||||
includeOptionalProperties: false);
|
||||
|
||||
// Act
|
||||
AddTrackCommand result = request.ToCommand(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("/music/queen/bohemian-rhapsody.flac", result.Path);
|
||||
Assert.Equal("Love of My Life", result.Metadata!.Title);
|
||||
Assert.Null(result.DiscNumber);
|
||||
Assert.Null(result.Script);
|
||||
Assert.Null(result.Key);
|
||||
Assert.Null(result.Bpm);
|
||||
Assert.Null(result.Work);
|
||||
Assert.Null(result.MusicBrainzRecordingId);
|
||||
Assert.Null(result.MusicBrainzTrackId);
|
||||
Assert.Null(result.MusicBrainzWorkId);
|
||||
Assert.Null(result.Moods);
|
||||
Assert.Null(result.Isrcs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenRouteIdentifiersAreNull_ShouldMapNullRouteIdentifiers()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
AddTrackCommand result = request.ToCommand(null, null, null);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.LibraryId);
|
||||
Assert.Null(result.ArtistId);
|
||||
Assert.Null(result.AlbumId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommands_WhenMappingMultipleRequests_ShouldMapEachRequest()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
List<AddTrackRequest> requests = _addTrackRequestFixture.CreateMany(3);
|
||||
|
||||
// Act
|
||||
List<AddTrackCommand> result = [.. requests.ToCommands(libraryId.ToString(), artistId.ToString(), albumId.ToString())];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(requests.Count, result.Count);
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
{
|
||||
Assert.Equal(requests[i].Path, result[i].Path);
|
||||
Assert.Equal(requests[i].TrackNumber, result[i].TrackNumber);
|
||||
Assert.Equal(libraryId.ToString(), result[i].LibraryId);
|
||||
Assert.Equal(artistId.ToString(), result[i].ArtistId);
|
||||
Assert.Equal(albumId.ToString(), result[i].AlbumId);
|
||||
}
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
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.Common.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AudioMetadataDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AudioMetadataDtoMappingTests
|
||||
{
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = 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
|
||||
AudioMetadataDto dto = _audioMetadataDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<AudioMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AudioMetadata 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.DurationInSeconds, metadata.DurationInSeconds);
|
||||
Assert.Equal(dto.SampleRate, metadata.SampleRate);
|
||||
Assert.Equal(dto.Channels, metadata.Channels);
|
||||
Assert.True(metadata.BitDepth.HasValue);
|
||||
Assert.Equal(dto.BitDepth, metadata.BitDepth.Value);
|
||||
Assert.True(metadata.AudioCodec.HasValue);
|
||||
Assert.Equal(dto.AudioCodec, metadata.AudioCodec.Value);
|
||||
Assert.True(metadata.Bitrate.HasValue);
|
||||
Assert.Equal(dto.Bitrate, metadata.Bitrate.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));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults()
|
||||
{
|
||||
// Arrange
|
||||
AudioMetadataDto dto = _audioMetadataDtoFixture.Create(
|
||||
includeOriginalTitle: false,
|
||||
includeDescription: false,
|
||||
includeReleaseInfo: false,
|
||||
includeLanguage: false,
|
||||
includeOriginalLanguage: false,
|
||||
includeTags: false,
|
||||
includeGenres: false,
|
||||
includeDurationInSeconds: false,
|
||||
includeSampleRate: false,
|
||||
includeChannels: false,
|
||||
includeBitDepth: false,
|
||||
includeAudioCodec: false,
|
||||
includeBitrate: false);
|
||||
|
||||
// Act
|
||||
Result<AudioMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AudioMetadata 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.Equal(0, metadata.DurationInSeconds);
|
||||
Assert.Equal(0, metadata.SampleRate);
|
||||
Assert.Equal(0, metadata.Channels);
|
||||
Assert.False(metadata.BitDepth.HasValue);
|
||||
Assert.False(metadata.AudioCodec.HasValue);
|
||||
Assert.False(metadata.Bitrate.HasValue);
|
||||
Assert.False(metadata.Language.HasValue);
|
||||
Assert.False(metadata.OriginalLanguage.HasValue);
|
||||
Assert.Empty(metadata.Genres);
|
||||
Assert.Empty(metadata.Tags);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenLanguageIsMissingRequiredSubproperties_ShouldMapLanguageToNone()
|
||||
{
|
||||
// Arrange
|
||||
LanguageInfoDto incompleteLanguage = _languageInfoDtoFixture.Create(includeLanguageCode: false);
|
||||
AudioMetadataDto dto = _audioMetadataDtoFixture.Create(
|
||||
language: incompleteLanguage,
|
||||
originalLanguage: _languageInfoDtoFixture.Create(includeLanguageName: false));
|
||||
|
||||
// Act
|
||||
Result<AudioMetadata> 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);
|
||||
AudioMetadataDto dto = _audioMetadataDtoFixture.Create(releaseInfo: releaseInfo);
|
||||
|
||||
// Act
|
||||
Result<AudioMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AudioMetadataDto dto = _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]);
|
||||
|
||||
// Act
|
||||
Result<AudioMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTagIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AudioMetadataDto dto = _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: " ")]);
|
||||
|
||||
// Act
|
||||
Result<AudioMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
}
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
#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.Tracks;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
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.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TrackEntityMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackEntityMappingTests
|
||||
{
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidTrackEntity_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity entity = _trackEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Track> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Track track = result.Value;
|
||||
Assert.Equal(entity.Id, track.Id.Value);
|
||||
Assert.Equal(entity.Path, track.Path);
|
||||
Assert.Equal(entity.Title, track.Metadata.Title);
|
||||
Assert.True(track.Metadata.OriginalTitle.HasValue);
|
||||
Assert.Equal(entity.OriginalTitle, track.Metadata.OriginalTitle.Value);
|
||||
Assert.True(track.Metadata.Description.HasValue);
|
||||
Assert.Equal(entity.Description, track.Metadata.Description.Value);
|
||||
Assert.Equal(entity.OriginalReleaseDate, track.Metadata.ReleaseInfo.OriginalReleaseDate.Value);
|
||||
Assert.Equal(entity.OriginalReleaseYear, track.Metadata.ReleaseInfo.OriginalReleaseYear.Value);
|
||||
Assert.Equal(entity.ReReleaseDate, track.Metadata.ReleaseInfo.ReReleaseDate.Value);
|
||||
Assert.Equal(entity.ReReleaseYear, track.Metadata.ReleaseInfo.ReReleaseYear.Value);
|
||||
Assert.Equal(entity.ReleaseCountry, track.Metadata.ReleaseInfo.ReleaseCountry.Value);
|
||||
Assert.Equal(entity.ReleaseVersion, track.Metadata.ReleaseInfo.ReleaseVersion.Value);
|
||||
Assert.True(track.Metadata.Language.HasValue);
|
||||
Assert.Equal(entity.LanguageCode!.ToLowerInvariant(), track.Metadata.Language.Value.LanguageCode);
|
||||
Assert.Equal(entity.LanguageName, track.Metadata.Language.Value.LanguageName);
|
||||
Assert.Equal(entity.LanguageNativeName, track.Metadata.Language.Value.NativeName.Value);
|
||||
Assert.True(track.Metadata.OriginalLanguage.HasValue);
|
||||
Assert.Equal(entity.OriginalLanguageCode!.ToLowerInvariant(), track.Metadata.OriginalLanguage.Value.LanguageCode);
|
||||
Assert.Equal(entity.OriginalLanguageName, track.Metadata.OriginalLanguage.Value.LanguageName);
|
||||
Assert.Equal(entity.OriginalLanguageNativeName, track.Metadata.OriginalLanguage.Value.NativeName.Value);
|
||||
Assert.Equal(entity.DurationInSeconds, track.Metadata.DurationInSeconds);
|
||||
Assert.Equal(entity.SampleRate, track.Metadata.SampleRate);
|
||||
Assert.Equal(entity.Channels, track.Metadata.Channels);
|
||||
Assert.Equal(entity.BitDepth, track.Metadata.BitDepth.Value);
|
||||
Assert.Equal(entity.AudioCodec, track.Metadata.AudioCodec.Value);
|
||||
Assert.Equal(entity.Bitrate, track.Metadata.Bitrate.Value);
|
||||
Assert.Equal(entity.Genres.Select(genre => genre.Name).OrderBy(name => name), track.Metadata.Genres.Select(genre => genre.Name).OrderBy(name => name));
|
||||
Assert.Equal(entity.Tags.Select(tag => tag.Name).OrderBy(name => name), track.Metadata.Tags.Select(tag => tag.Name).OrderBy(name => name));
|
||||
Assert.Equal(entity.TrackNumber, track.TrackNumber);
|
||||
Assert.Equal(entity.DiscNumber, track.DiscNumber.Value);
|
||||
Assert.Equal(entity.Script, track.Script.Value);
|
||||
Assert.Equal(entity.Key, track.Key.Value);
|
||||
Assert.Equal(entity.Bpm, track.Bpm.Value);
|
||||
Assert.Equal(entity.Work, track.Work.Value);
|
||||
Assert.Equal(entity.MusicBrainzRecordingId, track.MusicBrainzRecordingId.Value.Value);
|
||||
Assert.Equal(entity.MusicBrainzTrackId, track.MusicBrainzTrackId.Value.Value);
|
||||
Assert.Equal(entity.MusicBrainzWorkId, track.MusicBrainzWorkId.Value.Value);
|
||||
Assert.Equal(entity.Moods.Select(mood => mood.Name), track.Moods.Select(mood => mood.Name));
|
||||
Assert.Equal(entity.Isrcs.Select(isrc => isrc.Value), track.Isrcs.Select(isrc => isrc.Value));
|
||||
Assert.Equal(entity.Ratings.Select(rating => rating.Value), track.Ratings.Select(rating => (decimal?)rating.Value));
|
||||
Assert.Equal(entity.Contributors.Select(contributor => contributor.MediaContributorId), track.Contributors.Select(contributor => contributor.ContributorId.Value));
|
||||
Assert.Equal(entity.Contributors.Select(contributor => contributor.Role), track.Contributors.Select(contributor => contributor.Role));
|
||||
Assert.Equal(entity.CreatedOnUtc, track.CreatedOnUtc);
|
||||
Assert.Equal(entity.UpdatedOnUtc, track.UpdatedOnUtc.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenReleaseDateAndYearDoNotMatch_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity entity = _trackEntityFixture.Create(
|
||||
originalReleaseDate: new DateOnly(2000, 1, 1),
|
||||
originalReleaseYear: 1999);
|
||||
|
||||
// Act
|
||||
Result<Track> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity entity = _trackEntityFixture.Create();
|
||||
entity.Genres = [new GenreEntity(string.Empty)];
|
||||
|
||||
// Act
|
||||
Result<Track> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTagIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity entity = _trackEntityFixture.Create();
|
||||
entity.Tags = [new TagEntity(" ")];
|
||||
|
||||
// Act
|
||||
Result<Track> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMoodIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity entity = _trackEntityFixture.Create();
|
||||
entity.Moods = [new TrackMoodEntity(string.Empty)];
|
||||
|
||||
// Act
|
||||
Result<Track> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.MoodNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenIsrcIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity entity = _trackEntityFixture.Create();
|
||||
entity.Isrcs = [new TrackIsrcEntity("not-an-isrc")];
|
||||
|
||||
// Act
|
||||
Result<Track> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.IsrcInvalidFormat, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenRatingIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity entity = _trackEntityFixture.Create();
|
||||
entity.Ratings = [_audioRatingEntityFixture.Create(value: 6, maxValue: 5, includeSource: false, includeVoteCount: false)];
|
||||
|
||||
// Act
|
||||
Result<Track> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingTrackEntity_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity entity = _trackEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
TrackResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(entity.Id, result.Id);
|
||||
Assert.Equal(entity.AlbumId, result.AlbumId);
|
||||
Assert.Equal(entity.LibraryId, result.LibraryId);
|
||||
Assert.Equal(entity.Path, result.Path);
|
||||
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.DurationInSeconds, result.Metadata.DurationInSeconds);
|
||||
Assert.Equal(entity.SampleRate, result.Metadata.SampleRate);
|
||||
Assert.Equal(entity.Channels, result.Metadata.Channels);
|
||||
Assert.Equal(entity.BitDepth, result.Metadata.BitDepth);
|
||||
Assert.Equal(entity.AudioCodec, result.Metadata.AudioCodec);
|
||||
Assert.Equal(entity.Bitrate, result.Metadata.Bitrate);
|
||||
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.TrackNumber, result.TrackNumber);
|
||||
Assert.Equal(entity.DiscNumber, result.DiscNumber);
|
||||
Assert.Equal(entity.Script, result.Script);
|
||||
Assert.Equal(entity.Key, result.Key);
|
||||
Assert.Equal(entity.Bpm, result.Bpm);
|
||||
Assert.Equal(entity.Work, result.Work);
|
||||
Assert.Equal(entity.MusicBrainzRecordingId, result.MusicBrainzRecordingId);
|
||||
Assert.Equal(entity.MusicBrainzTrackId, result.MusicBrainzTrackId);
|
||||
Assert.Equal(entity.MusicBrainzWorkId, result.MusicBrainzWorkId);
|
||||
Assert.Equal(entity.CreatedOnUtc, result.CreatedOnUtc);
|
||||
Assert.Equal(entity.UpdatedOnUtc, result.UpdatedOnUtc);
|
||||
Assert.Equal(entity.Moods.Select(mood => mood.Name), result.Moods!.Select(mood => mood.Name));
|
||||
Assert.Equal(entity.Isrcs.Select(isrc => isrc.Value), result.Isrcs!.Select(isrc => isrc.Value));
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenLanguageSubpropertiesAreBlank_ShouldMapLanguagesToNull()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity entity = _trackEntityFixture.Create();
|
||||
entity.LanguageCode = null;
|
||||
entity.LanguageName = null;
|
||||
entity.LanguageNativeName = null;
|
||||
entity.OriginalLanguageCode = null;
|
||||
entity.OriginalLanguageName = null;
|
||||
entity.OriginalLanguageNativeName = null;
|
||||
|
||||
// Act
|
||||
TrackResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Metadata.Language);
|
||||
Assert.Null(result.Metadata.OriginalLanguage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleTrackEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<TrackEntity> entities = _trackEntityFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<TrackResponse> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TrackLiteRowMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackLiteRowMappingTests
|
||||
{
|
||||
private readonly TrackLiteRowFixture _trackLiteRowFixture = new();
|
||||
private readonly PaginatedResultDtoFixture<TrackLiteRow> _paginatedResultDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingTrackLiteRow_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TrackLiteRow readModel = _trackLiteRowFixture.Create();
|
||||
|
||||
// Act
|
||||
TrackLiteResponse result = readModel.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(readModel.Id, result.Id);
|
||||
Assert.Equal(readModel.Title, result.Title);
|
||||
Assert.Equal(readModel.TrackNumber, result.TrackNumber);
|
||||
Assert.Equal(readModel.DiscNumber, result.DiscNumber);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenDiscNumberIsProvided_ShouldMapIt()
|
||||
{
|
||||
// Arrange
|
||||
TrackLiteRow readModel = _trackLiteRowFixture.Create(discNumber: 2);
|
||||
|
||||
// Act
|
||||
TrackLiteResponse result = readModel.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.DiscNumber);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleTrackLiteRows_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<TrackLiteRow> readModels = _trackLiteRowFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<TrackLiteResponse> 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.TrackNumber), results.Select(response => response.TrackNumber));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingPaginatedTrackLiteRows_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<TrackLiteRow> readModels = _trackLiteRowFixture.CreateMany(2);
|
||||
PaginatedResultDto<TrackLiteRow> paginatedReadModels = _paginatedResultDtoFixture.Create(
|
||||
data: readModels,
|
||||
currentPage: 1,
|
||||
perPage: 10,
|
||||
count: 2,
|
||||
numberOfPages: 1);
|
||||
|
||||
// Act
|
||||
PaginatedResponse<TrackLiteResponse> 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);
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
#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.Common;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.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.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TrackMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackMappingTests
|
||||
{
|
||||
private readonly TrackFixture _trackFixture = new();
|
||||
private readonly AudioMetadataFixture _audioMetadataFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingCompleteTrack_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Track track = _trackFixture.Create();
|
||||
|
||||
// Act
|
||||
TrackEntity result = track.ToRepositoryEntity(albumId, libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(track.Id.Value, result.Id);
|
||||
Assert.Equal(albumId, result.AlbumId);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
Assert.Equal(track.Path, result.Path);
|
||||
Assert.Equal(track.Metadata.Title, result.Title);
|
||||
Assert.Equal(track.Metadata.OriginalTitle.HasValue ? track.Metadata.OriginalTitle.Value : null, result.OriginalTitle);
|
||||
Assert.Equal(track.Metadata.Description.HasValue ? track.Metadata.Description.Value : null, result.Description);
|
||||
Assert.Equal(track.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue ? track.Metadata.ReleaseInfo.OriginalReleaseDate.Value : null, result.OriginalReleaseDate);
|
||||
Assert.Equal(track.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue ? track.Metadata.ReleaseInfo.OriginalReleaseYear.Value : null, result.OriginalReleaseYear);
|
||||
Assert.Equal(track.Metadata.ReleaseInfo.ReReleaseDate.HasValue ? track.Metadata.ReleaseInfo.ReReleaseDate.Value : null, result.ReReleaseDate);
|
||||
Assert.Equal(track.Metadata.ReleaseInfo.ReReleaseYear.HasValue ? track.Metadata.ReleaseInfo.ReReleaseYear.Value : null, result.ReReleaseYear);
|
||||
Assert.Equal(track.Metadata.ReleaseInfo.ReleaseCountry.HasValue ? track.Metadata.ReleaseInfo.ReleaseCountry.Value : null, result.ReleaseCountry);
|
||||
Assert.Equal(track.Metadata.ReleaseInfo.ReleaseVersion.HasValue ? track.Metadata.ReleaseInfo.ReleaseVersion.Value : null, result.ReleaseVersion);
|
||||
Assert.Equal(track.Metadata.Language.HasValue ? track.Metadata.Language.Value.LanguageCode : null, result.LanguageCode);
|
||||
Assert.Equal(track.Metadata.Language.HasValue ? track.Metadata.Language.Value.LanguageName : null, result.LanguageName);
|
||||
Assert.Equal(track.Metadata.Language.HasValue && track.Metadata.Language.Value.NativeName.HasValue ? track.Metadata.Language.Value.NativeName.Value : null, result.LanguageNativeName);
|
||||
Assert.Equal(track.Metadata.OriginalLanguage.HasValue ? track.Metadata.OriginalLanguage.Value.LanguageCode : null, result.OriginalLanguageCode);
|
||||
Assert.Equal(track.Metadata.OriginalLanguage.HasValue ? track.Metadata.OriginalLanguage.Value.LanguageName : null, result.OriginalLanguageName);
|
||||
Assert.Equal(track.Metadata.OriginalLanguage.HasValue && track.Metadata.OriginalLanguage.Value.NativeName.HasValue ? track.Metadata.OriginalLanguage.Value.NativeName.Value : null, result.OriginalLanguageNativeName);
|
||||
// The repository entity stores genres and tags as sets, so duplicate names in the domain collection collapse into a single entry.
|
||||
Assert.Equal(track.Metadata.Genres.ToRepositoryEntities().Distinct().OrderBy(genre => genre.Name), result.Genres.OrderBy(genre => genre.Name));
|
||||
Assert.Equal(track.Metadata.Tags.ToRepositoryEntities().Distinct().OrderBy(tag => tag.Name), result.Tags.OrderBy(tag => tag.Name));
|
||||
Assert.Equal(track.Metadata.DurationInSeconds, result.DurationInSeconds);
|
||||
Assert.Equal(track.Metadata.SampleRate, result.SampleRate);
|
||||
Assert.Equal(track.Metadata.Channels, result.Channels);
|
||||
Assert.Equal(track.Metadata.BitDepth.HasValue ? track.Metadata.BitDepth.Value : null, result.BitDepth);
|
||||
Assert.Equal(track.Metadata.AudioCodec.HasValue ? track.Metadata.AudioCodec.Value : null, result.AudioCodec);
|
||||
Assert.Equal(track.Metadata.Bitrate.HasValue ? track.Metadata.Bitrate.Value : null, result.Bitrate);
|
||||
Assert.Equal(track.TrackNumber, result.TrackNumber);
|
||||
Assert.Equal(track.DiscNumber.HasValue ? track.DiscNumber.Value : null, result.DiscNumber);
|
||||
Assert.Equal(track.Script.HasValue ? track.Script.Value : null, result.Script);
|
||||
Assert.Equal(track.Key.HasValue ? track.Key.Value : null, result.Key);
|
||||
Assert.Equal(track.Bpm.HasValue ? track.Bpm.Value : null, result.Bpm);
|
||||
Assert.Equal(track.Work.HasValue ? track.Work.Value : null, result.Work);
|
||||
Assert.Equal(track.MusicBrainzRecordingId.HasValue ? track.MusicBrainzRecordingId.Value.Value : null, result.MusicBrainzRecordingId);
|
||||
Assert.Equal(track.MusicBrainzTrackId.HasValue ? track.MusicBrainzTrackId.Value.Value : null, result.MusicBrainzTrackId);
|
||||
Assert.Equal(track.MusicBrainzWorkId.HasValue ? track.MusicBrainzWorkId.Value.Value : null, result.MusicBrainzWorkId);
|
||||
Assert.Equal(track.Moods.ToRepositoryEntities(), result.Moods);
|
||||
Assert.Equal(track.Isrcs.ToRepositoryEntities(), result.Isrcs);
|
||||
Assert.Equal(track.Ratings.ToRepositoryEntities(), result.Ratings);
|
||||
Assert.Equal(track.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 albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Track track = _trackFixture.Create();
|
||||
|
||||
// Act
|
||||
TrackEntity result = track.ToRepositoryEntity(albumId, libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(track.Contributors.Count, result.Contributors.Count);
|
||||
for (int i = 0; i < track.Contributors.Count; i++)
|
||||
{
|
||||
MusicMediaContributor contributor = track.Contributors.ElementAt(i);
|
||||
TrackContributorEntity contributorEntity = result.Contributors[i];
|
||||
Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId);
|
||||
Assert.Equal(contributor.Role, contributorEntity.Role);
|
||||
Assert.Equal(track.Id.Value, contributorEntity.TrackId);
|
||||
Assert.Equal(track.CreatedOnUtc, contributorEntity.CreatedOnUtc);
|
||||
Assert.Equal(Guid.Empty, contributorEntity.CreatedBy);
|
||||
Assert.Null(contributorEntity.UpdatedOnUtc);
|
||||
Assert.Null(contributorEntity.UpdatedBy);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNulls()
|
||||
{
|
||||
// Arrange
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AudioMetadata metadata = _audioMetadataFixture.Create(
|
||||
originalTitle: Optional<string>.None(),
|
||||
description: Optional<string>.None(),
|
||||
releaseInfo: ReleaseInfo.Create(
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<int>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<int>.None(),
|
||||
Optional<ReleaseCountry>.None(),
|
||||
Optional<string>.None()).Value,
|
||||
language: Optional<LanguageInfo>.None(),
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
bitDepth: Optional<int>.None(),
|
||||
audioCodec: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
Track track = _trackFixture.Create(
|
||||
metadata: metadata,
|
||||
discNumber: Optional<int>.None(),
|
||||
script: Optional<string>.None(),
|
||||
key: Optional<MusicKey>.None(),
|
||||
bpm: Optional<int>.None(),
|
||||
work: Optional<string>.None(),
|
||||
moods: [],
|
||||
isrcs: [],
|
||||
musicBrainzRecordingId: Optional<MusicBrainzId>.None(),
|
||||
musicBrainzTrackId: Optional<MusicBrainzId>.None(),
|
||||
musicBrainzWorkId: Optional<MusicBrainzId>.None(),
|
||||
contributors: [],
|
||||
ratings: []);
|
||||
|
||||
// Act
|
||||
TrackEntity result = track.ToRepositoryEntity(albumId, libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.OriginalTitle);
|
||||
Assert.Null(result.Description);
|
||||
Assert.Null(result.OriginalReleaseDate);
|
||||
Assert.Null(result.OriginalReleaseYear);
|
||||
Assert.Null(result.ReReleaseDate);
|
||||
Assert.Null(result.ReReleaseYear);
|
||||
Assert.Null(result.ReleaseCountry);
|
||||
Assert.Null(result.ReleaseVersion);
|
||||
Assert.Null(result.LanguageCode);
|
||||
Assert.Null(result.LanguageName);
|
||||
Assert.Null(result.LanguageNativeName);
|
||||
Assert.Null(result.OriginalLanguageCode);
|
||||
Assert.Null(result.OriginalLanguageName);
|
||||
Assert.Null(result.OriginalLanguageNativeName);
|
||||
Assert.Null(result.BitDepth);
|
||||
Assert.Null(result.AudioCodec);
|
||||
Assert.Null(result.Bitrate);
|
||||
Assert.Null(result.DiscNumber);
|
||||
Assert.Null(result.Script);
|
||||
Assert.Null(result.Key);
|
||||
Assert.Null(result.Bpm);
|
||||
Assert.Null(result.Work);
|
||||
Assert.Null(result.MusicBrainzRecordingId);
|
||||
Assert.Null(result.MusicBrainzTrackId);
|
||||
Assert.Null(result.MusicBrainzWorkId);
|
||||
Assert.Empty(result.Moods);
|
||||
Assert.Empty(result.Isrcs);
|
||||
Assert.Empty(result.Contributors);
|
||||
Assert.Empty(result.Ratings);
|
||||
}
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateTrackCommandMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateTrackCommandMappingTests
|
||||
{
|
||||
private readonly UpdateTrackCommandFixture _updateTrackCommandFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly MoodDtoFixture _moodDtoFixture = new();
|
||||
private readonly IsrcDtoFixture _isrcDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
|
||||
string updatedPath = "/music/queen/a-night-at-the-opera/02-love-of-my-life.flac";
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), path: updatedPath);
|
||||
|
||||
// Act
|
||||
Result<Artist> result = command.ToDomainEntity(artist);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(artist, result.Value);
|
||||
Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId);
|
||||
Assert.Equal(updatedPath, updatedTrack.Path);
|
||||
Assert.Equal(command.Metadata!.Title, updatedTrack.Metadata.Title);
|
||||
Assert.Equal(command.TrackNumber, updatedTrack.TrackNumber);
|
||||
Assert.True(updatedTrack.DiscNumber.HasValue);
|
||||
Assert.Equal(command.DiscNumber, updatedTrack.DiscNumber.Value);
|
||||
Assert.True(updatedTrack.Script.HasValue);
|
||||
Assert.Equal(command.Script, updatedTrack.Script.Value);
|
||||
Assert.True(updatedTrack.Key.HasValue);
|
||||
Assert.Equal(command.Key, updatedTrack.Key.Value);
|
||||
Assert.True(updatedTrack.Bpm.HasValue);
|
||||
Assert.Equal(command.Bpm, updatedTrack.Bpm.Value);
|
||||
Assert.True(updatedTrack.Work.HasValue);
|
||||
Assert.Equal(command.Work, updatedTrack.Work.Value);
|
||||
Assert.Equal(command.MusicBrainzRecordingId, updatedTrack.MusicBrainzRecordingId.Value.Value);
|
||||
Assert.Equal(command.MusicBrainzTrackId, updatedTrack.MusicBrainzTrackId.Value.Value);
|
||||
Assert.Equal(command.MusicBrainzWorkId, updatedTrack.MusicBrainzWorkId.Value.Value);
|
||||
Assert.Equal(command.Moods!.Count, updatedTrack.Moods.Count);
|
||||
Assert.Equal(command.Isrcs!.Count, updatedTrack.Isrcs.Count);
|
||||
Assert.Equal(command.Contributors!.Count, updatedTrack.Contributors.Count);
|
||||
Assert.Equal(command.Ratings!.Count, updatedTrack.Ratings.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapRequiredPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
|
||||
string updatedPath = "/music/queen/a-night-at-the-opera/03-you-re-my-best-friend.flac";
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), path: updatedPath, includeOptionalProperties: false, contributors: [], ratings: []);
|
||||
|
||||
// Act
|
||||
Result<Artist> result = command.ToDomainEntity(artist);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId);
|
||||
Assert.Equal(updatedPath, updatedTrack.Path);
|
||||
Assert.Equal(command.TrackNumber, updatedTrack.TrackNumber);
|
||||
Assert.False(updatedTrack.DiscNumber.HasValue);
|
||||
Assert.False(updatedTrack.Script.HasValue);
|
||||
Assert.False(updatedTrack.Key.HasValue);
|
||||
Assert.False(updatedTrack.Bpm.HasValue);
|
||||
Assert.False(updatedTrack.Work.HasValue);
|
||||
Assert.False(updatedTrack.MusicBrainzRecordingId.HasValue);
|
||||
Assert.False(updatedTrack.MusicBrainzTrackId.HasValue);
|
||||
Assert.False(updatedTrack.MusicBrainzWorkId.HasValue);
|
||||
Assert.Empty(updatedTrack.Moods);
|
||||
Assert.Empty(updatedTrack.Isrcs);
|
||||
Assert.Empty(updatedTrack.Contributors);
|
||||
Assert.Empty(updatedTrack.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
artistId: artist.Id.Value.ToString(),
|
||||
albumId: albumId.ToString(),
|
||||
trackId: trackId.ToString(),
|
||||
metadata: _audioMetadataDtoFixture.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_WhenMoodCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), moods: [_moodDtoFixture.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.MoodNameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenIsrcCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), isrcs: [_isrcDtoFixture.Create(value: string.Empty)]);
|
||||
|
||||
// Act
|
||||
Result<Artist> result = command.ToDomainEntity(artist);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.Music.IsrcValueCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.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_WhenTheSameContributorHasDifferentRoles_ShouldKeepBothRoles()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
|
||||
Guid contributorId = Guid.NewGuid();
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
artistId: artist.Id.Value.ToString(),
|
||||
albumId: albumId.ToString(),
|
||||
trackId: trackId.ToString(),
|
||||
contributors:
|
||||
[
|
||||
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Vocals),
|
||||
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Guitar)
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<Artist> result = command.ToDomainEntity(artist);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId);
|
||||
Assert.Equal(2, updatedTrack.Contributors.Count);
|
||||
Assert.All(updatedTrack.Contributors, contributor => Assert.Equal(contributorId, contributor.ContributorId.Value));
|
||||
Assert.Contains(updatedTrack.Contributors, contributor => contributor.Role == MediaContributorRole.Vocals);
|
||||
Assert.Contains(updatedTrack.Contributors, contributor => contributor.Role == MediaContributorRole.Guitar);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenAlbumIsNotPartOfTheArtist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid _, Guid trackId) = CreateDomainArtist(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: Guid.NewGuid().ToString(), trackId: trackId.ToString());
|
||||
|
||||
// Act
|
||||
Result<Artist> result = command.ToDomainEntity(artist);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTrackIsNotPartOfTheAlbum_ShouldReturnTrackNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId, Guid _) = CreateDomainArtist(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
Result<Artist> result = command.ToDomainEntity(artist);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a domain artist that owns a single album, which in turn owns a single track, all belonging to <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <returns>The created domain artist, together with the Ids of its album and track.</returns>
|
||||
private (Artist artist, Guid albumId, Guid trackId) CreateDomainArtist(Guid libraryId)
|
||||
{
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
AlbumEntity albumEntity = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
libraryId: libraryId,
|
||||
tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)]);
|
||||
ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]);
|
||||
Result<Artist> artistResult = artistEntity.ToDomainEntity();
|
||||
return (artistResult.Value, albumId, trackId);
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateTrackRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateTrackRequestMappingTests
|
||||
{
|
||||
private readonly UpdateTrackRequestFixture _updateTrackRequestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
UpdateTrackCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString(), albumId.ToString(), trackId.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(trackId.ToString(), result.TrackId);
|
||||
Assert.Equal(request.Path, result.Path);
|
||||
Assert.Equal(request.Metadata, result.Metadata);
|
||||
Assert.Equal(request.TrackNumber, result.TrackNumber);
|
||||
Assert.Equal(request.DiscNumber, result.DiscNumber);
|
||||
Assert.Equal(request.Script, result.Script);
|
||||
Assert.Equal(request.Key, result.Key);
|
||||
Assert.Equal(request.Bpm, result.Bpm);
|
||||
Assert.Equal(request.Work, result.Work);
|
||||
Assert.Equal(request.MusicBrainzRecordingId, result.MusicBrainzRecordingId);
|
||||
Assert.Equal(request.MusicBrainzTrackId, result.MusicBrainzTrackId);
|
||||
Assert.Equal(request.MusicBrainzWorkId, result.MusicBrainzWorkId);
|
||||
Assert.Equal(request.Moods, result.Moods);
|
||||
Assert.Equal(request.Isrcs, result.Isrcs);
|
||||
Assert.Equal(request.Contributors, result.Contributors);
|
||||
Assert.Equal(request.Ratings, result.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create(includeOptionalProperties: false, contributors: [], ratings: []);
|
||||
|
||||
// Act
|
||||
UpdateTrackCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString(), albumId.ToString(), trackId.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(trackId.ToString(), result.TrackId);
|
||||
Assert.NotNull(result.Metadata);
|
||||
Assert.Equal(request.Metadata, result.Metadata);
|
||||
Assert.Null(result.DiscNumber);
|
||||
Assert.Null(result.Script);
|
||||
Assert.Null(result.Key);
|
||||
Assert.Null(result.Bpm);
|
||||
Assert.Null(result.Work);
|
||||
Assert.Null(result.MusicBrainzRecordingId);
|
||||
Assert.Null(result.MusicBrainzTrackId);
|
||||
Assert.Null(result.MusicBrainzWorkId);
|
||||
Assert.Null(result.Moods);
|
||||
Assert.Null(result.Isrcs);
|
||||
Assert.Empty(result.Contributors!);
|
||||
Assert.Empty(result.Ratings!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create(
|
||||
moods: [new("dramatic")],
|
||||
isrcs: [new("GBUM71029604")],
|
||||
contributors: [new(Guid.NewGuid(), MediaContributorRole.Vocals)],
|
||||
ratings: [new(4.5m, 5m, AudioRatingSource.MusicBrainz, 1000)],
|
||||
includeOptionalProperties: false);
|
||||
|
||||
// Act
|
||||
UpdateTrackCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString(), albumId.ToString(), trackId.ToString());
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(request.Moods, result.Moods);
|
||||
Assert.Equal(request.Isrcs, result.Isrcs);
|
||||
Assert.Equal(request.Contributors, result.Contributors);
|
||||
Assert.Equal(request.Ratings, result.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenCalledWithRouteIds_ShouldMapRouteIdsFromArguments()
|
||||
{
|
||||
// Arrange
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
UpdateTrackCommand result = request.ToCommand("library-route", "artist-route", "album-route", "track-route");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("library-route", result.LibraryId);
|
||||
Assert.Equal("artist-route", result.ArtistId);
|
||||
Assert.Equal("album-route", result.AlbumId);
|
||||
Assert.Equal("track-route", result.TrackId);
|
||||
}
|
||||
}
|
||||
+548
@@ -0,0 +1,548 @@
|
||||
#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.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.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;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
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.Tracks.Commands.AddTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddTrackCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddTrackCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IArtistRepository _mockArtistRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly ITrackRepository _mockTrackRepository;
|
||||
private readonly IMediaContributorRepository _mockMediaContributorRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<AddTrackCommand> _mockValidator;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly Guid _userId;
|
||||
private readonly AddTrackCommandHandler _sut;
|
||||
private readonly AddTrackCommandFixture _addTrackCommandFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddTrackCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public AddTrackCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockArtistRepository = Substitute.For<IArtistRepository>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockTrackRepository = Substitute.For<ITrackRepository>();
|
||||
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockValidator = Substitute.For<IValidator<AddTrackCommand>>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
|
||||
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
|
||||
// Default stub: saving changes succeeds.
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
// Default stub: the validator passes and the current user is authenticated.
|
||||
_mockValidator.Validate(Arg.Any<AddTrackCommand>()).Returns([]);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
// Default stub: the library ownership policy allows access.
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
// Default stub: the library exists and the track path is 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 track can be read back by its Id.
|
||||
_mockTrackRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Result.From<TrackEntity?>(_trackEntityFixture.Create(id: callInfo.Arg<Guid>())));
|
||||
_sut = new AddTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<AddTrackCommand>())
|
||||
.Returns([Errors.Music.TrackPathCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackPathCannotBeEmpty, 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
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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 _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<ArtistEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingPolicy()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
ArrangeArtist(command, libraryId: Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The mismatch is reported as not found, without disclosing that the artist exists in another library.
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
ArrangeArtist(command);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumDoesNotExistInTheArtist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
ArrangeArtist(command, albumId: Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
ArrangeArtist(command);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
ArrangeArtist(command);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<LibraryEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTrackPathIsNotWithinLibraryContentLocations_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
ArrangeArtist(command);
|
||||
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]);
|
||||
ArrangeArtist(command);
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]);
|
||||
ArrangeArtist(command);
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([]));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create(contributors: []);
|
||||
ArrangeArtist(command);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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_WhenArtistDomainConversionFails_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
ArrangeArtist(command, name: string.Empty);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError);
|
||||
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]));
|
||||
ArrangeArtist(command);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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_WhenTrackIsAlreadyInTheAlbum_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity existingTrack = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
album.Tracks = [existingTrack];
|
||||
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false);
|
||||
artist.Albums = [album];
|
||||
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(artist));
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString(), trackId: trackId);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TheTrackIsAlreadyInTheAlbum, 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
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
ArrangeArtist(command);
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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_ShouldReturnFailureResultWithoutReadingTheTrack()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
ArrangeArtist(command);
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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 _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPersistedTrackCannotBeRead_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
ArrangeArtist(command);
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
_mockTrackRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Music.TrackIdCannotBeEmpty);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackIdCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPersistedTrackDoesNotExist_ShouldReturnTrackNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
ArrangeArtist(command);
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
_mockTrackRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<TrackEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalledWithValidCommand_ShouldPersistTheTrackAndReturnItsResponse()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackCommand command = _addTrackCommandFixture.Create();
|
||||
Guid albumId = Guid.Parse(command.AlbumId!);
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
ArrangeArtist(command);
|
||||
ArtistEntity? updatedArtist = null;
|
||||
TrackEntity? persistedTrack = null;
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
updatedArtist = callInfo.Arg<ArtistEntity>();
|
||||
return Result.Updated;
|
||||
});
|
||||
_mockTrackRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
persistedTrack = _trackEntityFixture.Create(id: callInfo.Arg<Guid>(), albumId: albumId, libraryId: libraryId);
|
||||
return Result.From<TrackEntity?>(persistedTrack);
|
||||
});
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(persistedTrack);
|
||||
Assert.NotNull(updatedArtist);
|
||||
Assert.Equal(persistedTrack!.Id, result.Value.Id);
|
||||
Assert.Equal(persistedTrack.Path, result.Value.Path);
|
||||
Assert.Equal(persistedTrack.Title, result.Value.Metadata.Title);
|
||||
Assert.Contains(updatedArtist!.Albums.Single().Tracks, track => track.Id == persistedTrack.Id);
|
||||
await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Arranges an existing artist that matches the route identifiers of <paramref name="command"/>, together with one album.
|
||||
/// </summary>
|
||||
/// <param name="command">The command whose route identifiers are used.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album contained by the artist, when it must differ from the route album Id.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the artist belongs to, when it must differ from the route library Id.</param>
|
||||
/// <param name="name">Optional. The name of the artist.</param>
|
||||
/// <returns>The existing artist entity.</returns>
|
||||
private ArtistEntity ArrangeArtist(AddTrackCommand command, Guid? albumId = null, Guid? libraryId = null, string? name = null)
|
||||
{
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
Guid resolvedLibraryId = libraryId ?? Guid.Parse(command.LibraryId!);
|
||||
Guid resolvedAlbumId = albumId ?? Guid.Parse(command.AlbumId!);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: resolvedAlbumId, artistId: artistId, libraryId: resolvedLibraryId, includeTracks: false, includeMetadata: false);
|
||||
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: resolvedLibraryId, name: name, includeAlbums: false, includeContributors: false);
|
||||
artist.Albums = [album];
|
||||
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(artist));
|
||||
return artist;
|
||||
}
|
||||
}
|
||||
+1454
File diff suppressed because it is too large.
Load diff
+483
@@ -0,0 +1,483 @@
|
||||
#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.Tracks.Commands.DeleteTrack;
|
||||
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.Tracks.Commands.DeleteTrack;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteTrackCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteTrackCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IArtistRepository _mockArtistRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<DeleteTrackCommand> _mockValidator;
|
||||
private readonly DeleteTrackCommandHandler _sut;
|
||||
private readonly DeleteTrackCommandFixture _deleteTrackCommandFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly Guid _userId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteTrackCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteTrackCommandHandlerTests()
|
||||
{
|
||||
_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<DeleteTrackCommand>>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the artist update succeeds and saving changes succeeds.
|
||||
_mockValidator.Validate(Arg.Any<DeleteTrackCommand>()).Returns([]);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success);
|
||||
|
||||
_sut = new DeleteTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTrackExists_ShouldRemoveTrackFromAlbumAndReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
|
||||
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId);
|
||||
StubArtistAndLibrary(artist, libraryId);
|
||||
|
||||
// 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[0].Id == albumId &&
|
||||
updatedArtist.Albums[0].Tracks.Count == 0),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalled_ShouldLoadTheArtistWithNavigationPropertiesAndTheLibraryWithoutTracking()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
|
||||
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId);
|
||||
StubArtistAndLibrary(artist, libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockArtistRepository.Received(1).GetByIdAsync(
|
||||
artistId,
|
||||
shouldIncludeNavigationProperties: true,
|
||||
shouldTrackEntities: false,
|
||||
cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.Received(1).GetByIdAsync(
|
||||
libraryId,
|
||||
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_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<DeleteTrackCommand>())
|
||||
.Returns([DomainErrors.Music.TrackIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Music.TrackIdCannotBeEmpty, result.FirstError);
|
||||
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), 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_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.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_WhenGetArtistFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
(_, Guid artistId, _, _) = GetCommandIds(command);
|
||||
Error error = Error.Failure(description: "Failed to get artist");
|
||||
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, 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>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
(_, Guid artistId, _, _) = GetCommandIds(command);
|
||||
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: 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 _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_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundErrorWithoutEvaluatingThePolicy()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
|
||||
ArtistEntity artist = CreateArtistWithAlbumAndTrack(Guid.NewGuid(), artistId, albumId, trackId);
|
||||
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(artist));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the artist exists in another library.
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _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_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
|
||||
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId);
|
||||
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(artist));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, 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>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumDoesNotExistInArtist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
(Guid libraryId, Guid artistId, _, Guid trackId) = GetCommandIds(command);
|
||||
Guid otherAlbumId = Guid.NewGuid();
|
||||
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, otherAlbumId, trackId);
|
||||
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(artist));
|
||||
|
||||
// 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_WhenTrackDoesNotExistInAlbum_ShouldReturnTrackNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, _) = GetCommandIds(command);
|
||||
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, Guid.NewGuid());
|
||||
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(artist));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Music.TrackNotFound, 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_WhenGetLibraryFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
|
||||
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId);
|
||||
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(artist));
|
||||
Error error = Error.Failure(description: "Failed to get library");
|
||||
_mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
|
||||
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId);
|
||||
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(artist));
|
||||
_mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: 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>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenArtistDomainConversionFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
|
||||
// An empty name is rejected by the artist aggregate invariant, so the repository entity fails to convert to a domain entity.
|
||||
AlbumEntity album = CreateAlbumWithTrack(libraryId, artistId, albumId, trackId);
|
||||
ArtistEntity artist = _artistEntityFixture.Create(
|
||||
id: artistId,
|
||||
libraryId: libraryId,
|
||||
name: string.Empty,
|
||||
albums: [album],
|
||||
includeContributors: false,
|
||||
includeMetadata: false);
|
||||
StubArtistAndLibrary(artist, libraryId);
|
||||
|
||||
// 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_WhenUpdateArtistFails_ShouldReturnErrorWithoutSaving()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
|
||||
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId);
|
||||
StubArtistAndLibrary(artist, libraryId);
|
||||
Error error = Error.Failure(description: "Failed to update artist");
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
|
||||
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId);
|
||||
StubArtistAndLibrary(artist, libraryId);
|
||||
Error error = Error.Failure(description: "Failed to save changes");
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the parsed identifiers carried by <paramref name="command"/>.
|
||||
/// </summary>
|
||||
/// <param name="command">The command whose route identifiers are extracted.</param>
|
||||
/// <returns>The parsed library, artist, album and track identifiers.</returns>
|
||||
private static (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) GetCommandIds(DeleteTrackCommand command)
|
||||
{
|
||||
return (
|
||||
Guid.Parse(command.LibraryId!),
|
||||
Guid.Parse(command.ArtistId!),
|
||||
Guid.Parse(command.AlbumId!),
|
||||
Guid.Parse(command.TrackId!));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an artist that contains a single album, which in turn contains a single track.
|
||||
/// </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.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <returns>The created artist entity, with its album and track graph.</returns>
|
||||
private ArtistEntity CreateArtistWithAlbumAndTrack(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
AlbumEntity album = CreateAlbumWithTrack(libraryId, artistId, albumId, trackId);
|
||||
return _artistEntityFixture.Create(
|
||||
id: artistId,
|
||||
libraryId: libraryId,
|
||||
albums: [album],
|
||||
includeContributors: false,
|
||||
includeMetadata: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an album that contains a single track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <returns>The created album entity, with its track.</returns>
|
||||
private AlbumEntity CreateAlbumWithTrack(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
return _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
tracks: [track],
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artist and library repositories so that the handler finds the artist and the library.
|
||||
/// </summary>
|
||||
/// <param name="artist">The artist returned by the artist repository.</param>
|
||||
/// <param name="libraryId">The Id of the media library returned by the library repository.</param>
|
||||
private void StubArtistAndLibrary(ArtistEntity artist, Guid libraryId)
|
||||
{
|
||||
_mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(artist));
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId);
|
||||
_mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteTrackCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteTrackCommandValidatorTests
|
||||
{
|
||||
private readonly DeleteTrackCommandFixture _deleteTrackCommandFixture = new();
|
||||
private readonly DeleteTrackCommandValidator _validator = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenIdsAreValid_ShouldNotHaveAnyValidationErrors()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData(" ")] // whitespace route value, which the format rule skips but the not empty rule rejects
|
||||
[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
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.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 the format rule skips but the not empty rule rejects
|
||||
[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
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.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 the format rule skips but the not empty rule rejects
|
||||
[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
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create(albumId: albumId, includeAlbumId: albumId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData(" ")] // whitespace route value, which the format rule skips but the not empty rule rejects
|
||||
[InlineData("not-a-track-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenTrackIdIsEmptyOrInvalid_ShouldHaveValidationError(string? trackId)
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create(trackId: trackId, includeTrackId: trackId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenOnlyTheArtistIdIsInvalid_ShouldNotReportUnrelatedValidationErrors()
|
||||
{
|
||||
// Arrange
|
||||
DeleteTrackCommand command = _deleteTrackCommandFixture.Create(artistId: "not-an-artist-guid");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.Music.TrackIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+591
@@ -0,0 +1,591 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
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.Tracks.Commands.UpdateTrack;
|
||||
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.Tracks.Commands.UpdateTrack;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.Tracks;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
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.Tracks.Commands.UpdateTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateTrackCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateTrackCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IArtistRepository _mockArtistRepository;
|
||||
private readonly ITrackRepository _mockTrackRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IMediaContributorRepository _mockMediaContributorRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<UpdateTrackCommand> _mockValidator;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly UpdateTrackCommandHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly UpdateTrackCommandFixture _updateTrackCommandFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateTrackCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateTrackCommandHandlerTests()
|
||||
{
|
||||
_mockArtistRepository = Substitute.For<IArtistRepository>();
|
||||
_mockTrackRepository = Substitute.For<ITrackRepository>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
|
||||
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<UpdateTrackCommand>>();
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
// Default stubs: the current user is authenticated, the library ownership policy allows access, the validator passes,
|
||||
// the track path is within the library content locations, the artist is updated and the library and contributors exist.
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockValidator.Validate(Arg.Any<UpdateTrackCommand>()).Returns([]);
|
||||
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(true);
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
|
||||
_mockTrackRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Result.From<TrackEntity?>(_trackEntityFixture.Create(id: callInfo.ArgAt<Guid>(0))));
|
||||
_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 => new MediaContributorEntity
|
||||
{
|
||||
Id = contributorId,
|
||||
DisplayName = contributorId.ToString(),
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
})]);
|
||||
});
|
||||
|
||||
_sut = new UpdateTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCommandIsValid_ShouldUpdateTrackAndReturnResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
|
||||
ArtistEntity? updatedArtist = null;
|
||||
TrackEntity? updatedTrack = null;
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
updatedArtist = callInfo.Arg<ArtistEntity>();
|
||||
updatedTrack = updatedArtist.Albums.SelectMany(album => album.Tracks).First(track => track.Id == trackId);
|
||||
return Result.Updated;
|
||||
});
|
||||
_mockTrackRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<TrackEntity?>(updatedTrack));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(trackId, result.Value.Id);
|
||||
Assert.Equal(command.Path, result.Value.Path);
|
||||
Assert.Equal(command.Metadata!.Title, result.Value.Metadata!.Title);
|
||||
Assert.Equal(command.Contributors!.Count, result.Value.Contributors!.Count);
|
||||
await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutUpdating()
|
||||
{
|
||||
// Arrange
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<UpdateTrackCommand>()).Returns([Errors.Music.TrackIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackIdCannotBeEmpty, 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
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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_WhenArtistRepositoryReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create();
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Music.ArtistNotFound);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create();
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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_ShouldReturnArtistNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
Guid routeLibraryId = Guid.NewGuid();
|
||||
ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: Guid.NewGuid());
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: routeLibraryId.ToString(), artistId: existingArtist.Id.ToString());
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorWithoutUpdating()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
|
||||
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumIsNotPartOfTheArtist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid _, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: Guid.NewGuid().ToString(), trackId: trackId.ToString());
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTrackIsNotPartOfTheAlbum_ShouldReturnTrackNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid _) = CreateArtistWithTrack(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: Guid.NewGuid().ToString());
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
|
||||
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryRepositoryReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.LibraryNotFound);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundErrorWithoutUpdating()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> 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_WhenPathIsNotWithinLibraryContentLocations_ShouldReturnPathError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create(contentLocations: ["/music/queen"])));
|
||||
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackPathMustBeWithinLibraryContentLocations, result.FirstError);
|
||||
_mockPathService.Received(1).IsPathWithin(command.Path!, Arg.Any<string>());
|
||||
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenNoContributorsAreReferenced_ShouldNotQueryTheContributorRepository()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), contributors: []);
|
||||
ArtistEntity? updatedArtist = null;
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
updatedArtist = callInfo.Arg<ArtistEntity>();
|
||||
return Result.Updated;
|
||||
});
|
||||
_mockTrackRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<TrackEntity?>(updatedArtist!.Albums.SelectMany(album => album.Tracks).First(track => track.Id == trackId)));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenContributorRepositoryReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.MediaContributor.MediaContributorNotFound);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError);
|
||||
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), contributors: [_mediaContributorReferenceDtoFixture.Create()]);
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([]));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError);
|
||||
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenContributorIdsAreDuplicated_ShouldQueryTheRepositoryWithDistinctIds()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
Guid firstContributorId = Guid.NewGuid();
|
||||
Guid secondContributorId = Guid.NewGuid();
|
||||
List<MediaContributorReferenceDto> duplicatedContributors =
|
||||
[
|
||||
_mediaContributorReferenceDtoFixture.Create(contributorId: firstContributorId, role: MediaContributorRole.Vocals),
|
||||
_mediaContributorReferenceDtoFixture.Create(contributorId: firstContributorId, role: MediaContributorRole.Guitar),
|
||||
_mediaContributorReferenceDtoFixture.Create(contributorId: secondContributorId, role: MediaContributorRole.Producer),
|
||||
_mediaContributorReferenceDtoFixture.Create(contributorId: secondContributorId, role: MediaContributorRole.Producer)
|
||||
];
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), contributors: duplicatedContributors);
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockMediaContributorRepository.Received(1).GetByIdsAsync(
|
||||
Arg.Is<IReadOnlyCollection<Guid>>(contributorIds => contributorIds.Count == 2 && contributorIds.Contains(firstContributorId) && contributorIds.Contains(secondContributorId)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenArtistToDomainEntityConversionFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
AlbumEntity invalidAlbum = _albumEntityFixture.Create(id: albumId, libraryId: libraryId, tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)]);
|
||||
invalidAlbum.Genres = [new GenreEntity(string.Empty)];
|
||||
ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: libraryId, albums: [invalidAlbum]);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description);
|
||||
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCommandToDomainEntityConversionFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
AudioMetadataDto invalidMetadata = _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), metadata: invalidMetadata);
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description);
|
||||
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRepositoryUpdateFails_ShouldReturnFailureResultWithoutSaving()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.LibraryNotFound);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReadingThePersistedTrack()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Errors.Library.LibraryNotFound);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
|
||||
await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPersistedTrackIsNotFound_ShouldReturnTrackNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
_mockTrackRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<TrackEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an artist entity that owns a single album, which in turn owns a single track, all belonging to <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <returns>The created artist entity, together with the Ids of its album and track.</returns>
|
||||
private (ArtistEntity artist, Guid albumId, Guid trackId) CreateArtistWithTrack(Guid libraryId)
|
||||
{
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
ArtistEntity artist = _artistEntityFixture.Create(
|
||||
libraryId: libraryId,
|
||||
albums:
|
||||
[
|
||||
_albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
libraryId: libraryId,
|
||||
tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)])
|
||||
]);
|
||||
return (artist, albumId, trackId);
|
||||
}
|
||||
}
|
||||
+1771
File diff suppressed because it is too large.
Load diff
+347
@@ -0,0 +1,347 @@
|
||||
#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.Tracks.Queries.GetTrack;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
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.Tracks.Queries.GetTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetTrackQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTrackQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IAlbumRepository _mockAlbumRepository;
|
||||
private readonly ITrackRepository _mockTrackRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<GetTrackQuery> _mockValidator;
|
||||
private readonly GetTrackQueryHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly GetTrackQueryFixture _getTrackQueryFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public GetTrackQueryHandlerTests()
|
||||
{
|
||||
_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<GetTrackQuery>>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
// Default stubs: the current user is authenticated and the library ownership policy allows access.
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockValidator.Validate(Arg.Any<GetTrackQuery>()).Returns([]);
|
||||
|
||||
_sut = new GetTrackQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTrackExists_ShouldReturnMappedTrackResponse()
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid artistId = Guid.Parse(query.ArtistId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
Guid trackId = Guid.Parse(query.TrackId!);
|
||||
AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
TrackEntity trackEntity = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", title: "Bohemian Rhapsody");
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(albumEntity));
|
||||
_mockTrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<TrackEntity?>(trackEntity));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(trackId, result.Value.Id);
|
||||
Assert.Equal(albumId, result.Value.AlbumId);
|
||||
Assert.Equal(libraryId, result.Value.LibraryId);
|
||||
Assert.Equal("/music/queen/bohemian-rhapsody.flac", result.Value.Path);
|
||||
Assert.Equal("Bohemian Rhapsody", result.Value.Metadata.Title);
|
||||
Assert.Equal(trackEntity.TrackNumber, result.Value.TrackNumber);
|
||||
Assert.NotNull(result.Value.Moods);
|
||||
Assert.NotEmpty(result.Value.Moods!);
|
||||
Assert.NotNull(result.Value.Isrcs);
|
||||
Assert.NotEmpty(result.Value.Isrcs!);
|
||||
Assert.NotNull(result.Value.Contributors);
|
||||
Assert.NotEmpty(result.Value.Contributors!);
|
||||
Assert.NotNull(result.Value.Ratings);
|
||||
Assert.NotEmpty(result.Value.Ratings!);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == trackEntity.LibraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumNotFound_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create();
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(albumEntity));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The route artist id is enforced before the track is read, and 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 _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create();
|
||||
Guid artistId = Guid.Parse(query.ArtistId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: Guid.NewGuid());
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(albumEntity));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The route library id is enforced before the track is read, and 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 _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAlbumRepositoryReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create();
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTrackNotFound_ShouldReturnTrackNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid artistId = Guid.Parse(query.ArtistId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
Guid trackId = Guid.Parse(query.TrackId!);
|
||||
AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(albumEntity));
|
||||
_mockTrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<TrackEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTrackBelongsToAnotherAlbum_ShouldReturnTrackNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid artistId = Guid.Parse(query.ArtistId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
Guid trackId = Guid.Parse(query.TrackId!);
|
||||
AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
TrackEntity trackEntity = _trackEntityFixture.Create(id: trackId, albumId: Guid.NewGuid(), libraryId: libraryId);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(albumEntity));
|
||||
_mockTrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<TrackEntity?>(trackEntity));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The route album id is enforced, so a track of another album can never be read through this album's route.
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTrackBelongsToAnotherLibrary_ShouldReturnTrackNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid artistId = Guid.Parse(query.ArtistId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
Guid trackId = Guid.Parse(query.TrackId!);
|
||||
AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
TrackEntity trackEntity = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: Guid.NewGuid());
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(albumEntity));
|
||||
_mockTrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<TrackEntity?>(trackEntity));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The route library id is enforced, so a track of another library can never be read through this library's route.
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTrackRepositoryReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid artistId = Guid.Parse(query.ArtistId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
Guid trackId = Guid.Parse(query.TrackId!);
|
||||
AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(albumEntity));
|
||||
_mockTrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Music.TrackIdCannotBeEmpty);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackIdCannotBeEmpty, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<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>(), shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid artistId = Guid.Parse(query.ArtistId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
Guid trackId = Guid.Parse(query.TrackId!);
|
||||
AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
TrackEntity trackEntity = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId);
|
||||
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(albumEntity));
|
||||
_mockTrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<TrackEntity?>(trackEntity));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<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 == trackEntity.LibraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<GetTrackQuery>()).Returns([Errors.Music.TrackIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackIdCannotBeEmpty, result.FirstError);
|
||||
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetTrackQueryValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTrackQueryValidatorTests
|
||||
{
|
||||
private readonly GetTrackQueryFixture _getTrackQueryFixture = new();
|
||||
private readonly GetTrackQueryValidator _validator = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenIdsAreValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.Music.TrackIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData(" ")] // whitespace route value, which the format rule skips but the not empty rule rejects
|
||||
[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
|
||||
GetTrackQuery query = _getTrackQueryFixture.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 the format rule skips but the not empty rule rejects
|
||||
[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
|
||||
GetTrackQuery query = _getTrackQueryFixture.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 the format rule skips but the not empty rule rejects
|
||||
[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
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create(albumId: albumId, includeAlbumId: albumId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData(" ")] // whitespace route value, which the format rule skips but the not empty rule rejects
|
||||
[InlineData("not-a-track-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenTrackIdIsEmptyOrInvalid_ShouldHaveValidationError(string? trackId)
|
||||
{
|
||||
// Arrange
|
||||
GetTrackQuery query = _getTrackQueryFixture.Create(trackId: trackId, includeTrackId: trackId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
#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="TrackConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackConfigurationTests : IDisposable
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TrackConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public TrackConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Tracks", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(TrackEntity.Id));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty pathProperty = entityType.GetProperty(nameof(TrackEntity.Path));
|
||||
IProperty titleProperty = entityType.GetProperty(nameof(TrackEntity.Title));
|
||||
IProperty originalTitleProperty = entityType.GetProperty(nameof(TrackEntity.OriginalTitle));
|
||||
IProperty descriptionProperty = entityType.GetProperty(nameof(TrackEntity.Description));
|
||||
IProperty releaseCountryProperty = entityType.GetProperty(nameof(TrackEntity.ReleaseCountry));
|
||||
IProperty scriptProperty = entityType.GetProperty(nameof(TrackEntity.Script));
|
||||
IProperty keyProperty = entityType.GetProperty(nameof(TrackEntity.Key));
|
||||
IProperty audioCodecProperty = entityType.GetProperty(nameof(TrackEntity.AudioCodec));
|
||||
IProperty workProperty = entityType.GetProperty(nameof(TrackEntity.Work));
|
||||
|
||||
// Assert
|
||||
Assert.False(pathProperty.IsNullable);
|
||||
Assert.Equal(2048, pathProperty.GetMaxLength());
|
||||
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(50, scriptProperty.GetMaxLength());
|
||||
Assert.Equal(typeof(MusicKey?), keyProperty.ClrType);
|
||||
Assert.Equal("TEXT", keyProperty.GetColumnType());
|
||||
Assert.Equal(50, keyProperty.GetMaxLength());
|
||||
Assert.Equal(50, audioCodecProperty.GetMaxLength());
|
||||
Assert.Equal(255, workProperty.GetMaxLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAlbumRelationshipWithCascadeDelete()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
List<IForeignKey> foreignKeys = [.. entityType.GetForeignKeys()];
|
||||
|
||||
// Assert
|
||||
IForeignKey albumForeignKey = Assert.Single(foreignKeys);
|
||||
Assert.Equal(nameof(TrackEntity.AlbumId), albumForeignKey.Properties.Single().Name);
|
||||
Assert.Equal(typeof(AlbumEntity), albumForeignKey.PrincipalEntityType.ClrType);
|
||||
Assert.Equal(DeleteBehavior.Cascade, albumForeignKey.DeleteBehavior);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureOwnedTypesForMoodsIsrcsAndRatings()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
List<IEntityType> ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(3, ownedTypes.Count);
|
||||
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackMoodEntity) && ownedType.GetTableName() == "TrackMoods");
|
||||
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackIsrcEntity) && ownedType.GetTableName() == "TrackIsrcs");
|
||||
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(AudioRatingEntity) && ownedType.GetTableName() == "TrackRatings");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureManyToManyJoinTablesForTagsAndGenres()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
List<ISkipNavigation> skipNavigations = [.. entityType.GetSkipNavigations()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, skipNavigations.Count);
|
||||
Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(TrackEntity.Tags) && navigation.JoinEntityType.GetTableName() == "TrackTags");
|
||||
Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(TrackEntity.Genres) && navigation.JoinEntityType.GetTableName() == "TrackGenres");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureIndexesOnAlbumIdTrackNumberAndLibraryIdPath()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
List<IIndex> indexes = [.. entityType.GetIndexes()];
|
||||
|
||||
// Assert
|
||||
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackEntity.AlbumId), nameof(TrackEntity.TrackNumber)]));
|
||||
IIndex pathIndex = Assert.Single(indexes.Where(index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackEntity.LibraryId), nameof(TrackEntity.Path)])));
|
||||
Assert.True(pathIndex.IsUnique);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(TrackEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(TrackEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(TrackEntity.UpdatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
Assert.True(updatedOnUtcProperty.IsNullable);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the database context.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
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="TrackContributorConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackContributorConfigurationTests : IDisposable
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TrackContributorConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public TrackContributorConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("TrackContributors", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(TrackContributorEntity.Id));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty trackIdProperty = entityType.GetProperty(nameof(TrackContributorEntity.TrackId));
|
||||
IProperty mediaContributorIdProperty = entityType.GetProperty(nameof(TrackContributorEntity.MediaContributorId));
|
||||
IProperty roleProperty = entityType.GetProperty(nameof(TrackContributorEntity.Role));
|
||||
|
||||
// Assert
|
||||
Assert.False(trackIdProperty.IsNullable);
|
||||
Assert.False(mediaContributorIdProperty.IsNullable);
|
||||
Assert.False(roleProperty.IsNullable);
|
||||
Assert.Equal(typeof(MediaContributorRole), roleProperty.ClrType);
|
||||
Assert.Equal("TEXT", roleProperty.GetColumnType());
|
||||
Assert.Equal(50, roleProperty.GetMaxLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureUniqueIndexAndContributorLookupIndex()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
|
||||
|
||||
// Act
|
||||
List<IIndex> indexes = [.. entityType.GetIndexes()];
|
||||
|
||||
// Assert
|
||||
IIndex uniquenessIndex = Assert.Single(indexes.Where(index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackContributorEntity.TrackId), nameof(TrackContributorEntity.MediaContributorId), nameof(TrackContributorEntity.Role)])));
|
||||
Assert.True(uniquenessIndex.IsUnique);
|
||||
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackContributorEntity.MediaContributorId)]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(TrackContributorEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(TrackContributorEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(TrackContributorEntity.UpdatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
Assert.True(updatedOnUtcProperty.IsNullable);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the database context.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
}
|
||||
+825
@@ -0,0 +1,825 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
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 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="TrackRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly TrackRepository _sut;
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new();
|
||||
private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new();
|
||||
private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new();
|
||||
private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TrackRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public TrackRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new TrackRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenTrackDoesNotExist_ShouldAddTrackToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity track = _trackEntityFixture.Create(includeMetadata: false);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(track, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<TrackEntity>? addedTrack = _mockContext.ChangeTracker.Entries<TrackEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == track.Id);
|
||||
Assert.NotNull(addedTrack);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenTrackWithTheSameIdAlreadyExists_ShouldReturnTrackAlreadyExists()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity existingTrack = _trackEntityFixture.Create(includeMetadata: false);
|
||||
_mockContext.Tracks.Add(existingTrack);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
TrackEntity track = _trackEntityFixture.Create(id: existingTrack.Id, includeMetadata: false);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(track, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<TrackEntity>()); // Only the existing track should remain tracked.
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAnotherTrackOfTheSameLibraryHasTheSamePath_ShouldReturnTrackAlreadyExists()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
TrackEntity existingTrack = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false);
|
||||
_mockContext.Tracks.Add(existingTrack);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
TrackEntity track = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(track, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldAddTrackToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity existingTrack = _trackEntityFixture.Create(path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false);
|
||||
_mockContext.Tracks.Add(existingTrack);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
TrackEntity track = _trackEntityFixture.Create(libraryId: Guid.NewGuid(), path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(track, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
// The same physical path is only unique within its library, so the second library is allowed to register it.
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<TrackEntity>(), entry => entry.State == EntityState.Added);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenExistingTagsAreFoundByName_ShouldReplaceThemWithTheStoredInstances()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity existingTag = _tagEntityFixture.Create(name: "Existing");
|
||||
_mockContext.Set<TagEntity>().Add(existingTag);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
TrackEntity track = _trackEntityFixture.Create(includeMetadata: false);
|
||||
track.Tags = [_tagEntityFixture.Create(name: "Existing"), _tagEntityFixture.Create(name: "New")];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(track, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<TrackEntity>? addedTrack = _mockContext.ChangeTracker.Entries<TrackEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == track.Id);
|
||||
Assert.NotNull(addedTrack);
|
||||
TrackEntity addedTrackEntity = addedTrack!.Entity;
|
||||
Assert.Equal(2, addedTrackEntity.Tags.Count);
|
||||
Assert.Contains(addedTrackEntity.Tags, tag => tag.Name == "Existing" && ReferenceEquals(tag, existingTag));
|
||||
Assert.Contains(addedTrackEntity.Tags, tag => tag.Name == "New" && !ReferenceEquals(tag, existingTag));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenExistingGenresAreFoundByName_ShouldReplaceThemWithTheStoredInstances()
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity existingGenre = _genreEntityFixture.Create(name: "Existing");
|
||||
_mockContext.Set<GenreEntity>().Add(existingGenre);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
TrackEntity track = _trackEntityFixture.Create(includeMetadata: false);
|
||||
track.Genres = [_genreEntityFixture.Create(name: "Existing"), _genreEntityFixture.Create(name: "New")];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(track, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<TrackEntity>? addedTrack = _mockContext.ChangeTracker.Entries<TrackEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == track.Id);
|
||||
Assert.NotNull(addedTrack);
|
||||
TrackEntity addedTrackEntity = addedTrack!.Entity;
|
||||
Assert.Equal(2, addedTrackEntity.Genres.Count);
|
||||
Assert.Contains(addedTrackEntity.Genres, genre => genre.Name == "Existing" && ReferenceEquals(genre, existingGenre));
|
||||
Assert.Contains(addedTrackEntity.Genres, genre => genre.Name == "New" && !ReferenceEquals(genre, existingGenre));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenTrackHasNoTagsOrGenres_ShouldStillAddTrackAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity track = _trackEntityFixture.Create(includeMetadata: false);
|
||||
track.Tags = [];
|
||||
track.Genres = [];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(track, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<TrackEntity>? addedTrack = _mockContext.ChangeTracker.Entries<TrackEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == track.Id);
|
||||
Assert.NotNull(addedTrack);
|
||||
Assert.Empty(addedTrack!.Entity.Tags);
|
||||
Assert.Empty(addedTrack.Entity.Genres);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetExistingPathsAsync_WhenPathsIsEmpty_ShouldReturnAnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
IReadOnlyCollection<string> paths = [];
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(Guid.NewGuid(), paths, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetExistingPathsAsync_WhenCalled_ShouldReturnOnlyThePathsUsedByTracksOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
TrackEntity trackOfLibrary = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/love-of-my-life.flac", includeMetadata: false);
|
||||
TrackEntity trackOfAnotherLibrary = _trackEntityFixture.Create(libraryId: Guid.NewGuid(), path: "/music/queen/we-will-rock-you.flac", includeMetadata: false);
|
||||
_mockContext.Tracks.AddRange(trackOfLibrary, trackOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(libraryId, ["/music/queen/love-of-my-life.flac", "/music/queen/we-will-rock-you.flac"], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
string existingPath = Assert.Single(result.Value);
|
||||
Assert.Equal("/music/queen/love-of-my-life.flac", existingPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetExistingPathsAsync_WhenInputContainsDuplicatePaths_ShouldDeDuplicateTheResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/love-of-my-life.flac", includeMetadata: false);
|
||||
_mockContext.Tracks.Add(track);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(libraryId, ["/music/queen/love-of-my-life.flac", "/music/queen/love-of-my-life.flac", "/music/queen/love-of-my-life.flac"], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
Assert.Equal("/music/queen/love-of-my-life.flac", result.Value.First());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetExistingPathsAsync_WhenPathDiffersOnlyByCase_ShouldNotReportItAsExisting()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(libraryId: libraryId, path: "/Music/Queen/Love-Of-My-Life.flac", includeMetadata: false);
|
||||
_mockContext.Tracks.Add(track);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(libraryId, ["/music/queen/love-of-my-life.flac"], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenTrackExists_ShouldUpdateItsScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false);
|
||||
_mockContext.Tracks.Add(storedTrack);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false);
|
||||
data.Title = "Somebody to Love";
|
||||
data.TrackNumber = 7;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
TrackEntity? retrievedTrack = await _mockContext.Tracks.FindAsync(storedTrack.Id);
|
||||
Assert.NotNull(retrievedTrack);
|
||||
Assert.Equal("Somebody to Love", retrievedTrack!.Title);
|
||||
Assert.Equal(7, retrievedTrack.TrackNumber);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenTrackDoesNotExist_ShouldReturnTrackNotFound()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity data = _trackEntityFixture.Create(includeMetadata: false);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenIncomingIdentityColumnsDiffer_ShouldPreserveTheStoredIdentity()
|
||||
{
|
||||
// Arrange
|
||||
Guid storedAlbumId = Guid.NewGuid();
|
||||
Guid storedLibraryId = Guid.NewGuid();
|
||||
TrackEntity storedTrack = _trackEntityFixture.Create(albumId: storedAlbumId, libraryId: storedLibraryId, includeMetadata: false);
|
||||
_mockContext.Tracks.Add(storedTrack);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false);
|
||||
data.AlbumId = Guid.NewGuid();
|
||||
data.LibraryId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackEntity? retrievedTrack = await _mockContext.Tracks.FindAsync(storedTrack.Id);
|
||||
Assert.NotNull(retrievedTrack);
|
||||
Assert.Equal(storedAlbumId, retrievedTrack!.AlbumId);
|
||||
Assert.Equal(storedLibraryId, retrievedTrack.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenIncomingAuditColumnsDiffer_ShouldPreserveTheStoredAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
Guid storedCreatedBy = Guid.NewGuid();
|
||||
TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false);
|
||||
storedTrack.CreatedOnUtc = storedCreatedOnUtc;
|
||||
storedTrack.CreatedBy = storedCreatedBy;
|
||||
storedTrack.UpdatedOnUtc = null;
|
||||
storedTrack.UpdatedBy = null;
|
||||
_mockContext.Tracks.Add(storedTrack);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false);
|
||||
data.Title = "Don't Stop Me Now";
|
||||
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);
|
||||
TrackEntity? retrievedTrack = await _mockContext.Tracks.FindAsync(storedTrack.Id);
|
||||
Assert.NotNull(retrievedTrack);
|
||||
Assert.Equal("Don't Stop Me Now", retrievedTrack!.Title);
|
||||
// The audit columns are owned by the auditing interceptor alone, so an edit never overwrites them.
|
||||
Assert.Equal(storedCreatedOnUtc, retrievedTrack.CreatedOnUtc);
|
||||
Assert.Equal(storedCreatedBy, retrievedTrack.CreatedBy);
|
||||
Assert.Null(retrievedTrack.UpdatedOnUtc);
|
||||
Assert.Null(retrievedTrack.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAnUnchangedContributorIsSubmitted_ShouldPreserveItsStoredIdentityAndAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
Guid keptMediaContributorId = Guid.NewGuid();
|
||||
TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false);
|
||||
TrackContributorEntity keptContributor = _trackContributorEntityFixture.Create(
|
||||
trackId: storedTrack.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer);
|
||||
storedTrack.Contributors = [keptContributor];
|
||||
_mockContext.Tracks.Add(storedTrack);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
Guid keptContributorId = keptContributor.Id;
|
||||
DateTime keptContributorCreatedOnUtc = keptContributor.CreatedOnUtc;
|
||||
|
||||
TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false);
|
||||
data.Contributors =
|
||||
[_trackContributorEntityFixture.Create(trackId: storedTrack.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer)];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackContributorEntity storedContributor = Assert.Single(
|
||||
await _mockContext.Set<TrackContributorEntity>().Where(contributor => contributor.TrackId == storedTrack.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();
|
||||
TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false);
|
||||
TrackContributorEntity keptContributor = _trackContributorEntityFixture.Create(
|
||||
trackId: storedTrack.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer);
|
||||
TrackContributorEntity removedContributor = _trackContributorEntityFixture.Create(
|
||||
trackId: storedTrack.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Producer);
|
||||
storedTrack.Contributors = [keptContributor, removedContributor];
|
||||
_mockContext.Tracks.Add(storedTrack);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
Guid keptContributorId = keptContributor.Id;
|
||||
|
||||
TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false);
|
||||
data.Contributors =
|
||||
[
|
||||
_trackContributorEntityFixture.Create(trackId: storedTrack.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer),
|
||||
_trackContributorEntityFixture.Create(trackId: storedTrack.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<TrackContributorEntity> storedContributors = await _mockContext.Set<TrackContributorEntity>()
|
||||
.Where(contributor => contributor.TrackId == storedTrack.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_WhenRatingsChange_ShouldReplaceTheChangedAddTheNewAndRemoveTheMissingOnes()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false);
|
||||
storedTrack.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.Tracks.Add(storedTrack);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, 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);
|
||||
TrackEntity? retrievedTrack = await _mockContext.Tracks.Include(track => track.Ratings).FirstOrDefaultAsync(track => track.Id == storedTrack.Id);
|
||||
Assert.NotNull(retrievedTrack);
|
||||
List<AudioRatingEntity> ratings = retrievedTrack!.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_WhenTagsAndGenresAlreadyExistByName_ShouldReuseTheStoredRows()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity existingTag = _tagEntityFixture.Create(name: "ExistingTag");
|
||||
GenreEntity existingGenre = _genreEntityFixture.Create(name: "ExistingGenre");
|
||||
TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false);
|
||||
storedTrack.Tags = [existingTag];
|
||||
storedTrack.Genres = [existingGenre];
|
||||
_mockContext.Tracks.Add(storedTrack);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, 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);
|
||||
TrackEntity? retrievedTrack = await _mockContext.Tracks
|
||||
.Include(track => track.Tags)
|
||||
.Include(track => track.Genres)
|
||||
.FirstOrDefaultAsync(track => track.Id == storedTrack.Id);
|
||||
Assert.NotNull(retrievedTrack);
|
||||
TagEntity retrievedTag = Assert.Single(retrievedTrack!.Tags);
|
||||
GenreEntity retrievedGenre = Assert.Single(retrievedTrack.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 UpdateAsync_WhenMoodsAndIsrcsAreUnchanged_ShouldNotDuplicateThem()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false);
|
||||
storedTrack.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Energetic")];
|
||||
storedTrack.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")];
|
||||
_mockContext.Tracks.Add(storedTrack);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false);
|
||||
data.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")];
|
||||
data.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000002")];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackEntity? retrievedTrack = await _mockContext.Tracks
|
||||
.Include(track => track.Moods)
|
||||
.Include(track => track.Isrcs)
|
||||
.FirstOrDefaultAsync(track => track.Id == storedTrack.Id);
|
||||
Assert.NotNull(retrievedTrack);
|
||||
Assert.Equal(2, retrievedTrack!.Moods.Count);
|
||||
Assert.Single(retrievedTrack.Moods, mood => mood.Name == "Calm");
|
||||
Assert.Contains(retrievedTrack.Moods, mood => mood.Name == "Upbeat");
|
||||
Assert.Equal(2, retrievedTrack.Isrcs.Count);
|
||||
Assert.Single(retrievedTrack.Isrcs, isrc => isrc.Value == "USRC12345678");
|
||||
Assert.Contains(retrievedTrack.Isrcs, isrc => isrc.Value == "GBAYE0000002");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenTrackExists_ShouldReturnTheTrack()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity track = _trackEntityFixture.Create(includeMetadata: false);
|
||||
_mockContext.Tracks.Add(track);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<TrackEntity?> result = await _sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(track.Id, result.Value!.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenTrackDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<TrackEntity?> 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 = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
|
||||
track.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")];
|
||||
track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")];
|
||||
track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")];
|
||||
track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
|
||||
track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
|
||||
_mockContext.Artists.Add(artist);
|
||||
_mockContext.Albums.Add(album);
|
||||
_mockContext.Tracks.Add(track);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<TrackEntity?> result = await _sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackEntity retrievedTrack = result.Value!;
|
||||
Assert.NotNull(retrievedTrack.Album);
|
||||
Assert.NotNull(retrievedTrack.Album!.Artist);
|
||||
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.Ratings);
|
||||
Assert.Single(retrievedTrack.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnAnUntrackedTrack()
|
||||
{
|
||||
// Arrange
|
||||
// The EntityFrameworkCore.Testing mocked context does not honour AsNoTracking, because its mocked DbSet returns the already tracked instances,
|
||||
// so a real in-memory provider context is used for this contract, which is a query provider feature rather than repository logic.
|
||||
// The navigation properties are not requested here, because the include path uses AsSplitQuery, which the in-memory provider does not support;
|
||||
// the include path is covered by the mocked context tests and by the integration tests.
|
||||
DbContextOptions<LuminaDbContext> options = new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseInMemoryDatabase($"TrackRepositoryTests-NoTracking-{Guid.NewGuid()}")
|
||||
.Options;
|
||||
using (LuminaDbContext context = new(options))
|
||||
{
|
||||
TrackRepository sut = new(context);
|
||||
TrackEntity track = _trackEntityFixture.Create(includeMetadata: false);
|
||||
context.Tracks.Add(track);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<TrackEntity?> result = await sut.GetByIdAsync(
|
||||
track.Id, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(context.ChangeTracker.Entries<TrackEntity>());
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByAlbumIdAsync_WhenCalled_ShouldReturnOnlyTheAlbumTracksOrderedByDiscThenTrackThenId()
|
||||
{
|
||||
// Arrange
|
||||
Guid albumId = Guid.NewGuid();
|
||||
TrackEntity secondDiscTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/dont-stop-me-now.flac", trackNumber: 1, includeMetadata: false);
|
||||
secondDiscTrack.DiscNumber = 2;
|
||||
TrackEntity firstDiscSecondTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/somebody-to-love.flac", trackNumber: 2, includeMetadata: false);
|
||||
firstDiscSecondTrack.DiscNumber = 1;
|
||||
TrackEntity firstDiscFirstTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/killer-queen.flac", trackNumber: 1, includeMetadata: false);
|
||||
firstDiscFirstTrack.DiscNumber = 1;
|
||||
TrackEntity firstDiscFirstTieTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/seven-seas-of-rhye.flac", trackNumber: 1, includeMetadata: false);
|
||||
firstDiscFirstTieTrack.DiscNumber = 1;
|
||||
TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(path: "/music/queen/under-pressure.flac", includeMetadata: false);
|
||||
_mockContext.Tracks.AddRange(secondDiscTrack, firstDiscSecondTrack, firstDiscFirstTrack, firstDiscFirstTieTrack, trackOfAnotherAlbum);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
List<TrackEntity> albumTracks = [firstDiscFirstTrack, firstDiscFirstTieTrack, firstDiscSecondTrack, secondDiscTrack];
|
||||
Guid[] expectedOrder = [.. albumTracks
|
||||
.OrderBy(track => track.DiscNumber)
|
||||
.ThenBy(track => track.TrackNumber)
|
||||
.ThenBy(track => track.Id)
|
||||
.Select(track => track.Id)];
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackEntity>> result = await _sut.GetByAlbumIdAsync(albumId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedOrder, result.Value.Select(track => track.Id));
|
||||
Assert.DoesNotContain(result.Value, track => track.Id == trackOfAnotherAlbum.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByAlbumIdAsync_WhenCalled_ShouldIncludeTheRelatedCollections()
|
||||
{
|
||||
// Arrange
|
||||
Guid albumId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/radio-ga-ga.flac", includeMetadata: false);
|
||||
track.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")];
|
||||
track.Moods = [_trackMoodEntityFixture.Create(name: "Calm")];
|
||||
track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")];
|
||||
track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
|
||||
track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
|
||||
_mockContext.Tracks.Add(track);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackEntity>> result = await _sut.GetByAlbumIdAsync(albumId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackEntity retrievedTrack = Assert.Single(result.Value);
|
||||
Assert.Equal(2, retrievedTrack.Tags.Count);
|
||||
Assert.Equal(2, retrievedTrack.Genres.Count);
|
||||
Assert.Single(retrievedTrack.Moods);
|
||||
Assert.Single(retrievedTrack.Isrcs);
|
||||
Assert.Single(retrievedTrack.Ratings);
|
||||
Assert.Single(retrievedTrack.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTracksLiteByAlbumIdAsync_WhenPaginationDataIsNull_ShouldReturnAllTracksOfTheAlbumOrdered()
|
||||
{
|
||||
// Arrange
|
||||
Guid albumId = Guid.NewGuid();
|
||||
TrackEntity secondTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/we-are-the-champions.flac", trackNumber: 2, title: "We Are the Champions", includeMetadata: false);
|
||||
secondTrack.DiscNumber = 1;
|
||||
TrackEntity firstTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/i-want-to-break-free.flac", trackNumber: 1, title: "Bohemian Rhapsody", includeMetadata: false);
|
||||
firstTrack.DiscNumber = 1;
|
||||
TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(path: "/music/queen/a-kind-of-magic.flac", includeMetadata: false);
|
||||
_mockContext.Tracks.AddRange(secondTrack, firstTrack, trackOfAnotherAlbum);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<TrackLiteRow>> result = await _sut.GetTracksLiteByAlbumIdAsync(albumId, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
PaginatedResultDto<TrackLiteRow> 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([firstTrack.Id, secondTrack.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 GetTracksLiteByAlbumIdAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage(int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount)
|
||||
{
|
||||
// Arrange
|
||||
Guid albumId = Guid.NewGuid();
|
||||
List<TrackEntity> tracks = _trackEntityFixture.CreateMany(5);
|
||||
for (int index = 0; index < tracks.Count; index++)
|
||||
{
|
||||
tracks[index].AlbumId = albumId;
|
||||
tracks[index].DiscNumber = 1;
|
||||
tracks[index].TrackNumber = index + 1;
|
||||
tracks[index].Path = $"/music/queen/track-{index}.flac";
|
||||
tracks[index].Tags = [];
|
||||
tracks[index].Genres = [];
|
||||
tracks[index].Moods = [];
|
||||
tracks[index].Isrcs = [];
|
||||
tracks[index].Contributors = [];
|
||||
tracks[index].Ratings = [];
|
||||
}
|
||||
_mockContext.Tracks.AddRange(tracks);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<TrackLiteRow>> result = await _sut.GetTracksLiteByAlbumIdAsync(albumId, paginationData, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
PaginatedResultDto<TrackLiteRow> 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 GetTracksLiteByAlbumIdAsync_WhenCalled_ShouldReturnOnlyTheTracksOfTheRequestedAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid albumId = Guid.NewGuid();
|
||||
TrackEntity trackOfAlbum = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/youre-my-best-friend.flac", includeMetadata: false);
|
||||
TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(path: "/music/queen/fat-bottomed-girls.flac", includeMetadata: false);
|
||||
_mockContext.Tracks.AddRange(trackOfAlbum, trackOfAnotherAlbum);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<TrackLiteRow>> result = await _sut.GetTracksLiteByAlbumIdAsync(albumId, paginationData, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackLiteRow row = Assert.Single(result.Value.Data);
|
||||
Assert.Equal(trackOfAlbum.Id, row.Id);
|
||||
Assert.Equal(1, result.Value.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTracksLiteByAlbumIdAsync_WhenCalled_ShouldProjectTheLiteFields()
|
||||
{
|
||||
// Arrange
|
||||
Guid albumId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/bicycle-race.flac", title: "Killer Queen", trackNumber: 9, includeMetadata: false);
|
||||
track.DiscNumber = 3;
|
||||
_mockContext.Tracks.Add(track);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<TrackLiteRow>> result = await _sut.GetTracksLiteByAlbumIdAsync(albumId, paginationData, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackLiteRow row = Assert.Single(result.Value.Data);
|
||||
Assert.Equal(track.Id, row.Id);
|
||||
Assert.Equal("Killer Queen", row.Title);
|
||||
Assert.Equal(9, row.TrackNumber);
|
||||
Assert.Equal(3, row.DiscNumber);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Mood"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MoodTests
|
||||
{
|
||||
private readonly MoodFixture _moodFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithUntrimmedName_ShouldTrimTheName()
|
||||
{
|
||||
// Act
|
||||
Result<Mood> result = Mood.Create(" calm ");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("calm", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // null mood name
|
||||
[InlineData("")] // empty mood name
|
||||
[InlineData(" ")] // whitespace mood name
|
||||
public void Create_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name)
|
||||
{
|
||||
// Act
|
||||
Result<Mood> result = Mood.Create(name!);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Metadata.MoodNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToString_WhenCalled_ShouldReturnName()
|
||||
{
|
||||
// Arrange
|
||||
Mood mood = _moodFixture.Create(name: "energetic");
|
||||
|
||||
// Act
|
||||
string result = mood.ToString();
|
||||
|
||||
// Assert
|
||||
Assert.Equal("energetic", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameName_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Mood firstMood = _moodFixture.Create(name: "calm");
|
||||
Mood secondMood = _moodFixture.Create(name: "calm");
|
||||
|
||||
// Act
|
||||
bool result = firstMood.Equals(secondMood);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentName_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Mood firstMood = _moodFixture.Create(name: "calm");
|
||||
Mood secondMood = _moodFixture.Create(name: "energetic");
|
||||
|
||||
// Act
|
||||
bool result = firstMood.Equals(secondMood);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+9
-9
@@ -27,13 +27,13 @@ public class AudioMetadataTests
|
||||
{
|
||||
// Act
|
||||
Result<AudioMetadata> result = AudioMetadata.Create(
|
||||
"Abbey Road",
|
||||
"Bohemian Rhapsody",
|
||||
Optional<string>.None(),
|
||||
durationInSeconds: 2826,
|
||||
sampleRate: 44100,
|
||||
channels: 2,
|
||||
_releaseInfoFixture.Create(),
|
||||
Optional<string>.Some("The last recorded album by the Beatles."),
|
||||
Optional<string>.Some("A song by the British rock band Queen."),
|
||||
[_genreFixture.Create(name: "Rock")],
|
||||
[_tagFixture.Create(name: "classic")],
|
||||
Optional<LanguageInfo>.None(),
|
||||
@@ -44,11 +44,11 @@ public class AudioMetadataTests
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Abbey Road", result.Value.Title);
|
||||
Assert.Equal("Bohemian Rhapsody", result.Value.Title);
|
||||
Assert.Equal(2826, result.Value.DurationInSeconds);
|
||||
Assert.Equal(44100, result.Value.SampleRate);
|
||||
Assert.Equal(2, result.Value.Channels);
|
||||
Assert.Equal("The last recorded album by the Beatles.", result.Value.Description.Value);
|
||||
Assert.Equal("A song by the British rock band Queen.", result.Value.Description.Value);
|
||||
Assert.Equal(16, result.Value.BitDepth.Value);
|
||||
Assert.Equal("PCM", result.Value.AudioCodec.Value);
|
||||
Assert.Equal(1411, result.Value.Bitrate.Value);
|
||||
@@ -61,7 +61,7 @@ public class AudioMetadataTests
|
||||
{
|
||||
// Act
|
||||
Result<AudioMetadata> result = AudioMetadata.Create(
|
||||
"Abbey Road",
|
||||
"Bohemian Rhapsody",
|
||||
Optional<string>.None(),
|
||||
durationInSeconds: 2826,
|
||||
sampleRate: 44100,
|
||||
@@ -91,7 +91,7 @@ public class AudioMetadataTests
|
||||
|
||||
// Act
|
||||
AudioMetadata firstResult = _audioMetadataFixture.Create(
|
||||
title: "Abbey Road",
|
||||
title: "Bohemian Rhapsody",
|
||||
originalTitle: Optional<string>.None(),
|
||||
durationInSeconds: 2826,
|
||||
sampleRate: 44100,
|
||||
@@ -106,7 +106,7 @@ public class AudioMetadataTests
|
||||
audioCodec: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
AudioMetadata secondResult = _audioMetadataFixture.Create(
|
||||
title: "Abbey Road",
|
||||
title: "Bohemian Rhapsody",
|
||||
originalTitle: Optional<string>.None(),
|
||||
durationInSeconds: 2826,
|
||||
sampleRate: 44100,
|
||||
@@ -133,7 +133,7 @@ public class AudioMetadataTests
|
||||
|
||||
// Act
|
||||
AudioMetadata firstResult = _audioMetadataFixture.Create(
|
||||
title: "Abbey Road",
|
||||
title: "Bohemian Rhapsody",
|
||||
originalTitle: Optional<string>.None(),
|
||||
durationInSeconds: 2826,
|
||||
sampleRate: 44100,
|
||||
@@ -148,7 +148,7 @@ public class AudioMetadataTests
|
||||
audioCodec: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
AudioMetadata secondResult = _audioMetadataFixture.Create(
|
||||
title: "Abbey Road",
|
||||
title: "Bohemian Rhapsody",
|
||||
originalTitle: Optional<string>.None(),
|
||||
durationInSeconds: 2826,
|
||||
sampleRate: 48000,
|
||||
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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 Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Artist"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ArtistTests
|
||||
{
|
||||
private readonly ArtistFixture _artistFixture = new();
|
||||
private readonly AlbumFixture _albumFixture = new();
|
||||
private readonly TrackFixture _trackFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void AddTrackToAlbum_WhenAlbumIsOwnedByTheArtist_ShouldAddTheTrackAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(tracks: []);
|
||||
Artist artist = _artistFixture.Create(albums: [album]);
|
||||
Track track = _trackFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = artist.AddTrackToAlbum(album, track);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Track storedTrack = Assert.Single(album.Tracks);
|
||||
Assert.Equal(track, storedTrack);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddTrackToAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
Album ownedAlbum = _albumFixture.Create(tracks: []);
|
||||
Album foreignAlbum = _albumFixture.Create(tracks: []);
|
||||
Artist artist = _artistFixture.Create(albums: [ownedAlbum]);
|
||||
Track track = _trackFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = artist.AddTrackToAlbum(foreignAlbum, track);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
Assert.Empty(foreignAlbum.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddTrackToAlbum_WhenTrackIsAlreadyInTheAlbum_ShouldPropagateTheTrackIsAlreadyInTheAlbumError()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(tracks: []);
|
||||
Artist artist = _artistFixture.Create(albums: [album]);
|
||||
Track track = _trackFixture.Create();
|
||||
artist.AddTrackToAlbum(album, track);
|
||||
|
||||
// Act
|
||||
Result<Created> result = artist.AddTrackToAlbum(album, track);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TheTrackIsAlreadyInTheAlbum, result.FirstError);
|
||||
Assert.Single(album.Tracks);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Album"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumTests
|
||||
{
|
||||
private readonly AlbumFixture _albumFixture = new();
|
||||
private readonly TrackFixture _trackFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void AddTrack_WhenTrackIsNotInTheAlbum_ShouldAddTheTrackAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(tracks: []);
|
||||
Track track = _trackFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = album.AddTrack(track);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Track storedTrack = Assert.Single(album.Tracks);
|
||||
Assert.Equal(track, storedTrack);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddTrack_WhenTrackIsAlreadyInTheAlbum_ShouldReturnTheTrackIsAlreadyInTheAlbumErrorAndNotAddDuplicate()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(tracks: []);
|
||||
Track track = _trackFixture.Create();
|
||||
album.AddTrack(track);
|
||||
|
||||
// Act
|
||||
Result<Created> result = album.AddTrack(track);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TheTrackIsAlreadyInTheAlbum, result.FirstError);
|
||||
Assert.Single(album.Tracks);
|
||||
}
|
||||
}
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Track"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackTests
|
||||
{
|
||||
private readonly TrackFixture _trackFixture = new();
|
||||
private readonly MoodFixture _moodFixture = new();
|
||||
private readonly IsrcFixture _isrcFixture = new();
|
||||
private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new();
|
||||
private readonly AudioRatingFixture _audioRatingFixture = new();
|
||||
private readonly AudioMetadataFixture _audioMetadataFixture = new();
|
||||
private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidData_ShouldCreateTrackWithAllPropertiesPopulated()
|
||||
{
|
||||
// Act
|
||||
Track track = _trackFixture.Create();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(track);
|
||||
Assert.NotNull(track.Id);
|
||||
Assert.NotEqual(Guid.Empty, track.Id.Value);
|
||||
Assert.False(string.IsNullOrWhiteSpace(track.Path));
|
||||
Assert.NotNull(track.Metadata);
|
||||
Assert.True(track.TrackNumber > 0);
|
||||
Assert.True(track.DiscNumber.HasValue);
|
||||
Assert.NotEmpty(track.Moods);
|
||||
Assert.True(track.Script.HasValue);
|
||||
Assert.True(track.Key.HasValue);
|
||||
Assert.True(track.Bpm.HasValue);
|
||||
Assert.NotEmpty(track.Isrcs);
|
||||
Assert.True(track.Work.HasValue);
|
||||
Assert.True(track.MusicBrainzRecordingId.HasValue);
|
||||
Assert.True(track.MusicBrainzTrackId.HasValue);
|
||||
Assert.True(track.MusicBrainzWorkId.HasValue);
|
||||
Assert.NotEmpty(track.Contributors);
|
||||
Assert.NotEmpty(track.Ratings);
|
||||
Assert.True(track.CreatedOnUtc > DateTime.MinValue);
|
||||
Assert.False(track.UpdatedOnUtc.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithPreExistingIdAndTimestamps_ShouldPreserveIdentityAndTimestamps()
|
||||
{
|
||||
// Arrange
|
||||
Track sourceTrack = _trackFixture.Create();
|
||||
DateTime createdOnUtc = DateTime.UtcNow.AddDays(-1);
|
||||
DateTime updatedOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Track> result = Track.Create(
|
||||
sourceTrack.Id,
|
||||
sourceTrack.Path,
|
||||
sourceTrack.Metadata,
|
||||
sourceTrack.TrackNumber,
|
||||
sourceTrack.DiscNumber,
|
||||
[.. sourceTrack.Moods],
|
||||
sourceTrack.Script,
|
||||
sourceTrack.Key,
|
||||
sourceTrack.Bpm,
|
||||
[.. sourceTrack.Isrcs],
|
||||
sourceTrack.Work,
|
||||
sourceTrack.MusicBrainzRecordingId,
|
||||
sourceTrack.MusicBrainzTrackId,
|
||||
sourceTrack.MusicBrainzWorkId,
|
||||
[.. sourceTrack.Contributors],
|
||||
[.. sourceTrack.Ratings],
|
||||
createdOnUtc,
|
||||
Optional<DateTime>.Some(updatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Track track = result.Value;
|
||||
Assert.Equal(sourceTrack.Id, track.Id);
|
||||
Assert.Equal(sourceTrack.Path, track.Path);
|
||||
Assert.Equal(sourceTrack.Metadata, track.Metadata);
|
||||
Assert.Equal(sourceTrack.TrackNumber, track.TrackNumber);
|
||||
Assert.Equal(sourceTrack.DiscNumber, track.DiscNumber);
|
||||
Assert.Equal(sourceTrack.Moods, track.Moods);
|
||||
Assert.Equal(sourceTrack.Isrcs, track.Isrcs);
|
||||
Assert.Equal(sourceTrack.Contributors, track.Contributors);
|
||||
Assert.Equal(sourceTrack.Ratings, track.Ratings);
|
||||
Assert.Equal(createdOnUtc, track.CreatedOnUtc);
|
||||
Assert.Equal(Optional<DateTime>.Some(updatedOnUtc), track.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateMoods_WhenCalledTwice_ShouldReplaceTheMoodsInsteadOfAppending()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create(moods: []);
|
||||
Mood firstMood = _moodFixture.Create(name: "calm");
|
||||
Mood secondMood = _moodFixture.Create(name: "energetic");
|
||||
track.UpdateMoods([firstMood, _moodFixture.Create(name: "melancholic")]);
|
||||
|
||||
// Act
|
||||
track.UpdateMoods([secondMood]);
|
||||
|
||||
// Assert
|
||||
// the second call replaces the first set, it is not appended to it
|
||||
Mood storedMood = Assert.Single(track.Moods);
|
||||
Assert.Equal(secondMood, storedMood);
|
||||
Assert.DoesNotContain(firstMood, track.Moods);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateIsrcs_WhenCalledTwice_ShouldReplaceTheIsrcsInsteadOfAppending()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create(isrcs: []);
|
||||
Isrc firstIsrc = _isrcFixture.Create(value: "USRC17607839");
|
||||
Isrc secondIsrc = _isrcFixture.Create(value: "GBAYE0000001");
|
||||
track.UpdateIsrcs([firstIsrc, _isrcFixture.Create(value: "FRUM71400001")]);
|
||||
|
||||
// Act
|
||||
track.UpdateIsrcs([secondIsrc]);
|
||||
|
||||
// Assert
|
||||
// the second call replaces the first set, it is not appended to it
|
||||
Isrc storedIsrc = Assert.Single(track.Isrcs);
|
||||
Assert.Equal(secondIsrc, storedIsrc);
|
||||
Assert.DoesNotContain(firstIsrc, track.Isrcs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateContributors_WhenCalledTwice_ShouldReplaceTheContributorsInsteadOfAppending()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create(contributors: []);
|
||||
MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create();
|
||||
MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create();
|
||||
track.UpdateContributors([firstContributor]);
|
||||
|
||||
// Act
|
||||
track.UpdateContributors([secondContributor]);
|
||||
|
||||
// Assert
|
||||
// the second call replaces the first set, it is not appended to it
|
||||
MusicMediaContributor storedContributor = Assert.Single(track.Contributors);
|
||||
Assert.Equal(secondContributor, storedContributor);
|
||||
Assert.DoesNotContain(firstContributor, track.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateRatings_WhenCalledTwice_ShouldReplaceTheRatingsInsteadOfAppending()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create(ratings: []);
|
||||
AudioRating firstRating = _audioRatingFixture.Create(value: 1m, maxValue: 5m);
|
||||
AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m);
|
||||
track.UpdateRatings([firstRating]);
|
||||
|
||||
// Act
|
||||
track.UpdateRatings([secondRating]);
|
||||
|
||||
// Assert
|
||||
// the second call replaces the first set, it is not appended to it
|
||||
AudioRating storedRating = Assert.Single(track.Ratings);
|
||||
Assert.Equal(secondRating, storedRating);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateDetails_WhenCalled_ShouldUpdateAllDetailPropertiesAndSetUpdatedOnUtc()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create();
|
||||
List<Mood> originalMoods = [.. track.Moods];
|
||||
string path = "C:\\Music\\queen\\bohemian-rhapsody.flac";
|
||||
AudioMetadata metadata = _audioMetadataFixture.Create();
|
||||
Optional<int> discNumber = Optional<int>.Some(2);
|
||||
Optional<string> script = Optional<string>.Some("Latin");
|
||||
Optional<MusicKey> key = Optional<MusicKey>.Some(MusicKey.DMajor);
|
||||
Optional<int> bpm = Optional<int>.Some(128);
|
||||
Optional<string> work = Optional<string>.Some("Symphony No. 5");
|
||||
Optional<MusicBrainzId> recordingId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
Optional<MusicBrainzId> trackId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
Optional<MusicBrainzId> workId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
DateTime beforeUpdate = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = track.UpdateDetails(
|
||||
path,
|
||||
metadata,
|
||||
7,
|
||||
discNumber,
|
||||
script,
|
||||
key,
|
||||
bpm,
|
||||
work,
|
||||
recordingId,
|
||||
trackId,
|
||||
workId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(path, track.Path);
|
||||
Assert.Equal(metadata, track.Metadata);
|
||||
Assert.Equal(7, track.TrackNumber);
|
||||
Assert.Equal(discNumber, track.DiscNumber);
|
||||
Assert.Equal(script, track.Script);
|
||||
Assert.Equal(key, track.Key);
|
||||
Assert.Equal(bpm, track.Bpm);
|
||||
Assert.Equal(work, track.Work);
|
||||
Assert.Equal(recordingId, track.MusicBrainzRecordingId);
|
||||
Assert.Equal(trackId, track.MusicBrainzTrackId);
|
||||
Assert.Equal(workId, track.MusicBrainzWorkId);
|
||||
Assert.True(track.UpdatedOnUtc.HasValue);
|
||||
Assert.True(track.UpdatedOnUtc.Value >= beforeUpdate);
|
||||
// the collections are not part of the details update
|
||||
Assert.Equal(originalMoods, track.Moods);
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Isrc"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsrcTests
|
||||
{
|
||||
private readonly IsrcFixture _isrcFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidIsrc_ShouldCreateIsrc()
|
||||
{
|
||||
// Act
|
||||
Result<Isrc> result = Isrc.Create("USRC17607839");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("USRC17607839", result.Value.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenValueHasLowercaseAndWhitespace_ShouldNormalizeToUppercaseTrimmed()
|
||||
{
|
||||
// Act
|
||||
Result<Isrc> result = Isrc.Create(" usrc17607839 ");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("USRC17607839", result.Value.Value);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // null ISRC value
|
||||
[InlineData("")] // empty ISRC value
|
||||
[InlineData(" ")] // whitespace ISRC value
|
||||
public void Create_WhenValueIsNullOrWhitespace_ShouldReturnError(string? value)
|
||||
{
|
||||
// Act
|
||||
Result<Isrc> result = Isrc.Create(value!);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Music.IsrcValueCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("USRC1760783")] // too short
|
||||
[InlineData("USRC176078399")] // too long
|
||||
[InlineData("1SRC17607839")] // country code does not start with two letters
|
||||
[InlineData("USRC1760783X")] // designation segment is not purely numeric
|
||||
[InlineData("USRC-7607839")] // contains an invalid character
|
||||
public void Create_WhenValueHasInvalidFormat_ShouldReturnError(string value)
|
||||
{
|
||||
// Act
|
||||
Result<Isrc> result = Isrc.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Music.IsrcInvalidFormat, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Isrc firstIsrc = _isrcFixture.Create(value: "USRC17607839");
|
||||
Isrc secondIsrc = _isrcFixture.Create(value: "USRC17607839");
|
||||
|
||||
// Act
|
||||
bool result = firstIsrc.Equals(secondIsrc);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Isrc firstIsrc = _isrcFixture.Create(value: "USRC17607839");
|
||||
Isrc secondIsrc = _isrcFixture.Create(value: "GBAYE0000001");
|
||||
|
||||
// Act
|
||||
bool result = firstIsrc.Equals(secondIsrc);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
#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="MusicBrainzId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzIdTests
|
||||
{
|
||||
private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
MusicBrainzId musicBrainzId = MusicBrainzId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, musicBrainzId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
MusicBrainzId firstId = _musicBrainzIdFixture.Create(value);
|
||||
MusicBrainzId secondId = _musicBrainzIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicBrainzId firstId = _musicBrainzIdFixture.Create();
|
||||
MusicBrainzId secondId = _musicBrainzIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicMediaContributor"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicMediaContributorTests
|
||||
{
|
||||
private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new();
|
||||
private readonly MediaContributorIdFixture _mediaContributorIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalled_ShouldReturnContributorWithContributorIdAndRole()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorId contributorId = _mediaContributorIdFixture.Create();
|
||||
|
||||
// Act
|
||||
MusicMediaContributor contributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Composer);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(contributorId, contributor.ContributorId);
|
||||
Assert.Equal(MediaContributorRole.Composer, contributor.Role);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameContributorIdAndRole_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorId contributorId = _mediaContributorIdFixture.Create();
|
||||
MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Composer);
|
||||
MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Composer);
|
||||
|
||||
// Act
|
||||
bool result = firstContributor.Equals(secondContributor);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentRole_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorId contributorId = _mediaContributorIdFixture.Create();
|
||||
MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Composer);
|
||||
MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Producer);
|
||||
|
||||
// Act
|
||||
bool result = firstContributor.Equals(secondContributor);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentContributorId_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create(contributorId: _mediaContributorIdFixture.Create(), role: MediaContributorRole.Composer);
|
||||
MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create(contributorId: _mediaContributorIdFixture.Create(), role: MediaContributorRole.Composer);
|
||||
|
||||
// Act
|
||||
bool result = firstContributor.Equals(secondContributor);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#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="TrackId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackIdTests
|
||||
{
|
||||
private readonly TrackIdFixture _trackIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
TrackId trackId = TrackId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(trackId);
|
||||
Assert.NotEqual(default, trackId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
TrackId trackId = TrackId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, trackId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
TrackId firstId = _trackIdFixture.Create(value);
|
||||
TrackId secondId = _trackIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
TrackId firstId = _trackIdFixture.Create();
|
||||
TrackId secondId = _trackIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Requests.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.Tracks.AddTrack;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.AddTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddTrackEndpointTests
|
||||
{
|
||||
private readonly Lumina.Application.Common.CQRS.ICommandHandler<AddTrackCommand, Result<TrackResponse>> _mockHandler;
|
||||
private readonly AddTrackEndpoint _sut;
|
||||
private readonly AddTrackRequestFixture _addTrackRequestFixture = new();
|
||||
private readonly TrackResponseFixture _trackResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public AddTrackEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<Lumina.Application.Common.CQRS.ICommandHandler<AddTrackCommand, Result<TrackResponse>>>();
|
||||
_sut = FastEndpoints.Factory.Create<AddTrackEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithLocationAndTrackResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
TrackResponse expectedResponse = _trackResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<AddTrackCommand>(), 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
|
||||
Created<TrackResponse> createdResult = Assert.IsType<Created<TrackResponse>>(result);
|
||||
Assert.Equal(expectedResponse, createdResult.Value);
|
||||
Assert.NotNull(createdResult.Location);
|
||||
Assert.EndsWith($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{expectedResponse.Id}", createdResult.Location);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Music.ArtistNotFound", "ArtistNotFound");
|
||||
_mockHandler.HandleAsync(Arg.Any<AddTrackCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
|
||||
Assert.Equal("Music.ArtistNotFound", 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_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Errors.Library.LibraryIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddTrackCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendAddTrackCommandToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddTrackCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_trackResponseFixture.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<AddTrackCommand>(command =>
|
||||
command.LibraryId == libraryId.ToString() &&
|
||||
command.ArtistId == artistId.ToString() &&
|
||||
command.AlbumId == albumId.ToString() &&
|
||||
command.Path == request.Path &&
|
||||
command.Metadata == request.Metadata &&
|
||||
command.TrackNumber == request.TrackNumber &&
|
||||
command.DiscNumber == request.DiscNumber &&
|
||||
command.Script == request.Script &&
|
||||
command.Key == request.Key &&
|
||||
command.Bpm == request.Bpm &&
|
||||
command.Work == request.Work &&
|
||||
command.MusicBrainzRecordingId == request.MusicBrainzRecordingId &&
|
||||
command.MusicBrainzTrackId == request.MusicBrainzTrackId &&
|
||||
command.MusicBrainzWorkId == request.MusicBrainzWorkId &&
|
||||
command.Moods == request.Moods &&
|
||||
command.Isrcs == request.Isrcs &&
|
||||
command.Contributors == request.Contributors &&
|
||||
command.Ratings == request.Ratings),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddTrackCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_trackResponseFixture.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<AddTrackCommand>(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_ShouldSendCommandWithNullRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddTrackCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_trackResponseFixture.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<AddTrackCommand>(command =>
|
||||
command.LibraryId == null &&
|
||||
command.ArtistId == null &&
|
||||
command.AlbumId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<AddTrackCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_trackResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
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.Tracks.DeleteTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteTrackEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<DeleteTrackCommand, Result<Deleted>> _mockHandler;
|
||||
private readonly DeleteTrackEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteTrackEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<DeleteTrackCommand, Result<Deleted>>>();
|
||||
_sut = FastEndpoints.Factory.Create<DeleteTrackEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteTrackCommand>(), 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.TrackNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteTrackCommand>(), 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);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
|
||||
Assert.Equal("General.NotFound", problemDetailsBody.Title);
|
||||
Assert.Equal("TrackNotFound", 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<DeleteTrackCommand>(), 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);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.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.TrackIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteTrackCommand>(), 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[] { "TrackIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteTrackCommandToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteTrackCommand>(), 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();
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<DeleteTrackCommand>(command =>
|
||||
command.LibraryId == libraryId.ToString() &&
|
||||
command.ArtistId == artistId.ToString() &&
|
||||
command.AlbumId == albumId.ToString() &&
|
||||
command.TrackId == trackId.ToString()),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteTrackCommand>(), 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";
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = "not-a-track-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<DeleteTrackCommand>(command =>
|
||||
command.LibraryId == "not-a-library-guid" &&
|
||||
command.ArtistId == "not-an-artist-guid" &&
|
||||
command.AlbumId == "not-an-album-guid" &&
|
||||
command.TrackId == "not-a-track-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteTrackCommand>(), 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");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("trackId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<DeleteTrackCommand>(command =>
|
||||
command.LibraryId == null &&
|
||||
command.ArtistId == null &&
|
||||
command.AlbumId == null &&
|
||||
command.TrackId == 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<DeleteTrackCommand>(), 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();
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = Guid.NewGuid().ToString();
|
||||
}
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack;
|
||||
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.Tracks.GetTrack;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTrackEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetTrackQuery, Result<TrackResponse>> _mockHandler;
|
||||
private readonly GetTrackEndpoint _sut;
|
||||
private readonly TrackResponseFixture _trackResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetTrackEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetTrackQuery, Result<TrackResponse>>>();
|
||||
_sut = FastEndpoints.Factory.Create<GetTrackEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithTrackResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
TrackResponse expectedResponse = _trackResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetTrackQuery>(), 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();
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<TrackResponse> okResult = Assert.IsType<Ok<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();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Track.NotFound", "TrackNotFound");
|
||||
_mockHandler.HandleAsync(Arg.Any<GetTrackQuery>(), 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();
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId.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);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
|
||||
Assert.Equal("Track.NotFound", problemDetailsBody.Title);
|
||||
Assert.Equal("TrackNotFound", problemDetailsBody.Detail);
|
||||
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();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Errors.Music.TrackIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetTrackQuery>(), 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();
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId.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[] { "TrackIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetTrackQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetTrackQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_trackResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetTrackQuery>(query =>
|
||||
query.LibraryId == libraryId.ToString() &&
|
||||
query.ArtistId == artistId.ToString() &&
|
||||
query.AlbumId == albumId.ToString() &&
|
||||
query.TrackId == trackId.ToString()),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetTrackQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_trackResponseFixture.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";
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = "not-a-track-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetTrackQuery>(query =>
|
||||
query.LibraryId == "not-a-library-guid" &&
|
||||
query.ArtistId == "not-an-artist-guid" &&
|
||||
query.AlbumId == "not-an-album-guid" &&
|
||||
query.TrackId == "not-a-track-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetTrackQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_trackResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("artistId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("albumId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("trackId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetTrackQuery>(query =>
|
||||
query.LibraryId == null &&
|
||||
query.ArtistId == null &&
|
||||
query.AlbumId == null &&
|
||||
query.TrackId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<GetTrackQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_trackResponseFixture.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();
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId.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);
|
||||
}
|
||||
}
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Requests.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.Tracks.UpdateTrack;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.UpdateTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateTrackEndpointTests
|
||||
{
|
||||
private readonly Application.Common.CQRS.ICommandHandler<UpdateTrackCommand, Result<TrackResponse>> _mockHandler;
|
||||
private readonly UpdateTrackEndpoint _sut;
|
||||
private readonly UpdateTrackRequestFixture _updateTrackRequestFixture = new();
|
||||
private readonly TrackResponseFixture _trackResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateTrackEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<Lumina.Application.Common.CQRS.ICommandHandler<UpdateTrackCommand, Result<TrackResponse>>>();
|
||||
_sut = Factory.Create<UpdateTrackEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithTrackResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
TrackResponse expectedResponse = _trackResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateTrackCommand>(), 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();
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<TrackResponse> okResult = Assert.IsType<Ok<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();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Track.NotFound", "TrackNotFound");
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateTrackCommand>(), 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();
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId.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);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
|
||||
Assert.Equal("Track.NotFound", problemDetailsBody.Title);
|
||||
Assert.Equal("TrackNotFound", problemDetailsBody.Detail);
|
||||
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();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Errors.Music.TrackPathCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateTrackCommand>(), 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();
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId.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[] { "TrackPathCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateTrackCommandToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateTrackCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_trackResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateTrackCommand>(command =>
|
||||
command.LibraryId == libraryId.ToString() &&
|
||||
command.ArtistId == artistId.ToString() &&
|
||||
command.AlbumId == albumId.ToString() &&
|
||||
command.TrackId == trackId.ToString() &&
|
||||
command.Path == request.Path &&
|
||||
command.Metadata == request.Metadata &&
|
||||
command.TrackNumber == request.TrackNumber &&
|
||||
command.DiscNumber == request.DiscNumber &&
|
||||
command.Script == request.Script &&
|
||||
command.Key == request.Key &&
|
||||
command.Bpm == request.Bpm &&
|
||||
command.Work == request.Work &&
|
||||
command.MusicBrainzRecordingId == request.MusicBrainzRecordingId &&
|
||||
command.MusicBrainzTrackId == request.MusicBrainzTrackId &&
|
||||
command.MusicBrainzWorkId == request.MusicBrainzWorkId &&
|
||||
command.Moods == request.Moods &&
|
||||
command.Isrcs == request.Isrcs &&
|
||||
command.Contributors == request.Contributors &&
|
||||
command.Ratings == request.Ratings),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateTrackCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_trackResponseFixture.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";
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = "not-a-track-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateTrackCommand>(command =>
|
||||
command.LibraryId == "not-a-library-guid" &&
|
||||
command.ArtistId == "not-an-artist-guid" &&
|
||||
command.AlbumId == "not-an-album-guid" &&
|
||||
command.TrackId == "not-a-track-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
|
||||
{
|
||||
// Arrange
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateTrackCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_trackResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("artistId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("albumId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("trackId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateTrackCommand>(command =>
|
||||
command.LibraryId == null &&
|
||||
command.ArtistId == null &&
|
||||
command.AlbumId == null &&
|
||||
command.TrackId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateTrackCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_trackResponseFixture.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();
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId.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