mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 05:11:10 +00:00
Adds the music library browsing and editing pages to the web client.
This commit is contained in:
1 parent
c7aab63552
commit
5a2c6c2bd8
215 files changed
+60042
-3
No files matched your search
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AudioRatingDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AudioRatingDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="AudioRatingDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The numeric value of the rating.</param>
|
||||
/// <param name="maxValue">Optional. The maximum possible rating value.</param>
|
||||
/// <param name="voteCount">Optional. The number of votes the rating is based on.</param>
|
||||
/// <param name="source">Optional. The source of 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="includeVoteCount">Whether the vote count 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>
|
||||
/// <returns>A configured <see cref="AudioRatingDto"/> instance.</returns>
|
||||
public AudioRatingDto Create(
|
||||
decimal? value = null,
|
||||
decimal? maxValue = null,
|
||||
int? voteCount = null,
|
||||
AudioRatingSource? source = null,
|
||||
bool includeValue = true,
|
||||
bool includeMaxValue = true,
|
||||
bool includeVoteCount = true,
|
||||
bool includeSource = true)
|
||||
{
|
||||
return new AudioRatingDto
|
||||
{
|
||||
Value = includeValue ? (value ?? _faker.Random.Decimal(1, 5)) : null,
|
||||
MaxValue = includeMaxValue ? (maxValue ?? 5) : null,
|
||||
VoteCount = includeVoteCount ? (voteCount ?? _faker.Random.Number(1, 1000)) : null,
|
||||
Source = includeSource ? (source ?? _faker.PickRandom<AudioRatingSource>()) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="AudioRatingDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="AudioRatingDto"/> instances.</returns>
|
||||
public List<AudioRatingDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="IsrcDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsrcDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="IsrcDto"/> instance with randomized test data.
|
||||
/// </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>A configured <see cref="IsrcDto"/> instance.</returns>
|
||||
public IsrcDto Create(
|
||||
string? value = null,
|
||||
bool includeValue = true)
|
||||
{
|
||||
return new IsrcDto
|
||||
{
|
||||
Value = includeValue ? (value ?? $"US{_faker.Random.String2(3, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")}{_faker.Random.Number(10000, 99999)}") : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="IsrcDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="IsrcDto"/> instances.</returns>
|
||||
public List<IsrcDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
|
||||
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicAlbumDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicAlbumDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new();
|
||||
private readonly MediaArtworkDtoFixture _mediaArtworkDtoFixture = new();
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicAlbumDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the album.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the album belongs to.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library this album belongs to.</param>
|
||||
/// <param name="coverPath">Optional. The path of the image representing the album.</param>
|
||||
/// <param name="artwork">Optional. The stored artwork of the album.</param>
|
||||
/// <param name="metadata">Optional. The album metadata of the album.</param>
|
||||
/// <param name="mediaFormat">Optional. The physical or digital medium of the album.</param>
|
||||
/// <param name="packaging">Optional. The outermost physical packaging of the album.</param>
|
||||
/// <param name="barcode">Optional. The barcode of the album.</param>
|
||||
/// <param name="catalogNumbers">Optional. The catalog numbers of the album.</param>
|
||||
/// <param name="label">Optional. The name of the label that issued the album.</param>
|
||||
/// <param name="asin">Optional. The ASIN of the album.</param>
|
||||
/// <param name="musicBrainzReleaseId">Optional. The MusicBrainz identifier of the release.</param>
|
||||
/// <param name="musicBrainzReleaseGroupId">Optional. The MusicBrainz identifier of the release group.</param>
|
||||
/// <param name="musicBrainzReleaseArtistId">Optional. The MusicBrainz identifier of the release artist.</param>
|
||||
/// <param name="createdOnUtc">Optional. The date and time when the album was created.</param>
|
||||
/// <param name="updatedOnUtc">Optional. The date and time when the album was updated.</param>
|
||||
/// <param name="contributors">Optional. The references to the media contributors that performed on the album.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the album.</param>
|
||||
/// <param name="tracks">Optional. The tracks of the album.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeArtwork">Whether the artwork should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMetadata">Whether the metadata should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaFormat">Whether the media format should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePackaging">Whether the packaging should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeBarcode">Whether the barcode should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeCatalogNumbers">Whether the catalog numbers should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLabel">Whether the label should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeAsin">Whether the ASIN should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzReleaseId">Whether the MusicBrainz release Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzReleaseGroupId">Whether the MusicBrainz release group Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzReleaseArtistId">Whether the MusicBrainz release artist Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeUpdatedOnUtc">Whether the update date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeContributors">Whether the contributors should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeRatings">Whether the ratings should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTracks">Whether the tracks should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicAlbumDto"/> instance.</returns>
|
||||
public MusicAlbumDto Create(
|
||||
Guid? id = null,
|
||||
Guid? artistId = null,
|
||||
Guid? libraryId = null,
|
||||
string? coverPath = null,
|
||||
List<MediaArtworkDto>? artwork = null,
|
||||
MusicAlbumMetadataDto? metadata = null,
|
||||
MusicMediaFormat? mediaFormat = null,
|
||||
MusicReleasePackaging? packaging = null,
|
||||
string? barcode = null,
|
||||
List<string>? catalogNumbers = null,
|
||||
string? label = null,
|
||||
string? asin = null,
|
||||
Guid? musicBrainzReleaseId = null,
|
||||
Guid? musicBrainzReleaseGroupId = null,
|
||||
Guid? musicBrainzReleaseArtistId = null,
|
||||
DateTime? createdOnUtc = null,
|
||||
DateTime? updatedOnUtc = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
List<MusicTrackDto>? tracks = null,
|
||||
bool includeCoverPath = true,
|
||||
bool includeArtwork = true,
|
||||
bool includeMetadata = true,
|
||||
bool includeMediaFormat = true,
|
||||
bool includePackaging = true,
|
||||
bool includeBarcode = true,
|
||||
bool includeCatalogNumbers = true,
|
||||
bool includeLabel = true,
|
||||
bool includeAsin = true,
|
||||
bool includeMusicBrainzReleaseId = true,
|
||||
bool includeMusicBrainzReleaseGroupId = true,
|
||||
bool includeMusicBrainzReleaseArtistId = true,
|
||||
bool includeUpdatedOnUtc = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true,
|
||||
bool includeTracks = true)
|
||||
{
|
||||
return new MusicAlbumDto
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
ArtistId = artistId ?? _faker.Random.Guid(),
|
||||
LibraryId = libraryId ?? _faker.Random.Guid(),
|
||||
CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null,
|
||||
Artwork = includeArtwork ? (artwork ?? [.. _mediaArtworkDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Metadata = includeMetadata ? (metadata ?? _musicAlbumMetadataDtoFixture.Create()) : null,
|
||||
MediaFormat = includeMediaFormat ? (mediaFormat ?? _faker.PickRandom<MusicMediaFormat>()) : null,
|
||||
Packaging = includePackaging ? (packaging ?? _faker.PickRandom<MusicReleasePackaging>()) : null,
|
||||
Barcode = includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null,
|
||||
CatalogNumbers = includeCatalogNumbers ? (catalogNumbers ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 3)).Select(_ => _faker.Random.String2(10))]) : null,
|
||||
Label = includeLabel ? (label ?? _faker.Company.CompanyName()) : null,
|
||||
ASIN = includeAsin ? (asin ?? _faker.Random.String2(10)) : null,
|
||||
MusicBrainzReleaseId = includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null,
|
||||
MusicBrainzReleaseGroupId = includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null,
|
||||
MusicBrainzReleaseArtistId = includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null,
|
||||
CreatedOnUtc = createdOnUtc ?? _faker.Date.Past(),
|
||||
UpdatedOnUtc = includeUpdatedOnUtc ? (updatedOnUtc ?? _faker.Date.Recent()) : null,
|
||||
Contributors = includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Ratings = includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Tracks = includeTracks ? (tracks ?? [.. _musicTrackDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicAlbumDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicAlbumDto"/> instances.</returns>
|
||||
public List<MusicAlbumDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicAlbumLiteDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicAlbumLiteDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicAlbumLiteDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the album.</param>
|
||||
/// <param name="title">Optional. The title of the album.</param>
|
||||
/// <param name="totalTracks">Optional. The number of tracks of the release.</param>
|
||||
/// <param name="coverPath">Optional. The path of the image representing the album.</param>
|
||||
/// <param name="releaseYear">Optional. The release year of the album.</param>
|
||||
/// <param name="releaseTypes">Optional. The set of types of the release.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReleaseYear">Whether the release year should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReleaseTypes">Whether the release types should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicAlbumLiteDto"/> instance.</returns>
|
||||
public MusicAlbumLiteDto Create(
|
||||
Guid? id = null,
|
||||
string? title = null,
|
||||
int? totalTracks = null,
|
||||
string? coverPath = null,
|
||||
int? releaseYear = null,
|
||||
List<MusicReleaseType>? releaseTypes = null,
|
||||
bool includeCoverPath = true,
|
||||
bool includeReleaseYear = true,
|
||||
bool includeReleaseTypes = true)
|
||||
{
|
||||
return new MusicAlbumLiteDto
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
Title = title ?? _faker.Lorem.Sentence(3),
|
||||
TotalTracks = totalTracks ?? _faker.Random.Number(1, 30),
|
||||
CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null,
|
||||
ReleaseYear = includeReleaseYear ? (releaseYear ?? Random.Shared.Next(1900, 2026)) : null,
|
||||
ReleaseTypes = includeReleaseTypes ? (releaseTypes ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 3)).Select(_ => _faker.PickRandom<MusicReleaseType>())]) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicAlbumLiteDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicAlbumLiteDto"/> instances.</returns>
|
||||
public List<MusicAlbumLiteDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicAlbumMetadataDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicAlbumMetadataDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
|
||||
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
|
||||
private readonly TagDtoFixture _tagDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicAlbumMetadataDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="title">Optional. The title of the album.</param>
|
||||
/// <param name="originalTitle">Optional. The original title of the album.</param>
|
||||
/// <param name="description">Optional. A brief description of the album.</param>
|
||||
/// <param name="disambiguation">Optional. The disambiguation comment of the album.</param>
|
||||
/// <param name="releaseInfo">Optional. The release information of the album.</param>
|
||||
/// <param name="language">Optional. The language of the album.</param>
|
||||
/// <param name="originalLanguage">Optional. The original language of the album.</param>
|
||||
/// <param name="tags">Optional. The tags that describe or categorize the album.</param>
|
||||
/// <param name="genres">Optional. The genres associated with the album.</param>
|
||||
/// <param name="script">Optional. The script used by the language of the release of the album.</param>
|
||||
/// <param name="releaseTypes">Optional. The set of types of the release.</param>
|
||||
/// <param name="releaseStatus">Optional. The status of the release.</param>
|
||||
/// <param name="totalDiscs">Optional. The number of discs of the release.</param>
|
||||
/// <param name="totalTracks">Optional. The number of tracks of the release.</param>
|
||||
/// <param name="releaseTitle">Optional. The title of the specific release the album files match.</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="includeDisambiguation">Whether the disambiguation 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="includeScript">Whether the script should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReleaseTypes">Whether the release types should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReleaseStatus">Whether the release status should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTotalDiscs">Whether the total number of discs should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTotalTracks">Whether the total number of tracks should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReleaseTitle">Whether the release title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicAlbumMetadataDto"/> instance.</returns>
|
||||
public MusicAlbumMetadataDto Create(
|
||||
string? title = null,
|
||||
string? originalTitle = null,
|
||||
string? description = null,
|
||||
string? disambiguation = null,
|
||||
ReleaseInfoDto? releaseInfo = null,
|
||||
LanguageInfoDto? language = null,
|
||||
LanguageInfoDto? originalLanguage = null,
|
||||
List<TagDto>? tags = null,
|
||||
List<GenreDto>? genres = null,
|
||||
string? script = null,
|
||||
List<MusicReleaseType>? releaseTypes = null,
|
||||
MusicReleaseStatus? releaseStatus = null,
|
||||
int? totalDiscs = null,
|
||||
int? totalTracks = null,
|
||||
string? releaseTitle = null,
|
||||
bool includeTitle = true,
|
||||
bool includeOriginalTitle = true,
|
||||
bool includeDescription = true,
|
||||
bool includeDisambiguation = true,
|
||||
bool includeReleaseInfo = true,
|
||||
bool includeLanguage = true,
|
||||
bool includeOriginalLanguage = true,
|
||||
bool includeTags = true,
|
||||
bool includeGenres = true,
|
||||
bool includeScript = true,
|
||||
bool includeReleaseTypes = true,
|
||||
bool includeReleaseStatus = true,
|
||||
bool includeTotalDiscs = true,
|
||||
bool includeTotalTracks = true,
|
||||
bool includeReleaseTitle = true)
|
||||
{
|
||||
return new MusicAlbumMetadataDto
|
||||
{
|
||||
Title = includeTitle ? (title ?? _faker.Lorem.Sentence(3)) : null,
|
||||
OriginalTitle = includeOriginalTitle ? (originalTitle ?? _faker.Lorem.Sentence(3)) : null,
|
||||
Description = includeDescription ? (description ?? _faker.Lorem.Paragraph()) : null,
|
||||
Disambiguation = includeDisambiguation ? (disambiguation ?? _faker.Lorem.Word()) : null,
|
||||
ReleaseInfo = includeReleaseInfo ? (releaseInfo ?? _releaseInfoDtoFixture.Create()) : null,
|
||||
Language = includeLanguage ? (language ?? _languageInfoDtoFixture.Create()) : null,
|
||||
OriginalLanguage = includeOriginalLanguage ? (originalLanguage ?? _languageInfoDtoFixture.Create()) : null,
|
||||
Tags = includeTags ? (tags ?? [.. _tagDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Genres = includeGenres ? (genres ?? [.. _genreDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Script = includeScript ? (script ?? _faker.Lorem.Word()) : null,
|
||||
ReleaseTypes = includeReleaseTypes ? (releaseTypes ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 3)).Select(_ => _faker.PickRandom<MusicReleaseType>())]) : null,
|
||||
ReleaseStatus = includeReleaseStatus ? (releaseStatus ?? _faker.PickRandom<MusicReleaseStatus>()) : null,
|
||||
TotalDiscs = includeTotalDiscs ? (totalDiscs ?? _faker.Random.Number(1, 4)) : null,
|
||||
TotalTracks = includeTotalTracks ? (totalTracks ?? _faker.Random.Number(1, 30)) : null,
|
||||
ReleaseTitle = includeReleaseTitle ? (releaseTitle ?? _faker.Lorem.Sentence(3)) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicAlbumMetadataDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicAlbumMetadataDto"/> instances.</returns>
|
||||
public List<MusicAlbumMetadataDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicAreaDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicAreaDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicAreaDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="musicBrainzAreaId">Optional. The MusicBrainz identifier of the area.</param>
|
||||
/// <param name="name">Optional. The name of the area.</param>
|
||||
/// <param name="sortName">Optional. The sort name of the area.</param>
|
||||
/// <param name="disambiguation">Optional. The disambiguation comment of the area.</param>
|
||||
/// <param name="type">Optional. The MusicBrainz type of the area.</param>
|
||||
/// <param name="iso3166Code">Optional. The ISO 3166 code of the area.</param>
|
||||
/// <param name="includeMusicBrainzAreaId">Whether the MusicBrainz area Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeSortName">Whether the sort name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeIso3166Code">Whether the ISO 3166 code should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicAreaDto"/> instance.</returns>
|
||||
public MusicAreaDto Create(
|
||||
Guid? musicBrainzAreaId = null,
|
||||
string? name = null,
|
||||
string? sortName = null,
|
||||
string? disambiguation = null,
|
||||
string? type = null,
|
||||
string? iso3166Code = null,
|
||||
bool includeMusicBrainzAreaId = true,
|
||||
bool includeName = true,
|
||||
bool includeSortName = true,
|
||||
bool includeDisambiguation = true,
|
||||
bool includeType = true,
|
||||
bool includeIso3166Code = true)
|
||||
{
|
||||
return new MusicAreaDto
|
||||
{
|
||||
MusicBrainzAreaId = includeMusicBrainzAreaId ? (musicBrainzAreaId ?? _faker.Random.Guid()) : null,
|
||||
Name = includeName ? (name ?? _faker.Address.Country()) : null,
|
||||
SortName = includeSortName ? (sortName ?? _faker.Address.Country()) : null,
|
||||
Disambiguation = includeDisambiguation ? (disambiguation ?? _faker.Lorem.Word()) : null,
|
||||
Type = includeType ? (type ?? _faker.Lorem.Word()) : null,
|
||||
Iso3166Code = includeIso3166Code ? (iso3166Code ?? _faker.Address.CountryCode()) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicAreaDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicAreaDto"/> instances.</returns>
|
||||
public List<MusicAreaDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicArtistAliasDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtistAliasDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicArtistAliasDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional. The name of the alias.</param>
|
||||
/// <param name="sortName">Optional. The sort name of the alias.</param>
|
||||
/// <param name="type">Optional. The type of the alias.</param>
|
||||
/// <param name="locale">Optional. The locale the alias is used in.</param>
|
||||
/// <param name="isPrimary">Optional. Whether this is the primary alias of the artist.</param>
|
||||
/// <param name="beginDate">Optional. The date the alias began being used.</param>
|
||||
/// <param name="endDate">Optional. The date the alias stopped being used.</param>
|
||||
/// <param name="isEnded">Optional. Whether the alias is no longer used.</param>
|
||||
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeSortName">Whether the sort name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLocale">Whether the locale should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeBeginDate">Whether the begin date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeEndDate">Whether the end date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicArtistAliasDto"/> instance.</returns>
|
||||
public MusicArtistAliasDto Create(
|
||||
string? name = null,
|
||||
string? sortName = null,
|
||||
string? type = null,
|
||||
string? locale = null,
|
||||
bool isPrimary = false,
|
||||
DateOnly? beginDate = null,
|
||||
DateOnly? endDate = null,
|
||||
bool isEnded = false,
|
||||
bool includeName = true,
|
||||
bool includeSortName = true,
|
||||
bool includeType = true,
|
||||
bool includeLocale = true,
|
||||
bool includeBeginDate = true,
|
||||
bool includeEndDate = true)
|
||||
{
|
||||
DateOnly resolvedBeginDate = beginDate ?? DateOnly.FromDateTime(_faker.Date.Past());
|
||||
DateOnly resolvedEndDate = endDate ?? DateOnly.FromDateTime(_faker.Date.Future());
|
||||
|
||||
return new MusicArtistAliasDto
|
||||
{
|
||||
Name = includeName ? (name ?? _faker.Name.FullName()) : null,
|
||||
SortName = includeSortName ? (sortName ?? _faker.Name.LastName()) : null,
|
||||
Type = includeType ? (type ?? _faker.Lorem.Word()) : null,
|
||||
Locale = includeLocale ? (locale ?? _faker.Random.String2(2, "abcdefghijklmnopqrstuvwxyz")) : null,
|
||||
IsPrimary = isPrimary,
|
||||
BeginDate = includeBeginDate ? resolvedBeginDate : null,
|
||||
EndDate = includeEndDate ? resolvedEndDate : null,
|
||||
IsEnded = isEnded
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicArtistAliasDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicArtistAliasDto"/> instances.</returns>
|
||||
public List<MusicArtistAliasDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicArtistDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtistDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicArtistDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the artist.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library this artist belongs to.</param>
|
||||
/// <param name="coverPath">Optional. The path of the image representing the artist.</param>
|
||||
/// <param name="metadata">Optional. The metadata 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="ipis">Optional. The IPI codes of the artist.</param>
|
||||
/// <param name="isnis">Optional. The ISNI codes of the artist.</param>
|
||||
/// <param name="createdOnUtc">Optional. The date and time when the artist was created.</param>
|
||||
/// <param name="updatedOnUtc">Optional. The date and time when the artist was updated.</param>
|
||||
/// <param name="contributors">Optional. The references to the media contributors that make up the artist.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the artist.</param>
|
||||
/// <param name="albums">Optional. The albums of the artist.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover 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="includeWebsite">Whether the website should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzArtistId">Whether the MusicBrainz artist Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeIpis">Whether the IPI codes should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeIsnis">Whether the ISNI codes should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeUpdatedOnUtc">Whether the update date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeContributors">Whether the contributors should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeRatings">Whether the ratings should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeAlbums">Whether the albums should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicArtistDto"/> instance.</returns>
|
||||
public MusicArtistDto Create(
|
||||
Guid? id = null,
|
||||
Guid? libraryId = null,
|
||||
string? coverPath = null,
|
||||
MusicArtistMetadataDto? metadata = null,
|
||||
string? website = null,
|
||||
Guid? musicBrainzArtistId = null,
|
||||
List<string>? ipis = null,
|
||||
List<string>? isnis = null,
|
||||
DateTime? createdOnUtc = null,
|
||||
DateTime? updatedOnUtc = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
List<MusicAlbumDto>? albums = null,
|
||||
bool includeCoverPath = true,
|
||||
bool includeMetadata = true,
|
||||
bool includeWebsite = true,
|
||||
bool includeMusicBrainzArtistId = true,
|
||||
bool includeIpis = true,
|
||||
bool includeIsnis = true,
|
||||
bool includeUpdatedOnUtc = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true,
|
||||
bool includeAlbums = true)
|
||||
{
|
||||
return new MusicArtistDto
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
LibraryId = libraryId ?? _faker.Random.Guid(),
|
||||
CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null,
|
||||
Metadata = includeMetadata ? (metadata ?? _musicArtistMetadataDtoFixture.Create()) : null,
|
||||
Website = includeWebsite ? (website ?? _faker.Internet.Url()) : null,
|
||||
MusicBrainzArtistId = includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null,
|
||||
Ipis = includeIpis ? (ipis ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 3)).Select(_ => _faker.Random.String2(10, "0123456789"))]) : null,
|
||||
Isnis = includeIsnis ? (isnis ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 3)).Select(_ => _faker.Random.String2(16, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"))]) : null,
|
||||
CreatedOnUtc = createdOnUtc ?? _faker.Date.Past(),
|
||||
UpdatedOnUtc = includeUpdatedOnUtc ? (updatedOnUtc ?? _faker.Date.Recent()) : null,
|
||||
Contributors = includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Ratings = includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Albums = includeAlbums ? (albums ?? [.. _musicAlbumDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicArtistDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicArtistDto"/> instances.</returns>
|
||||
public List<MusicArtistDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicArtistLiteDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtistLiteDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicArtistLiteDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the artist.</param>
|
||||
/// <param name="name">Optional. The name of the artist.</param>
|
||||
/// <param name="coverPath">Optional. The path of the image representing the artist.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicArtistLiteDto"/> instance.</returns>
|
||||
public MusicArtistLiteDto Create(
|
||||
Guid? id = null,
|
||||
string? name = null,
|
||||
string? coverPath = null,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new MusicArtistLiteDto
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
Name = name ?? _faker.Name.FullName(),
|
||||
CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicArtistLiteDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicArtistLiteDto"/> instances.</returns>
|
||||
public List<MusicArtistLiteDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicArtistMetadataDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtistMetadataDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicAreaDtoFixture _musicAreaDtoFixture = new();
|
||||
private readonly MusicArtistAliasDtoFixture _musicArtistAliasDtoFixture = new();
|
||||
private readonly TagDtoFixture _tagDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicArtistMetadataDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional. The name of the artist.</param>
|
||||
/// <param name="sortName">Optional. The sort name of the artist.</param>
|
||||
/// <param name="disambiguation">Optional. The disambiguation comment of the artist.</param>
|
||||
/// <param name="type">Optional. The type of the artist.</param>
|
||||
/// <param name="gender">Optional. The gender of the artist.</param>
|
||||
/// <param name="country">Optional. The ISO 3166-1 alpha-2 code of the country the artist is associated with.</param>
|
||||
/// <param name="area">Optional. The area the artist is primarily identified with.</param>
|
||||
/// <param name="beginArea">Optional. The area the artist began in.</param>
|
||||
/// <param name="endArea">Optional. The area the artist ended in.</param>
|
||||
/// <param name="lifeSpanBegin">Optional. The date the artist started existing.</param>
|
||||
/// <param name="lifeSpanEnd">Optional. The date the artist stopped existing.</param>
|
||||
/// <param name="isEnded">Optional. Whether the artist no longer exists.</param>
|
||||
/// <param name="genres">Optional. The genres associated with the artist.</param>
|
||||
/// <param name="tags">Optional. The tags that describe or categorize the artist.</param>
|
||||
/// <param name="aliases">Optional. The alternative names of the artist.</param>
|
||||
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeSortName">Whether the sort name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeGender">Whether the gender should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeCountry">Whether the country should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeArea">Whether the area should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeBeginArea">Whether the begin area should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeEndArea">Whether the end area should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLifeSpanBegin">Whether the life span begin date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLifeSpanEnd">Whether the life span end date 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="includeTags">Whether the tags should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeAliases">Whether the aliases should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicArtistMetadataDto"/> instance.</returns>
|
||||
public MusicArtistMetadataDto Create(
|
||||
string? name = null,
|
||||
string? sortName = null,
|
||||
string? disambiguation = null,
|
||||
MusicArtistType? type = null,
|
||||
MusicArtistGender? gender = null,
|
||||
string? country = null,
|
||||
MusicAreaDto? area = null,
|
||||
MusicAreaDto? beginArea = null,
|
||||
MusicAreaDto? endArea = null,
|
||||
DateOnly? lifeSpanBegin = null,
|
||||
DateOnly? lifeSpanEnd = null,
|
||||
bool isEnded = false,
|
||||
List<GenreDto>? genres = null,
|
||||
List<TagDto>? tags = null,
|
||||
List<MusicArtistAliasDto>? aliases = null,
|
||||
bool includeName = true,
|
||||
bool includeSortName = true,
|
||||
bool includeDisambiguation = true,
|
||||
bool includeType = true,
|
||||
bool includeGender = true,
|
||||
bool includeCountry = true,
|
||||
bool includeArea = true,
|
||||
bool includeBeginArea = true,
|
||||
bool includeEndArea = true,
|
||||
bool includeLifeSpanBegin = true,
|
||||
bool includeLifeSpanEnd = true,
|
||||
bool includeGenres = true,
|
||||
bool includeTags = true,
|
||||
bool includeAliases = true)
|
||||
{
|
||||
return new MusicArtistMetadataDto
|
||||
{
|
||||
Name = includeName ? (name ?? _faker.Name.FullName()) : null,
|
||||
SortName = includeSortName ? (sortName ?? _faker.Name.LastName()) : null,
|
||||
Disambiguation = includeDisambiguation ? (disambiguation ?? _faker.Lorem.Word()) : null,
|
||||
Type = includeType ? (type ?? _faker.PickRandom<MusicArtistType>()) : null,
|
||||
Gender = includeGender ? (gender ?? _faker.PickRandom<MusicArtistGender>()) : null,
|
||||
Country = includeCountry ? (country ?? _faker.Address.CountryCode()) : null,
|
||||
Area = includeArea ? (area ?? _musicAreaDtoFixture.Create()) : null,
|
||||
BeginArea = includeBeginArea ? (beginArea ?? _musicAreaDtoFixture.Create()) : null,
|
||||
EndArea = includeEndArea ? (endArea ?? _musicAreaDtoFixture.Create()) : null,
|
||||
LifeSpanBegin = includeLifeSpanBegin ? (lifeSpanBegin ?? DateOnly.FromDateTime(_faker.Date.Past())) : null,
|
||||
LifeSpanEnd = includeLifeSpanEnd ? (lifeSpanEnd ?? DateOnly.FromDateTime(_faker.Date.Past())) : null,
|
||||
IsEnded = isEnded,
|
||||
Genres = includeGenres ? (genres ?? [.. _genreDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Tags = includeTags ? (tags ?? [.. _tagDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Aliases = includeAliases ? (aliases ?? [.. _musicArtistAliasDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicArtistMetadataDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicArtistMetadataDto"/> instances.</returns>
|
||||
public List<MusicArtistMetadataDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
|
||||
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicTrackDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicTrackDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new();
|
||||
private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new();
|
||||
private readonly MoodDtoFixture _moodDtoFixture = new();
|
||||
private readonly IsrcDtoFixture _isrcDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicTrackDto"/> instance with randomized test data.
|
||||
/// </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 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="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 moods of the track.</param>
|
||||
/// <param name="isrcs">Optional. The ISRC codes of the track.</param>
|
||||
/// <param name="contributors">Optional. The references to the media contributors that performed on the track.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the track.</param>
|
||||
/// <param name="includeMetadata">Whether the metadata should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeDiscNumber">Whether the disc number should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeScript">Whether the script should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeKey">Whether the musical key should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeBpm">Whether the tempo should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeWork">Whether the work should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzRecordingId">Whether the MusicBrainz recording Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzTrackId">Whether the MusicBrainz track Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeUpdatedOnUtc">Whether the update date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMoods">Whether the moods should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeIsrcs">Whether the ISRC codes should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeContributors">Whether the contributors 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>A configured <see cref="MusicTrackDto"/> instance.</returns>
|
||||
public MusicTrackDto Create(
|
||||
Guid? id = null,
|
||||
Guid? albumId = null,
|
||||
Guid? libraryId = null,
|
||||
string? path = null,
|
||||
MusicTrackMetadataDto? metadata = null,
|
||||
int? trackNumber = null,
|
||||
int? discNumber = null,
|
||||
string? script = null,
|
||||
MusicKey? key = null,
|
||||
int? bpm = null,
|
||||
MusicWorkDto? work = null,
|
||||
Guid? musicBrainzRecordingId = null,
|
||||
Guid? musicBrainzTrackId = null,
|
||||
DateTime? createdOnUtc = null,
|
||||
DateTime? updatedOnUtc = null,
|
||||
List<MoodDto>? moods = null,
|
||||
List<IsrcDto>? isrcs = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
bool includeMetadata = true,
|
||||
bool includeDiscNumber = true,
|
||||
bool includeScript = true,
|
||||
bool includeKey = true,
|
||||
bool includeBpm = true,
|
||||
bool includeWork = true,
|
||||
bool includeMusicBrainzRecordingId = true,
|
||||
bool includeMusicBrainzTrackId = true,
|
||||
bool includeUpdatedOnUtc = true,
|
||||
bool includeMoods = true,
|
||||
bool includeIsrcs = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true)
|
||||
{
|
||||
return new MusicTrackDto
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
AlbumId = albumId ?? _faker.Random.Guid(),
|
||||
LibraryId = libraryId ?? _faker.Random.Guid(),
|
||||
Path = path ?? _faker.System.FilePath(),
|
||||
Metadata = includeMetadata ? (metadata ?? _musicTrackMetadataDtoFixture.Create()) : null,
|
||||
TrackNumber = trackNumber ?? _faker.Random.Number(1, 30),
|
||||
DiscNumber = includeDiscNumber ? (discNumber ?? _faker.Random.Number(1, 3)) : null,
|
||||
Script = includeScript ? (script ?? _faker.Lorem.Word()) : null,
|
||||
Key = includeKey ? (key ?? _faker.PickRandom<MusicKey>()) : null,
|
||||
Bpm = includeBpm ? (bpm ?? _faker.Random.Number(60, 200)) : null,
|
||||
Work = includeWork ? (work ?? _musicWorkDtoFixture.Create()) : null,
|
||||
MusicBrainzRecordingId = includeMusicBrainzRecordingId ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null,
|
||||
MusicBrainzTrackId = includeMusicBrainzTrackId ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null,
|
||||
CreatedOnUtc = createdOnUtc ?? _faker.Date.Past(),
|
||||
UpdatedOnUtc = includeUpdatedOnUtc ? (updatedOnUtc ?? _faker.Date.Recent()) : null,
|
||||
Moods = includeMoods ? (moods ?? [.. _moodDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Isrcs = includeIsrcs ? (isrcs ?? [.. _isrcDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Contributors = includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Ratings = includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicTrackDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicTrackDto"/> instances.</returns>
|
||||
public List<MusicTrackDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicTrackLiteDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicTrackLiteDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicTrackLiteDto"/> instance with randomized test data.
|
||||
/// </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="durationInSeconds">Optional. The duration of the track in seconds.</param>
|
||||
/// <param name="includeDiscNumber">Whether the disc number should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicTrackLiteDto"/> instance.</returns>
|
||||
public MusicTrackLiteDto Create(
|
||||
Guid? id = null,
|
||||
string? title = null,
|
||||
int? trackNumber = null,
|
||||
int? discNumber = null,
|
||||
int? durationInSeconds = null,
|
||||
bool includeDiscNumber = true)
|
||||
{
|
||||
return new MusicTrackLiteDto
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
Title = title ?? _faker.Lorem.Sentence(3),
|
||||
TrackNumber = trackNumber ?? _faker.Random.Number(1, 30),
|
||||
DiscNumber = includeDiscNumber ? (discNumber ?? _faker.Random.Number(1, 3)) : null,
|
||||
DurationInSeconds = durationInSeconds ?? _faker.Random.Number(30, 600)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicTrackLiteDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicTrackLiteDto"/> instances.</returns>
|
||||
public List<MusicTrackLiteDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicTrackMetadataDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicTrackMetadataDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
|
||||
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
|
||||
private readonly TagDtoFixture _tagDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicTrackMetadataDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="title">Optional. The title of the track.</param>
|
||||
/// <param name="originalTitle">Optional. The original title of the track.</param>
|
||||
/// <param name="description">Optional. A brief description of the track.</param>
|
||||
/// <param name="disambiguation">Optional. The disambiguation comment of the track.</param>
|
||||
/// <param name="releaseInfo">Optional. The release information of the track.</param>
|
||||
/// <param name="language">Optional. The language of the track.</param>
|
||||
/// <param name="originalLanguage">Optional. The original language of the track.</param>
|
||||
/// <param name="tags">Optional. The tags that describe or categorize the track.</param>
|
||||
/// <param name="genres">Optional. The genres associated with the track.</param>
|
||||
/// <param name="isVideo">Optional. Whether the recording of the track is a video recording.</param>
|
||||
/// <param name="durationInSeconds">Optional. The duration of the audio of the track in seconds.</param>
|
||||
/// <param name="sampleRate">Optional. The sample rate of the audio of the track in Hz.</param>
|
||||
/// <param name="channels">Optional. The number of audio channels of the track.</param>
|
||||
/// <param name="bitDepth">Optional. The bit depth of the audio of the track.</param>
|
||||
/// <param name="audioCodec">Optional. The audio codec used by the track.</param>
|
||||
/// <param name="bitrate">Optional. The bitrate of the audio of the track in kbps.</param>
|
||||
/// <param name="acoustId">Optional. The AcoustID fingerprint identifier of the audio file of the track.</param>
|
||||
/// <param name="replayGainTrackGain">Optional. The ReplayGain track gain of the track in decibels.</param>
|
||||
/// <param name="replayGainTrackPeak">Optional. The ReplayGain track peak of the track.</param>
|
||||
/// <param name="replayGainAlbumGain">Optional. The ReplayGain album gain of the track in decibels.</param>
|
||||
/// <param name="replayGainAlbumPeak">Optional. The ReplayGain album peak of the track.</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="includeDisambiguation">Whether the disambiguation 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>
|
||||
/// <param name="includeAcoustId">Whether the AcoustID should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReplayGainTrackGain">Whether the ReplayGain track gain should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReplayGainTrackPeak">Whether the ReplayGain track peak should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReplayGainAlbumGain">Whether the ReplayGain album gain should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReplayGainAlbumPeak">Whether the ReplayGain album peak should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicTrackMetadataDto"/> instance.</returns>
|
||||
public MusicTrackMetadataDto Create(
|
||||
string? title = null,
|
||||
string? originalTitle = null,
|
||||
string? description = null,
|
||||
string? disambiguation = null,
|
||||
ReleaseInfoDto? releaseInfo = null,
|
||||
LanguageInfoDto? language = null,
|
||||
LanguageInfoDto? originalLanguage = null,
|
||||
List<TagDto>? tags = null,
|
||||
List<GenreDto>? genres = null,
|
||||
bool isVideo = false,
|
||||
int? durationInSeconds = null,
|
||||
int? sampleRate = null,
|
||||
int? channels = null,
|
||||
int? bitDepth = null,
|
||||
string? audioCodec = null,
|
||||
int? bitrate = null,
|
||||
string? acoustId = null,
|
||||
decimal? replayGainTrackGain = null,
|
||||
decimal? replayGainTrackPeak = null,
|
||||
decimal? replayGainAlbumGain = null,
|
||||
decimal? replayGainAlbumPeak = null,
|
||||
bool includeTitle = true,
|
||||
bool includeOriginalTitle = true,
|
||||
bool includeDescription = true,
|
||||
bool includeDisambiguation = 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,
|
||||
bool includeAcoustId = true,
|
||||
bool includeReplayGainTrackGain = true,
|
||||
bool includeReplayGainTrackPeak = true,
|
||||
bool includeReplayGainAlbumGain = true,
|
||||
bool includeReplayGainAlbumPeak = true)
|
||||
{
|
||||
return new MusicTrackMetadataDto
|
||||
{
|
||||
Title = includeTitle ? (title ?? _faker.Lorem.Sentence(3)) : null,
|
||||
OriginalTitle = includeOriginalTitle ? (originalTitle ?? _faker.Lorem.Sentence(3)) : null,
|
||||
Description = includeDescription ? (description ?? _faker.Lorem.Paragraph()) : null,
|
||||
Disambiguation = includeDisambiguation ? (disambiguation ?? _faker.Lorem.Word()) : null,
|
||||
ReleaseInfo = includeReleaseInfo ? (releaseInfo ?? _releaseInfoDtoFixture.Create()) : null,
|
||||
Language = includeLanguage ? (language ?? _languageInfoDtoFixture.Create()) : null,
|
||||
OriginalLanguage = includeOriginalLanguage ? (originalLanguage ?? _languageInfoDtoFixture.Create()) : null,
|
||||
Tags = includeTags ? (tags ?? [.. _tagDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Genres = includeGenres ? (genres ?? [.. _genreDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
IsVideo = isVideo,
|
||||
DurationInSeconds = includeDurationInSeconds ? (durationInSeconds ?? _faker.Random.Number(30, 600)) : null,
|
||||
SampleRate = includeSampleRate ? (sampleRate ?? _faker.Random.Number(22050, 192000)) : null,
|
||||
Channels = includeChannels ? (channels ?? _faker.Random.Number(1, 8)) : null,
|
||||
BitDepth = includeBitDepth ? (bitDepth ?? _faker.Random.Number(8, 32)) : null,
|
||||
AudioCodec = includeAudioCodec ? (audioCodec ?? _faker.Lorem.Word()) : null,
|
||||
Bitrate = includeBitrate ? (bitrate ?? _faker.Random.Number(64, 1411)) : null,
|
||||
AcoustId = includeAcoustId ? (acoustId ?? _faker.Random.String2(32, "0123456789abcdef")) : null,
|
||||
ReplayGainTrackGain = includeReplayGainTrackGain ? (replayGainTrackGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
|
||||
ReplayGainTrackPeak = includeReplayGainTrackPeak ? (replayGainTrackPeak ?? _faker.Random.Decimal(0m, 1m)) : null,
|
||||
ReplayGainAlbumGain = includeReplayGainAlbumGain ? (replayGainAlbumGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
|
||||
ReplayGainAlbumPeak = includeReplayGainAlbumPeak ? (replayGainAlbumPeak ?? _faker.Random.Decimal(0m, 1m)) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicTrackMetadataDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicTrackMetadataDto"/> instances.</returns>
|
||||
public List<MusicTrackMetadataDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicWorkDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicWorkDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicWorkDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="musicBrainzWorkId">Optional. The MusicBrainz identifier of the work.</param>
|
||||
/// <param name="title">Optional. The title of the work.</param>
|
||||
/// <param name="type">Optional. The MusicBrainz type of the work.</param>
|
||||
/// <param name="languages">Optional. The languages of the work.</param>
|
||||
/// <param name="iswcs">Optional. The ISWC codes of the work.</param>
|
||||
/// <param name="includeMusicBrainzWorkId">Whether the MusicBrainz work Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLanguages">Whether the languages should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeIswcs">Whether the ISWC codes should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicWorkDto"/> instance.</returns>
|
||||
public MusicWorkDto Create(
|
||||
Guid? musicBrainzWorkId = null,
|
||||
string? title = null,
|
||||
string? type = null,
|
||||
List<LanguageInfoDto>? languages = null,
|
||||
List<string>? iswcs = null,
|
||||
bool includeMusicBrainzWorkId = true,
|
||||
bool includeTitle = true,
|
||||
bool includeType = true,
|
||||
bool includeLanguages = true,
|
||||
bool includeIswcs = true)
|
||||
{
|
||||
return new MusicWorkDto
|
||||
{
|
||||
MusicBrainzWorkId = includeMusicBrainzWorkId ? (musicBrainzWorkId ?? _faker.Random.Guid()) : null,
|
||||
Title = includeTitle ? (title ?? _faker.Lorem.Sentence(3)) : null,
|
||||
Type = includeType ? (type ?? _faker.Lorem.Word()) : null,
|
||||
Languages = includeLanguages ? (languages ?? [.. _languageInfoDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Iswcs = includeIswcs ? (iswcs ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 3)).Select(_ => $"T{_faker.Random.Number(100000000, 999999999)}")]) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicWorkDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicWorkDto"/> instances.</returns>
|
||||
public List<MusicWorkDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PaginatedMusicAlbumLiteDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PaginatedMusicAlbumLiteDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicAlbumLiteDtoFixture _musicAlbumLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="PaginatedMusicAlbumLiteDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="data">Optional. The collection of lightweight album elements.</param>
|
||||
/// <param name="currentPage">Optional. The current page number in the paginated collection.</param>
|
||||
/// <param name="perPage">Optional. The number of items to include per page.</param>
|
||||
/// <param name="count">Optional. The total number of elements available in the result set.</param>
|
||||
/// <param name="numberOfPages">Optional. The total number of pages available.</param>
|
||||
/// <returns>A configured <see cref="PaginatedMusicAlbumLiteDto"/> instance.</returns>
|
||||
public PaginatedMusicAlbumLiteDto Create(
|
||||
IReadOnlyList<MusicAlbumLiteDto>? data = null,
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
int? count = null,
|
||||
int? numberOfPages = null)
|
||||
{
|
||||
return new PaginatedMusicAlbumLiteDto
|
||||
{
|
||||
Data = data ?? [.. _musicAlbumLiteDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
|
||||
CurrentPage = currentPage ?? _faker.Random.Int(1, 10),
|
||||
PerPage = perPage ?? _faker.Random.Int(1, 100),
|
||||
Count = count ?? _faker.Random.Int(0, 1000),
|
||||
NumberOfPages = numberOfPages ?? _faker.Random.Int(1, 100)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="PaginatedMusicAlbumLiteDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="PaginatedMusicAlbumLiteDto"/> instances.</returns>
|
||||
public List<PaginatedMusicAlbumLiteDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PaginatedMusicArtistLiteDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PaginatedMusicArtistLiteDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicArtistLiteDtoFixture _musicArtistLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="PaginatedMusicArtistLiteDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="data">Optional. The collection of lightweight artist elements.</param>
|
||||
/// <param name="currentPage">Optional. The current page number in the paginated collection.</param>
|
||||
/// <param name="perPage">Optional. The number of items to include per page.</param>
|
||||
/// <param name="count">Optional. The total number of elements available in the result set.</param>
|
||||
/// <param name="numberOfPages">Optional. The total number of pages available.</param>
|
||||
/// <returns>A configured <see cref="PaginatedMusicArtistLiteDto"/> instance.</returns>
|
||||
public PaginatedMusicArtistLiteDto Create(
|
||||
IReadOnlyList<MusicArtistLiteDto>? data = null,
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
int? count = null,
|
||||
int? numberOfPages = null)
|
||||
{
|
||||
return new PaginatedMusicArtistLiteDto
|
||||
{
|
||||
Data = data ?? [.. _musicArtistLiteDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
|
||||
CurrentPage = currentPage ?? _faker.Random.Int(1, 10),
|
||||
PerPage = perPage ?? _faker.Random.Int(1, 100),
|
||||
Count = count ?? _faker.Random.Int(0, 1000),
|
||||
NumberOfPages = numberOfPages ?? _faker.Random.Int(1, 100)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="PaginatedMusicArtistLiteDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="PaginatedMusicArtistLiteDto"/> instances.</returns>
|
||||
public List<PaginatedMusicArtistLiteDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PaginatedMusicTrackLiteDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PaginatedMusicTrackLiteDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicTrackLiteDtoFixture _musicTrackLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="PaginatedMusicTrackLiteDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="data">Optional. The collection of lightweight track elements.</param>
|
||||
/// <param name="currentPage">Optional. The current page number in the paginated collection.</param>
|
||||
/// <param name="perPage">Optional. The number of items to include per page.</param>
|
||||
/// <param name="count">Optional. The total number of elements available in the result set.</param>
|
||||
/// <param name="numberOfPages">Optional. The total number of pages available.</param>
|
||||
/// <returns>A configured <see cref="PaginatedMusicTrackLiteDto"/> instance.</returns>
|
||||
public PaginatedMusicTrackLiteDto Create(
|
||||
IReadOnlyList<MusicTrackLiteDto>? data = null,
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
int? count = null,
|
||||
int? numberOfPages = null)
|
||||
{
|
||||
return new PaginatedMusicTrackLiteDto
|
||||
{
|
||||
Data = data ?? [.. _musicTrackLiteDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
|
||||
CurrentPage = currentPage ?? _faker.Random.Int(1, 10),
|
||||
PerPage = perPage ?? _faker.Random.Int(1, 100),
|
||||
Count = count ?? _faker.Random.Int(0, 1000),
|
||||
NumberOfPages = numberOfPages ?? _faker.Random.Int(1, 100)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="PaginatedMusicTrackLiteDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="PaginatedMusicTrackLiteDto"/> instances.</returns>
|
||||
public List<PaginatedMusicTrackLiteDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateMusicCoverDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateMusicCoverDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="UpdateMusicCoverDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="coverPath">Optional. The relative path of the stored cover image.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="UpdateMusicCoverDto"/> instance.</returns>
|
||||
public UpdateMusicCoverDto Create(
|
||||
string? coverPath = null,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new UpdateMusicCoverDto
|
||||
{
|
||||
CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="UpdateMusicCoverDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="UpdateMusicCoverDto"/> instances.</returns>
|
||||
public List<UpdateMusicCoverDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Enums.MediaLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MediaArtworkDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaArtworkDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MediaArtworkDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="type">Optional. The type of the artwork.</param>
|
||||
/// <param name="ordinal">Optional. The ordinal of the artwork within its type.</param>
|
||||
/// <param name="path">Optional. The relative path of the stored artwork file.</param>
|
||||
/// <returns>A configured <see cref="MediaArtworkDto"/> instance.</returns>
|
||||
public MediaArtworkDto Create(
|
||||
ArtworkType? type = null,
|
||||
int? ordinal = null,
|
||||
string? path = null)
|
||||
{
|
||||
return new MediaArtworkDto
|
||||
{
|
||||
Type = type ?? _faker.PickRandom<ArtworkType>(),
|
||||
Ordinal = ordinal ?? _faker.Random.Int(1, 10),
|
||||
Path = path ?? _faker.System.FilePath()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MediaArtworkDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MediaArtworkDto"/> instances.</returns>
|
||||
public List<MediaArtworkDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MoodDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MoodDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MoodDto"/> instance with randomized test data.
|
||||
/// </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>A configured <see cref="MoodDto"/> instance.</returns>
|
||||
public MoodDto Create(
|
||||
string? name = null,
|
||||
bool includeName = true)
|
||||
{
|
||||
return new MoodDto
|
||||
{
|
||||
Name = includeName ? (name ?? _faker.Lorem.Word()) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MoodDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MoodDto"/> instances.</returns>
|
||||
public List<MoodDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
|
||||
using Lumina.Presentation.Web.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MediaContributorReferenceDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorReferenceDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MediaContributorReferenceDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="contributorId">Optional. The unique identifier of the media contributor.</param>
|
||||
/// <param name="role">Optional. The role the contributor played.</param>
|
||||
/// <param name="includeRole">Whether the role should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MediaContributorReferenceDto"/> instance.</returns>
|
||||
public MediaContributorReferenceDto Create(
|
||||
Guid? contributorId = null,
|
||||
MediaContributorRole? role = null,
|
||||
bool includeRole = true)
|
||||
{
|
||||
return new MediaContributorReferenceDto
|
||||
{
|
||||
ContributorId = contributorId ?? _faker.Random.Guid(),
|
||||
Role = includeRole ? (role ?? _faker.PickRandom<MediaContributorRole>()) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MediaContributorReferenceDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MediaContributorReferenceDto"/> instances.</returns>
|
||||
public List<MediaContributorReferenceDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetArtistAlbumsLiteRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetArtistAlbumsLiteRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetArtistAlbumsLiteRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="artistId">Optional Id of the artist whose albums are retrieved.</param>
|
||||
/// <param name="libraryId">Optional Id of the media library the artist belongs to.</param>
|
||||
/// <param name="currentPage">Optional page of results to retrieve.</param>
|
||||
/// <param name="perPage">Optional maximum number of albums to retrieve per page.</param>
|
||||
/// <returns>A configured <see cref="GetArtistAlbumsLiteRequest"/> instance.</returns>
|
||||
public GetArtistAlbumsLiteRequest Create(
|
||||
string? artistId = null,
|
||||
Guid? libraryId = null,
|
||||
int? currentPage = null,
|
||||
int? perPage = null)
|
||||
{
|
||||
return new GetArtistAlbumsLiteRequest(
|
||||
ArtistId: artistId ?? Guid.NewGuid().ToString(),
|
||||
LibraryId: libraryId ?? Guid.NewGuid(),
|
||||
CurrentPage: currentPage,
|
||||
PerPage: perPage
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetArtistAlbumsLiteRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetArtistAlbumsLiteRequest"/> instances.</returns>
|
||||
public List<GetArtistAlbumsLiteRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetMusicAlbumViewRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicAlbumViewRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetMusicAlbumViewRequest"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="artistId">Optional unique identifier of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">Optional unique identifier of the album to retrieve.</param>
|
||||
/// <param name="libraryId">Optional unique identifier of the media library the album belongs to.</param>
|
||||
/// <returns>A configured <see cref="GetMusicAlbumViewRequest"/> instance.</returns>
|
||||
public GetMusicAlbumViewRequest Create(
|
||||
string? artistId = null,
|
||||
string? albumId = null,
|
||||
Guid? libraryId = null)
|
||||
{
|
||||
return new GetMusicAlbumViewRequest(
|
||||
artistId ?? Guid.NewGuid().ToString(),
|
||||
albumId ?? Guid.NewGuid().ToString(),
|
||||
libraryId ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetMusicAlbumViewRequest"/> instances.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetMusicAlbumViewRequest"/> instances.</returns>
|
||||
public List<GetMusicAlbumViewRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
|
||||
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateMusicAlbumRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateMusicAlbumRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="UpdateMusicAlbumRequest"/> instance with randomized test data.
|
||||
/// </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="packaging">Optional. The outermost physical packaging of the album.</param>
|
||||
/// <param name="barcode">Optional. The barcode of the album.</param>
|
||||
/// <param name="catalogNumbers">Optional. The catalog numbers of the album.</param>
|
||||
/// <param name="label">Optional. The name of the label that issued the album.</param>
|
||||
/// <param name="asin">Optional. The ASIN 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 references to the media contributors that performed on the album.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the album.</param>
|
||||
/// <param name="includeMetadata">Whether the metadata should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaFormat">Whether the media format should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePackaging">Whether the packaging should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeBarcode">Whether the barcode should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeCatalogNumbers">Whether the catalog numbers should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLabel">Whether the label should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeAsin">Whether the ASIN should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzReleaseId">Whether the MusicBrainz release Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzReleaseGroupId">Whether the MusicBrainz release group Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzReleaseArtistId">Whether the MusicBrainz release artist Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeContributors">Whether the contributors should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeRatings">Whether the ratings should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="UpdateMusicAlbumRequest"/> instance.</returns>
|
||||
public UpdateMusicAlbumRequest Create(
|
||||
MusicAlbumMetadataDto? metadata = null,
|
||||
MusicMediaFormat? mediaFormat = null,
|
||||
MusicReleasePackaging? packaging = null,
|
||||
string? barcode = null,
|
||||
List<string>? catalogNumbers = null,
|
||||
string? label = null,
|
||||
string? asin = null,
|
||||
Guid? musicBrainzReleaseId = null,
|
||||
Guid? musicBrainzReleaseGroupId = null,
|
||||
Guid? musicBrainzReleaseArtistId = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
bool includeMetadata = true,
|
||||
bool includeMediaFormat = true,
|
||||
bool includePackaging = true,
|
||||
bool includeBarcode = true,
|
||||
bool includeCatalogNumbers = true,
|
||||
bool includeLabel = true,
|
||||
bool includeAsin = true,
|
||||
bool includeMusicBrainzReleaseId = true,
|
||||
bool includeMusicBrainzReleaseGroupId = true,
|
||||
bool includeMusicBrainzReleaseArtistId = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true)
|
||||
{
|
||||
return new UpdateMusicAlbumRequest(
|
||||
Metadata: includeMetadata ? (metadata ?? _musicAlbumMetadataDtoFixture.Create()) : null,
|
||||
MediaFormat: includeMediaFormat ? (mediaFormat ?? _faker.PickRandom<MusicMediaFormat>()) : null,
|
||||
Packaging: includePackaging ? (packaging ?? _faker.PickRandom<MusicReleasePackaging>()) : null,
|
||||
Barcode: includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null,
|
||||
CatalogNumbers: includeCatalogNumbers ? (catalogNumbers ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 3)).Select(_ => _faker.Random.String2(10))]) : null,
|
||||
Label: includeLabel ? (label ?? _faker.Company.CompanyName()) : null,
|
||||
ASIN: includeAsin ? (asin ?? _faker.Random.String2(10)) : null,
|
||||
MusicBrainzReleaseId: includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null,
|
||||
MusicBrainzReleaseGroupId: includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null,
|
||||
MusicBrainzReleaseArtistId: includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null,
|
||||
Contributors: includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Ratings: includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="UpdateMusicAlbumRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="UpdateMusicAlbumRequest"/> instances.</returns>
|
||||
public List<UpdateMusicAlbumRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetMusicArtistViewRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicArtistViewRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetMusicArtistViewRequest"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="artistId">Optional unique identifier of the artist to retrieve.</param>
|
||||
/// <param name="libraryId">Optional unique identifier of the media library the artist belongs to.</param>
|
||||
/// <returns>A configured <see cref="GetMusicArtistViewRequest"/> instance.</returns>
|
||||
public GetMusicArtistViewRequest Create(
|
||||
string? artistId = null,
|
||||
Guid? libraryId = null)
|
||||
{
|
||||
return new GetMusicArtistViewRequest(
|
||||
artistId ?? Guid.NewGuid().ToString(),
|
||||
libraryId ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetMusicArtistViewRequest"/> instances.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetMusicArtistViewRequest"/> instances.</returns>
|
||||
public List<GetMusicArtistViewRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Enums.Common;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetMusicArtistsLiteRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicArtistsLiteRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetMusicArtistsLiteRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional Id of the media library whose artists are retrieved.</param>
|
||||
/// <param name="currentPage">Optional page of results to retrieve.</param>
|
||||
/// <param name="perPage">Optional maximum number of artists to retrieve per page.</param>
|
||||
/// <param name="searchTerm">Optional search term used to filter the artists by name.</param>
|
||||
/// <param name="filterAlphaKey">Optional alpha key used to filter the results by the first character of their name.</param>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Optional whether the leading prefix of a name is ignored when computing the alpha key.</param>
|
||||
/// <param name="sortBy">Optional name of the field by which to sort the results.</param>
|
||||
/// <param name="sortOrder">Optional direction in which to sort the results.</param>
|
||||
/// <param name="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePerPage">Whether the per page count should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeSearchTerm">Whether the search term should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeFilterAlphaKey">Whether the alpha key should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeSortBy">Whether the sort field should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeSortOrder">Whether the sort order should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="GetMusicArtistsLiteRequest"/> instance.</returns>
|
||||
public GetMusicArtistsLiteRequest Create(
|
||||
Guid? libraryId = null,
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
string? searchTerm = null,
|
||||
string? filterAlphaKey = null,
|
||||
bool shouldIgnoreThePrefixForAlphaPicker = false,
|
||||
string? sortBy = null,
|
||||
SortOrder? sortOrder = null,
|
||||
bool includeCurrentPage = true,
|
||||
bool includePerPage = true,
|
||||
bool includeSearchTerm = true,
|
||||
bool includeFilterAlphaKey = true,
|
||||
bool includeSortBy = true,
|
||||
bool includeSortOrder = true)
|
||||
{
|
||||
return new GetMusicArtistsLiteRequest(
|
||||
LibraryId: libraryId ?? _faker.Random.Guid(),
|
||||
CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Int(1, 100)) : null,
|
||||
PerPage: includePerPage ? (perPage ?? _faker.Random.Int(1, 100)) : null,
|
||||
SearchTerm: includeSearchTerm ? (searchTerm ?? _faker.Lorem.Word()) : null,
|
||||
FilterAlphaKey: includeFilterAlphaKey ? (filterAlphaKey ?? _faker.Random.String2(1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")) : null,
|
||||
ShouldIgnoreThePrefixForAlphaPicker: shouldIgnoreThePrefixForAlphaPicker,
|
||||
SortBy: includeSortBy ? (sortBy ?? _faker.Lorem.Word()) : null,
|
||||
SortOrder: includeSortOrder ? (sortOrder ?? _faker.PickRandom<SortOrder>()) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetMusicArtistsLiteRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetMusicArtistsLiteRequest"/> instances.</returns>
|
||||
public List<GetMusicArtistsLiteRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetMusicArtistsViewRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicArtistsViewRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetMusicArtistsViewRequest"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional unique identifier of the media library whose artists are browsed.</param>
|
||||
/// <returns>A configured <see cref="GetMusicArtistsViewRequest"/> instance.</returns>
|
||||
public GetMusicArtistsViewRequest Create(
|
||||
Guid? libraryId = null)
|
||||
{
|
||||
return new GetMusicArtistsViewRequest(
|
||||
LibraryId: libraryId
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetMusicArtistsViewRequest"/> instances.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetMusicArtistsViewRequest"/> instances.</returns>
|
||||
public List<GetMusicArtistsViewRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
|
||||
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateMusicArtistAlbumRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateMusicArtistAlbumRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
private readonly UpdateMusicArtistTrackRequestFixture _updateMusicArtistTrackRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="UpdateMusicArtistAlbumRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="albumId">Optional. The Id of the album, when the album already exists.</param>
|
||||
/// <param name="metadata">Optional. The album metadata of the album.</param>
|
||||
/// <param name="mediaFormat">Optional. The physical or digital medium of the album.</param>
|
||||
/// <param name="packaging">Optional. The outermost physical packaging of the album.</param>
|
||||
/// <param name="barcode">Optional. The barcode of the album.</param>
|
||||
/// <param name="catalogNumbers">Optional. The catalog numbers of the album.</param>
|
||||
/// <param name="label">Optional. The name of the label that issued the album.</param>
|
||||
/// <param name="asin">Optional. The ASIN 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 references to the media contributors that performed on the album.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the album.</param>
|
||||
/// <param name="tracks">Optional. The tracks of the album.</param>
|
||||
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMetadata">Whether the metadata should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaFormat">Whether the media format should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePackaging">Whether the packaging should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeBarcode">Whether the barcode should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeCatalogNumbers">Whether the catalog numbers should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLabel">Whether the label should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeAsin">Whether the ASIN should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzReleaseId">Whether the MusicBrainz release Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzReleaseGroupId">Whether the MusicBrainz release group Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzReleaseArtistId">Whether the MusicBrainz release artist Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeContributors">Whether the contributors should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeRatings">Whether the ratings should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeTracks">Whether the tracks should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="UpdateMusicArtistAlbumRequest"/> instance.</returns>
|
||||
public UpdateMusicArtistAlbumRequest Create(
|
||||
Guid? albumId = null,
|
||||
MusicAlbumMetadataDto? metadata = null,
|
||||
MusicMediaFormat? mediaFormat = null,
|
||||
MusicReleasePackaging? packaging = null,
|
||||
string? barcode = null,
|
||||
List<string>? catalogNumbers = null,
|
||||
string? label = null,
|
||||
string? asin = null,
|
||||
Guid? musicBrainzReleaseId = null,
|
||||
Guid? musicBrainzReleaseGroupId = null,
|
||||
Guid? musicBrainzReleaseArtistId = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
List<UpdateMusicArtistTrackRequest>? tracks = null,
|
||||
bool includeAlbumId = true,
|
||||
bool includeMetadata = true,
|
||||
bool includeMediaFormat = true,
|
||||
bool includePackaging = true,
|
||||
bool includeBarcode = true,
|
||||
bool includeCatalogNumbers = true,
|
||||
bool includeLabel = true,
|
||||
bool includeAsin = true,
|
||||
bool includeMusicBrainzReleaseId = true,
|
||||
bool includeMusicBrainzReleaseGroupId = true,
|
||||
bool includeMusicBrainzReleaseArtistId = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true,
|
||||
bool includeTracks = true)
|
||||
{
|
||||
return new UpdateMusicArtistAlbumRequest(
|
||||
AlbumId: includeAlbumId ? (albumId ?? _faker.Random.Guid()) : null,
|
||||
Metadata: includeMetadata ? (metadata ?? _musicAlbumMetadataDtoFixture.Create()) : null,
|
||||
MediaFormat: includeMediaFormat ? (mediaFormat ?? _faker.PickRandom<MusicMediaFormat>()) : null,
|
||||
Packaging: includePackaging ? (packaging ?? _faker.PickRandom<MusicReleasePackaging>()) : null,
|
||||
Barcode: includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null,
|
||||
CatalogNumbers: includeCatalogNumbers ? (catalogNumbers ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 3)).Select(_ => _faker.Random.String2(10))]) : null,
|
||||
Label: includeLabel ? (label ?? _faker.Company.CompanyName()) : null,
|
||||
ASIN: includeAsin ? (asin ?? _faker.Random.String2(10)) : null,
|
||||
MusicBrainzReleaseId: includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null,
|
||||
MusicBrainzReleaseGroupId: includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null,
|
||||
MusicBrainzReleaseArtistId: includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null,
|
||||
Contributors: includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Ratings: includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Tracks: includeTracks ? (tracks ?? [.. _updateMusicArtistTrackRequestFixture.CreateMany(_faker.Random.Number(1, 3))]) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="UpdateMusicArtistAlbumRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="UpdateMusicArtistAlbumRequest"/> instances.</returns>
|
||||
public List<UpdateMusicArtistAlbumRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateMusicArtistRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateMusicArtistRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
private readonly UpdateMusicArtistAlbumRequestFixture _updateMusicArtistAlbumRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="UpdateMusicArtistRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="metadata">Optional. The metadata 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="ipis">Optional. The IPI codes of the artist.</param>
|
||||
/// <param name="isnis">Optional. The ISNI codes of the artist.</param>
|
||||
/// <param name="contributors">Optional. The references to the media contributors that make up the artist.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the artist.</param>
|
||||
/// <param name="albums">Optional. The albums of the artist, each with its own list of tracks.</param>
|
||||
/// <param name="includeMetadata">Whether the metadata should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeWebsite">Whether the website should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzArtistId">Whether the MusicBrainz artist Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeIpis">Whether the IPI codes should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeIsnis">Whether the ISNI codes should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeContributors">Whether the contributors should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeRatings">Whether the ratings should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeAlbums">Whether the albums should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="UpdateMusicArtistRequest"/> instance.</returns>
|
||||
public UpdateMusicArtistRequest Create(
|
||||
MusicArtistMetadataDto? metadata = null,
|
||||
string? website = null,
|
||||
Guid? musicBrainzArtistId = null,
|
||||
List<string>? ipis = null,
|
||||
List<string>? isnis = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
List<UpdateMusicArtistAlbumRequest>? albums = null,
|
||||
bool includeMetadata = true,
|
||||
bool includeWebsite = true,
|
||||
bool includeMusicBrainzArtistId = true,
|
||||
bool includeIpis = true,
|
||||
bool includeIsnis = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true,
|
||||
bool includeAlbums = true)
|
||||
{
|
||||
return new UpdateMusicArtistRequest(
|
||||
Metadata: includeMetadata ? (metadata ?? _musicArtistMetadataDtoFixture.Create()) : null,
|
||||
Website: includeWebsite ? (website ?? _faker.Internet.Url()) : null,
|
||||
MusicBrainzArtistId: includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null,
|
||||
Ipis: includeIpis ? (ipis ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 3)).Select(_ => _faker.Random.String2(10, "0123456789"))]) : null,
|
||||
Isnis: includeIsnis ? (isnis ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 3)).Select(_ => _faker.Random.String2(16, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"))]) : null,
|
||||
Contributors: includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Ratings: includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Albums: includeAlbums ? (albums ?? [.. _updateMusicArtistAlbumRequestFixture.CreateMany(_faker.Random.Number(1, 3))]) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="UpdateMusicArtistRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="UpdateMusicArtistRequest"/> instances.</returns>
|
||||
public List<UpdateMusicArtistRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
|
||||
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateMusicArtistTrackRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateMusicArtistTrackRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new();
|
||||
private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new();
|
||||
private readonly MoodDtoFixture _moodDtoFixture = new();
|
||||
private readonly IsrcDtoFixture _isrcDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="UpdateMusicArtistTrackRequest"/> instance with randomized test data.
|
||||
/// </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 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="moods">Optional. The moods of the track.</param>
|
||||
/// <param name="isrcs">Optional. The ISRC codes of the track.</param>
|
||||
/// <param name="contributors">Optional. The references to 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="includeDiscNumber">Whether the disc number should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeScript">Whether the script should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeKey">Whether the key should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeBpm">Whether the BPM should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeWork">Whether the work should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzRecordingId">Whether the MusicBrainz recording Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzTrackId">Whether the MusicBrainz track Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMoods">Whether the moods should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeIsrcs">Whether the ISRC codes should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeContributors">Whether the contributors 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>A configured <see cref="UpdateMusicArtistTrackRequest"/> instance.</returns>
|
||||
public UpdateMusicArtistTrackRequest Create(
|
||||
Guid? trackId = null,
|
||||
string? path = null,
|
||||
MusicTrackMetadataDto? metadata = null,
|
||||
int? trackNumber = null,
|
||||
int? discNumber = null,
|
||||
string? script = null,
|
||||
MusicKey? key = null,
|
||||
int? bpm = null,
|
||||
MusicWorkDto? work = null,
|
||||
Guid? musicBrainzRecordingId = null,
|
||||
Guid? musicBrainzTrackId = 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 includeDiscNumber = true,
|
||||
bool includeScript = true,
|
||||
bool includeKey = true,
|
||||
bool includeBpm = true,
|
||||
bool includeWork = true,
|
||||
bool includeMusicBrainzRecordingId = true,
|
||||
bool includeMusicBrainzTrackId = true,
|
||||
bool includeMoods = true,
|
||||
bool includeIsrcs = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true)
|
||||
{
|
||||
return new UpdateMusicArtistTrackRequest(
|
||||
TrackId: includeTrackId ? (trackId ?? _faker.Random.Guid()) : null,
|
||||
Path: includePath ? (path ?? _faker.System.FilePath()) : null,
|
||||
Metadata: includeMetadata ? (metadata ?? _musicTrackMetadataDtoFixture.Create()) : null,
|
||||
TrackNumber: includeTrackNumber ? (trackNumber ?? _faker.Random.Number(1, 30)) : null,
|
||||
DiscNumber: includeDiscNumber ? (discNumber ?? _faker.Random.Number(1, 4)) : null,
|
||||
Script: includeScript ? (script ?? _faker.Lorem.Word()) : null,
|
||||
Key: includeKey ? (key ?? _faker.PickRandom<MusicKey>()) : null,
|
||||
Bpm: includeBpm ? (bpm ?? _faker.Random.Number(60, 200)) : null,
|
||||
Work: includeWork ? (work ?? _musicWorkDtoFixture.Create()) : null,
|
||||
MusicBrainzRecordingId: includeMusicBrainzRecordingId ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null,
|
||||
MusicBrainzTrackId: includeMusicBrainzTrackId ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null,
|
||||
Moods: includeMoods ? (moods ?? [.. _moodDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Isrcs: includeIsrcs ? (isrcs ?? [.. _isrcDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Contributors: includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Ratings: includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="UpdateMusicArtistTrackRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="UpdateMusicArtistTrackRequest"/> instances.</returns>
|
||||
public List<UpdateMusicArtistTrackRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetAlbumTracksLiteRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksLiteRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetAlbumTracksLiteRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="artistId">Optional Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">Optional Id of the album whose tracks are retrieved.</param>
|
||||
/// <param name="libraryId">Optional Id of the media library the album belongs to.</param>
|
||||
/// <param name="currentPage">Optional page of results to retrieve.</param>
|
||||
/// <param name="perPage">Optional maximum number of tracks to retrieve per page.</param>
|
||||
/// <returns>A configured <see cref="GetAlbumTracksLiteRequest"/> instance.</returns>
|
||||
public GetAlbumTracksLiteRequest Create(
|
||||
string? artistId = null,
|
||||
string? albumId = null,
|
||||
Guid? libraryId = null,
|
||||
int? currentPage = null,
|
||||
int? perPage = null)
|
||||
{
|
||||
return new GetAlbumTracksLiteRequest(
|
||||
ArtistId: artistId ?? Guid.NewGuid().ToString(),
|
||||
AlbumId: albumId ?? Guid.NewGuid().ToString(),
|
||||
LibraryId: libraryId ?? Guid.NewGuid(),
|
||||
CurrentPage: currentPage,
|
||||
PerPage: perPage
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetAlbumTracksLiteRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetAlbumTracksLiteRequest"/> instances.</returns>
|
||||
public List<GetAlbumTracksLiteRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetMusicTrackViewRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicTrackViewRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetMusicTrackViewRequest"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="artistId">Optional unique identifier of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">Optional unique identifier of the album the track belongs to.</param>
|
||||
/// <param name="trackId">Optional unique identifier of the track to retrieve.</param>
|
||||
/// <param name="libraryId">Optional unique identifier of the media library the track belongs to.</param>
|
||||
/// <returns>A configured <see cref="GetMusicTrackViewRequest"/> instance.</returns>
|
||||
public GetMusicTrackViewRequest Create(
|
||||
string? artistId = null,
|
||||
string? albumId = null,
|
||||
string? trackId = null,
|
||||
Guid? libraryId = null)
|
||||
{
|
||||
return new GetMusicTrackViewRequest(
|
||||
artistId ?? Guid.NewGuid().ToString(),
|
||||
albumId ?? Guid.NewGuid().ToString(),
|
||||
trackId ?? Guid.NewGuid().ToString(),
|
||||
libraryId ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetMusicTrackViewRequest"/> instances.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetMusicTrackViewRequest"/> instances.</returns>
|
||||
public List<GetMusicTrackViewRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
|
||||
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateMusicTrackRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateMusicTrackRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new();
|
||||
private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new();
|
||||
private readonly MoodDtoFixture _moodDtoFixture = new();
|
||||
private readonly IsrcDtoFixture _isrcDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="UpdateMusicTrackRequest"/> instance with randomized test data.
|
||||
/// </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 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="moods">Optional. The moods of the track.</param>
|
||||
/// <param name="isrcs">Optional. The ISRC codes of the track.</param>
|
||||
/// <param name="contributors">Optional. The references to the media contributors that performed on the track.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the 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="includeDiscNumber">Whether the disc number should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeScript">Whether the script should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeKey">Whether the key should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeBpm">Whether the BPM should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeWork">Whether the work should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzRecordingId">Whether the MusicBrainz recording Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzTrackId">Whether the MusicBrainz track Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMoods">Whether the moods should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeIsrcs">Whether the ISRC codes should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeContributors">Whether the contributors 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>A configured <see cref="UpdateMusicTrackRequest"/> instance.</returns>
|
||||
public UpdateMusicTrackRequest Create(
|
||||
string? path = null,
|
||||
MusicTrackMetadataDto? metadata = null,
|
||||
int? trackNumber = null,
|
||||
int? discNumber = null,
|
||||
string? script = null,
|
||||
MusicKey? key = null,
|
||||
int? bpm = null,
|
||||
MusicWorkDto? work = null,
|
||||
Guid? musicBrainzRecordingId = null,
|
||||
Guid? musicBrainzTrackId = 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 includeDiscNumber = true,
|
||||
bool includeScript = true,
|
||||
bool includeKey = true,
|
||||
bool includeBpm = true,
|
||||
bool includeWork = true,
|
||||
bool includeMusicBrainzRecordingId = true,
|
||||
bool includeMusicBrainzTrackId = true,
|
||||
bool includeMoods = true,
|
||||
bool includeIsrcs = true,
|
||||
bool includeContributors = true,
|
||||
bool includeRatings = true)
|
||||
{
|
||||
return new UpdateMusicTrackRequest(
|
||||
Path: includePath ? (path ?? _faker.System.FilePath()) : null,
|
||||
Metadata: includeMetadata ? (metadata ?? _musicTrackMetadataDtoFixture.Create()) : null,
|
||||
TrackNumber: includeTrackNumber ? (trackNumber ?? _faker.Random.Number(1, 30)) : null,
|
||||
DiscNumber: includeDiscNumber ? (discNumber ?? _faker.Random.Number(1, 4)) : null,
|
||||
Script: includeScript ? (script ?? _faker.Lorem.Word()) : null,
|
||||
Key: includeKey ? (key ?? _faker.PickRandom<MusicKey>()) : null,
|
||||
Bpm: includeBpm ? (bpm ?? _faker.Random.Number(60, 200)) : null,
|
||||
Work: includeWork ? (work ?? _musicWorkDtoFixture.Create()) : null,
|
||||
MusicBrainzRecordingId: includeMusicBrainzRecordingId ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null,
|
||||
MusicBrainzTrackId: includeMusicBrainzTrackId ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null,
|
||||
Moods: includeMoods ? (moods ?? [.. _moodDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Isrcs: includeIsrcs ? (isrcs ?? [.. _isrcDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Contributors: includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null,
|
||||
Ratings: includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))]) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="UpdateMusicTrackRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="UpdateMusicTrackRequest"/> instances.</returns>
|
||||
public List<UpdateMusicTrackRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteMusicAlbumEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicAlbum_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardDeleteAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId, albumId, libraryId);
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicAlbum_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId, albumId, libraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicAlbum_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete request for the album identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album to delete.</param>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <returns>The configured delete request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(Guid artistId, Guid albumId, Guid libraryId)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-delete-album?libraryId={libraryId}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.EditMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.EditMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="EditMusicAlbumViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EditMusicAlbumViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EditMusicAlbumViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public EditMusicAlbumViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditMusicAlbum_WhenCalledByAuthenticatedUser_ShouldRenderEditAlbumPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create();
|
||||
expectedAlbum.Metadata!.Title = "An album";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{expectedAlbum.LibraryId}/artists/{expectedAlbum.ArtistId}/albums/{expectedAlbum.Id}", expectedAlbum);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{expectedAlbum.ArtistId}/albums/{expectedAlbum.Id}?libraryId={expectedAlbum.LibraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("An album", content);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetArtistAlbums;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetArtistAlbums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetArtistAlbumsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetArtistAlbumsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedMusicAlbumLiteDtoFixture _paginatedMusicAlbumLiteDtoFixture = new();
|
||||
private readonly MusicAlbumLiteDtoFixture _musicAlbumLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetArtistAlbumsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetArtistAlbumsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbums_WhenCalledByAuthenticatedUser_ShouldReturnAlbumsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
PaginatedMusicAlbumLiteDto expectedResponse = _paginatedMusicAlbumLiteDtoFixture.Create(data: [_musicAlbumLiteDtoFixture.Create(title: "Test Album")]);
|
||||
string expectedEndpoint = $"libraries/{libraryId}/artists/{artistId}/albums/lite?currentPage=1&perPage=20";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedResponse);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/api-get-albums?libraryId={libraryId}¤tPage=1&perPage=20");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedResponse.Data.Count, json.RootElement.GetProperty("data").GetProperty("data").GetArrayLength());
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbums_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/api-get-albums?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMusicAlbumEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicAlbum_WhenCalledByAuthenticatedUser_ShouldReturnAlbumFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", expectedAlbum);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-get-album?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(albumId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicAlbum_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/api-get-album?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.SaveMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.SaveMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SaveMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicAlbumRequestFixture _updateMusicAlbumRequestFixture = new();
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SaveMusicAlbumEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicAlbum_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", expectedAlbum);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, albumId, libraryId, request);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(albumId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}" && putRequest.Data is UpdateMusicAlbumRequest forwarded && forwarded.Metadata!.Title == request.Metadata!.Title && forwarded.ASIN == request.ASIN);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicAlbum_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, albumId, libraryId, request);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicAlbum_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), _updateMusicAlbumRequestFixture.Create());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that PUTs the given <paramref name="request"/> to the album identified by the route,
|
||||
/// with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album to save.</param>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="request">The album data to send.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(Guid artistId, Guid albumId, Guid libraryId, UpdateMusicAlbumRequest request)
|
||||
{
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-save-album?libraryId={libraryId}")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateAlbumCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly UpdateMusicCoverDtoFixture _updateMusicCoverDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdateAlbumCoverEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldUploadCoverAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/albums/cover.png";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", _updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId, albumId, libraryId, "cover.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, json.RootElement.GetProperty("data").GetString());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover" && putRequest.Data as string == "cover.png");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId, albumId, libraryId, "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenCalledWithoutUploadedFile_ShouldForwardRequestAndReturnFailure()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "AlbumCoverCannotBeNull");
|
||||
_apiFactory.ApiClientStub.RegisterPutException($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", new ApiException(problemDetails, HttpStatusCode.UnprocessableEntity, $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
MultipartFormDataContent noFileForm = [];
|
||||
noFileForm.Add(new StringContent("unrelated-field"));
|
||||
HttpRequestMessage uploadRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-update-cover?libraryId={libraryId}")
|
||||
{
|
||||
Content = noFileForm
|
||||
};
|
||||
uploadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The web does not short-circuit the missing file; it forwards the request, and the API reports the missing cover
|
||||
// with the same AlbumCoverCannotBeNull validation error any other client receives.
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover" && putRequest.Data == null);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the multipart PUT request that uploads a cover to the album identified by the route.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album whose cover is uploaded.</param>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>The configured upload request.</returns>
|
||||
private static HttpRequestMessage CreateUploadRequest(Guid artistId, Guid albumId, Guid libraryId, string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "cover", fileName);
|
||||
return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-update-cover?libraryId={libraryId}")
|
||||
{
|
||||
Content = form
|
||||
};
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteMusicArtistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicArtist_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardDeleteAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/artists/{artistId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId, libraryId);
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicArtist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId, libraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain($"libraries/{libraryId}/artists/{artistId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicArtist_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete request for the artist identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist to delete.</param>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <returns>The configured delete request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(Guid artistId, Guid libraryId)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/audio-library/music-library/artists/{artistId}/api-delete-artist?libraryId={libraryId}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.EditMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.EditMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="EditMusicArtistViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EditMusicArtistViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicArtistDtoFixture _musicArtistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EditMusicArtistViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public EditMusicArtistViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditMusicArtist_WhenCalledByAuthenticatedUser_ShouldRenderEditArtistPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create();
|
||||
expectedArtist.Metadata!.Name = "An artist";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{expectedArtist.LibraryId}/artists/{expectedArtist.Id}", expectedArtist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{expectedArtist.Id}?libraryId={expectedArtist.LibraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("An artist", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditMusicArtist_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicArtistDtoFixture _musicArtistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMusicArtistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicArtist_WhenCalledByAuthenticatedUser_ShouldReturnArtistFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create(id: artistId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}", expectedArtist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/{artistId}/api-get-artist?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(artistId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicArtist_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/api-get-artist?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMusicArtistsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicArtistsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedMusicArtistLiteDtoFixture _paginatedMusicArtistLiteDtoFixture = new();
|
||||
private readonly MusicArtistLiteDtoFixture _musicArtistLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicArtistsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMusicArtistsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicArtists_WhenCalledByAuthenticatedUser_ShouldReturnArtistsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
const string EXPECTED_ENDPOINT = "libraries/{0}/artists/lite?currentPage=1&perPage=20&shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(
|
||||
string.Format(EXPECTED_ENDPOINT, libraryId),
|
||||
_paginatedMusicArtistLiteDtoFixture.Create(data: [_musicArtistLiteDtoFixture.Create(name: "Test Artist")], currentPage: 1, perPage: 20, count: 1, numberOfPages: 1));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/api-get-artists?libraryId={libraryId}¤tPage=1&perPage=20&shouldIgnoreThePrefixForAlphaPicker=false");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(1, json.RootElement.GetProperty("data").GetProperty("currentPage").GetInt32());
|
||||
Assert.Contains(string.Format(EXPECTED_ENDPOINT, libraryId), _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicArtists_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/api-get-artists?libraryId={Guid.NewGuid()}&shouldIgnoreThePrefixForAlphaPicker=false");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.Index;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="MusicArtistsIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtistsIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtistsIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public MusicArtistsIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MusicArtistsIndex_WhenCalledByAuthenticatedUserWithLibraryId_ShouldRenderArtistsPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Music");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("search-input", content);
|
||||
Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MusicArtistsIndex_WhenCalledByAuthenticatedUserWithoutLibraryId_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/library/audio-library/music-library/artists");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("/en-us", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.SaveMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.SaveMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SaveMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicArtistRequestFixture _updateMusicArtistRequestFixture = new();
|
||||
private readonly MusicArtistDtoFixture _musicArtistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SaveMusicArtistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicArtist_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create(id: artistId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}", expectedArtist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, libraryId, request);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(artistId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}" && putRequest.Data is UpdateMusicArtistRequest forwarded && forwarded.Metadata!.Name == request.Metadata!.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicArtist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, libraryId, request);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicArtist_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(Guid.NewGuid(), Guid.NewGuid(), _updateMusicArtistRequestFixture.Create());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that PUTs the given <paramref name="request"/> to the artist identified by the route,
|
||||
/// with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist to save.</param>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="request">The artist data to send.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(Guid artistId, Guid libraryId, UpdateMusicArtistRequest request)
|
||||
{
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/api-save-artist?libraryId={libraryId}")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateArtistCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateArtistCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicCoverDtoFixture _updateMusicCoverDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdateArtistCoverEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldUploadCoverAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/artists/cover.png";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/cover", _updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId, libraryId, "cover.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, json.RootElement.GetProperty("data").GetString());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/cover" && putRequest.Data as string == "cover.png");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId, libraryId, "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/cover");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenCalledWithoutUploadedFile_ShouldForwardRequestAndReturnFailure()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/cover", _updateMusicCoverDtoFixture.Create(includeCoverPath: false));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
MultipartFormDataContent noFileForm = [];
|
||||
noFileForm.Add(new StringContent("unrelated-field"));
|
||||
HttpRequestMessage uploadRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/api-update-cover?libraryId={libraryId}")
|
||||
{
|
||||
Content = noFileForm
|
||||
};
|
||||
uploadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
// The web does not short-circuit the missing file; it forwards the request without a file, so that the upstream API reports it.
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/cover" && putRequest.Data == null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid(), Guid.NewGuid(), "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the multipart PUT request that uploads a cover to the artist identified by the route.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist whose cover is uploaded.</param>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>The configured upload request.</returns>
|
||||
private static HttpRequestMessage CreateUploadRequest(Guid artistId, Guid libraryId, string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "cover", fileName);
|
||||
return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/api-update-cover?libraryId={libraryId}")
|
||||
{
|
||||
Content = form
|
||||
};
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteMusicTrackEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicTrack_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardDeleteAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId, albumId, trackId, libraryId);
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicTrack_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId, albumId, trackId, libraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicTrack_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete request for the track identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the track belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The route Id of the track to delete.</param>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <returns>The configured delete request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(Guid artistId, Guid albumId, Guid trackId, Guid libraryId)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-delete-track?libraryId={libraryId}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.EditMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.EditMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="EditMusicTrackViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EditMusicTrackViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EditMusicTrackViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public EditMusicTrackViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditMusicTrack_WhenCalledByAuthenticatedUser_ShouldRenderEditTrackPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId);
|
||||
expectedTrack.Metadata!.Title = "A track";
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", expectedTrack);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", expectedAlbum);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("A track", content);
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditMusicTrack_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetAlbumTracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetAlbumTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAlbumTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedMusicTrackLiteDtoFixture _paginatedMusicTrackLiteDtoFixture = new();
|
||||
private readonly MusicTrackLiteDtoFixture _musicTrackLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetAlbumTracksEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenCalledByAuthenticatedUser_ShouldReturnTracksFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
PaginatedMusicTrackLiteDto expectedResponse = _paginatedMusicTrackLiteDtoFixture.Create(data: [_musicTrackLiteDtoFixture.Create(title: "Test Track")]);
|
||||
string expectedEndpoint = $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite?currentPage=1&perPage=20";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedResponse);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/api-get-tracks?libraryId={libraryId}¤tPage=1&perPage=20");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedResponse.Data.Count, json.RootElement.GetProperty("data").GetProperty("data").GetArrayLength());
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/api-get-tracks?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMusicTrackEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicTrack_WhenCalledByAuthenticatedUser_ShouldReturnTrackFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", expectedTrack);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-track?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(trackId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicTrack_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/api-get-track?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.SaveMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.SaveMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SaveMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicTrackRequestFixture _updateMusicTrackRequestFixture = new();
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SaveMusicTrackEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicTrack_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", expectedTrack);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, albumId, trackId, libraryId, request);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(trackId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" && putRequest.Data is UpdateMusicTrackRequest forwarded && forwarded.Metadata!.Title == request.Metadata!.Title && forwarded.Path == request.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicTrack_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, albumId, trackId, libraryId, request);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicTrack_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), _updateMusicTrackRequestFixture.Create());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that PUTs the given <paramref name="request"/> to the track identified by the route,
|
||||
/// with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the track belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The route Id of the track to save.</param>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="request">The track data to send.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(Guid artistId, Guid albumId, Guid trackId, Guid libraryId, UpdateMusicTrackRequest request)
|
||||
{
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-save-track?libraryId={libraryId}")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="DeleteMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteMusicAlbumEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task DeleteMusicAlbum_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverDeleteAnotherAlbum(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(maliciousId, maliciousId, libraryId.ToString());
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicAlbum_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId.ToString(), albumId.ToString(), libraryId.ToString());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicAlbum_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete request for the album identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
/// <returns>The configured delete request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(string artistId, string albumId, string libraryId)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/albums/{Uri.EscapeDataString(albumId)}/api-delete-album?libraryId={Uri.EscapeDataString(libraryId)}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.EditMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.EditMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="EditMusicAlbumViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EditMusicAlbumViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EditMusicAlbumViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public EditMusicAlbumViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditMusicAlbum_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetArtistAlbums;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
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.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetArtistAlbums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetArtistAlbumsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetArtistAlbumsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedMusicAlbumLiteDtoFixture _paginatedMusicAlbumLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetArtistAlbumsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetArtistAlbumsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbums_WhenCalledWithoutAuthentication_ShouldRedirectToLoginWithoutCallingApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/api-get-albums?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task GetArtistAlbums_WithSQLInjectionInArtistId_ShouldNormalizeTheIdWithoutLeakingData(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/lite", _paginatedMusicAlbumLiteDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(maliciousId)}/albums/api-get-albums?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using (JsonDocument json = JsonDocument.Parse(content))
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousId, content, StringComparison.Ordinal);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}/artists/{normalizedId}/albums/lite");
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
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.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMusicAlbumEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicAlbum_WhenCalledWithoutAuthentication_ShouldRedirectToLoginWithoutCallingApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/api-get-album?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task GetMusicAlbum_WithSQLInjectionInRouteId_ShouldNormalizeTheIdWithoutLeakingData(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}", expectedAlbum);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(maliciousId)}/albums/{Uri.EscapeDataString(maliciousId)}/api-get-album?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The route values are normalized to Guids before they are substituted into the upstream URL, so a crafted route value can never escape
|
||||
// its URL segment or reach a different album lookup; the Web layer must not fail local binding, leak stack traces or database details.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using (JsonDocument json = JsonDocument.Parse(content))
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousId, content, StringComparison.Ordinal);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}");
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.SaveMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.SaveMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="SaveMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicAlbumRequestFixture _updateMusicAlbumRequestFixture = new();
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SaveMusicAlbumEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task SaveMusicAlbum_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverCallAnotherAlbum(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}", _musicAlbumDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(maliciousId, maliciousId, libraryId.ToString(), _updateMusicAlbumRequestFixture.Create());
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The route is authoritative and its values are normalized to Guids before they are substituted into the upstream URL, so a crafted
|
||||
// route value can never escape its URL segment or redirect the update to another album, and the response must not leak stack traces
|
||||
// or database details.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task SaveMusicAlbum_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}", _musicAlbumDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId.ToString(), albumId.ToString(), maliciousLibraryId, _updateMusicAlbumRequestFixture.Create());
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task SaveMusicAlbum_WithSQLInjectionInPostedTitle_ShouldNotLeakOrExecuteIt(string maliciousTitle)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
request.Metadata!.Title = maliciousTitle;
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create(id: albumId);
|
||||
expectedAlbum.Metadata!.Title = maliciousTitle;
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", expectedAlbum);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId.ToString(), albumId.ToString(), libraryId.ToString(), request);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}" && putRequest.Data is UpdateMusicAlbumRequest forwarded && forwarded.Metadata!.Title == maliciousTitle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicAlbum_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId.ToString(), albumId.ToString(), libraryId.ToString(), _updateMusicAlbumRequestFixture.Create());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicAlbum_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), _updateMusicAlbumRequestFixture.Create());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that PUTs the given <paramref name="request"/> to the album identified by the route,
|
||||
/// with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
/// <param name="request">The album data to send.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(string artistId, string albumId, string libraryId, UpdateMusicAlbumRequest request)
|
||||
{
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/albums/{Uri.EscapeDataString(albumId)}/api-save-album?libraryId={Uri.EscapeDataString(libraryId)}")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="UpdateAlbumCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicCoverDtoFixture _updateMusicCoverDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdateAlbumCoverEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateAlbumCover_WithSQLInjectionInRouteId_ShouldNeverReachAnAlbumOrLeakData(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{Guid.Empty}/albums/{Guid.Empty}/cover", _updateMusicCoverDtoFixture.Create(coverPath: "/media/albums/cover.png"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(maliciousId, maliciousId, libraryId.ToString(), "cover.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The route is authoritative: an unparseable route value becomes an empty album or artist Id, so the upload can never reach a real album.
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{Guid.Empty}/albums/{Guid.Empty}/cover");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE MusicArtwork; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateAlbumCover_WithSQLInjectionInLibraryQueryId_ShouldNormalizeItAndNotLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{Guid.Empty}/artists/{artistId}/albums/{albumId}/cover", _updateMusicCoverDtoFixture.Create(coverPath: "/media/albums/cover.png"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId.ToString(), albumId.ToString(), maliciousLibraryId, "cover.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The library id is normalized to a Guid before it is substituted into the upstream URL, so a crafted value can never escape its URL segment.
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{Guid.Empty}/artists/{artistId}/albums/{albumId}/cover");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WithPathTraversalFileName_ShouldNotLeakData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", _updateMusicCoverDtoFixture.Create(coverPath: "/media/albums/cover.png"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId.ToString(), albumId.ToString(), libraryId.ToString(), "..\\..\\evil.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("..\\", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId.ToString(), albumId.ToString(), libraryId.ToString(), "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the multipart PUT request that uploads a cover to the album identified by the route.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>The configured upload request.</returns>
|
||||
private static HttpRequestMessage CreateUploadRequest(string artistId, string albumId, string libraryId, string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "cover", fileName);
|
||||
return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/albums/{Uri.EscapeDataString(albumId)}/api-update-cover?libraryId={Uri.EscapeDataString(libraryId)}")
|
||||
{
|
||||
Content = form
|
||||
};
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="DeleteMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteMusicArtistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Artists; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task DeleteMusicArtist_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverDeleteAnotherArtist(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/artists/{normalizedId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(maliciousId, libraryId.ToString());
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{normalizedId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicArtist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId.ToString(), libraryId.ToString());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicArtist_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete request for the artist identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
/// <returns>The configured delete request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(string artistId, string libraryId)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/api-delete-artist?libraryId={Uri.EscapeDataString(libraryId)}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.EditMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.EditMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="EditMusicArtistViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EditMusicArtistViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EditMusicArtistViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public EditMusicArtistViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditMusicArtist_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
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.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicArtistDtoFixture _musicArtistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMusicArtistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicArtist_WhenCalledWithoutAuthentication_ShouldRedirectToLoginWithoutCallingApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/api-get-artist?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Artists; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task GetMusicArtist_WithSQLInjectionInRouteId_ShouldNormalizeTheIdWithoutLeakingData(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{normalizedId}", expectedArtist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(maliciousId)}/api-get-artist?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The route value is normalized to a Guid before it is substituted into the upstream URL, so a crafted route value can never escape
|
||||
// its URL segment or reach a different artist lookup; the Web layer must not fail local binding, leak stack traces or database details.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using (JsonDocument json = JsonDocument.Parse(content))
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousId, content, StringComparison.Ordinal);
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{normalizedId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetMusicArtistsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicArtistsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedMusicArtistLiteDtoFixture _paginatedMusicArtistLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicArtistsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMusicArtistsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicArtists_WhenCalledWithoutAuthentication_ShouldRedirectToLoginWithoutCallingApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/api-get-artists?libraryId={Guid.NewGuid()}&shouldIgnoreThePrefixForAlphaPicker=false");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Artists--")] // destructive SQL injection
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
public async Task GetMusicArtists_WhenCalledWithInjectionInSearchTerm_ShouldRemainSecure(string maliciousSearchTerm)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"libraries/{libraryId}/artists/lite?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}&shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _paginatedMusicArtistLiteDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/api-get-artists?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}&shouldIgnoreThePrefixForAlphaPicker=false");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousSearchTerm, content, StringComparison.Ordinal);
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Artists--")] // destructive SQL injection
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
public async Task GetMusicArtists_WhenCalledWithInjectionInFilterAlphaKey_ShouldRemainSecure(string maliciousAlphaKey)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"libraries/{libraryId}/artists/lite?filterAlphaKey={Uri.EscapeDataString(maliciousAlphaKey)}&shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _paginatedMusicArtistLiteDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/api-get-artists?libraryId={libraryId}&filterAlphaKey={Uri.EscapeDataString(maliciousAlphaKey)}&shouldIgnoreThePrefixForAlphaPicker=false");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousAlphaKey, content, StringComparison.Ordinal);
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Artists--")] // destructive SQL injection
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
public async Task GetMusicArtists_WhenCalledWithInjectionInSortBy_ShouldRemainSecure(string maliciousSortBy)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"libraries/{libraryId}/artists/lite?shouldIgnoreThePrefixForAlphaPicker=False&sortBy={Uri.EscapeDataString(maliciousSortBy)}";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _paginatedMusicArtistLiteDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/api-get-artists?libraryId={libraryId}&sortBy={Uri.EscapeDataString(maliciousSortBy)}&shouldIgnoreThePrefixForAlphaPicker=false");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousSortBy, content, StringComparison.Ordinal);
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.Index;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="MusicArtistsIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtistsIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtistsIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public MusicArtistsIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MusicArtistsIndex_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/en-us/library/audio-library/music-library/artists?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.Ordinal));
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.SaveMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.SaveMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="SaveMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicArtistRequestFixture _updateMusicArtistRequestFixture = new();
|
||||
private readonly MusicArtistDtoFixture _musicArtistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SaveMusicArtistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Artists; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task SaveMusicArtist_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverCallAnotherArtist(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{normalizedId}", _musicArtistDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(maliciousId, libraryId.ToString(), _updateMusicArtistRequestFixture.Create());
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The route is authoritative and its value is normalized to a Guid before it is substituted into the upstream URL, so a crafted
|
||||
// route value can never escape its URL segment or redirect the update to another artist, and the response must not leak stack traces
|
||||
// or database details.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{normalizedId}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Artists; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task SaveMusicArtist_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{normalizedId}/artists/{artistId}", _musicArtistDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId.ToString(), maliciousLibraryId, _updateMusicArtistRequestFixture.Create());
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{normalizedId}/artists/{artistId}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Artists; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task SaveMusicArtist_WithSQLInjectionInPostedName_ShouldNotLeakOrExecuteIt(string maliciousName)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
request.Metadata!.Name = maliciousName;
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create(id: artistId);
|
||||
expectedArtist.Metadata!.Name = maliciousName;
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}", expectedArtist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId.ToString(), libraryId.ToString(), request);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}" && putRequest.Data is UpdateMusicArtistRequest forwarded && forwarded.Metadata!.Name == maliciousName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicArtist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId.ToString(), libraryId.ToString(), _updateMusicArtistRequestFixture.Create());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicArtist_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), _updateMusicArtistRequestFixture.Create());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that PUTs the given <paramref name="request"/> to the artist identified by the route,
|
||||
/// with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
/// <param name="request">The artist data to send.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(string artistId, string libraryId, UpdateMusicArtistRequest request)
|
||||
{
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/api-save-artist?libraryId={Uri.EscapeDataString(libraryId)}")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="UpdateArtistCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateArtistCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicCoverDtoFixture _updateMusicCoverDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdateArtistCoverEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Artists; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateArtistCover_WithSQLInjectionInRouteId_ShouldNeverReachAnArtistOrLeakData(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{Guid.Empty}/cover", _updateMusicCoverDtoFixture.Create(coverPath: "/media/artists/cover.png"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(maliciousId, libraryId.ToString(), "cover.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The route is authoritative: an unparseable route value becomes an empty artist Id, so the upload can never reach a real artist.
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{Guid.Empty}/cover");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE MusicArtwork; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateArtistCover_WithSQLInjectionInLibraryQueryId_ShouldNormalizeItAndNotLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{Guid.Empty}/artists/{artistId}/cover", _updateMusicCoverDtoFixture.Create(coverPath: "/media/artists/cover.png"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId.ToString(), maliciousLibraryId, "cover.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The library id is normalized to a Guid before it is substituted into the upstream URL, so a crafted value can never escape its URL segment.
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{Guid.Empty}/artists/{artistId}/cover");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WithPathTraversalFileName_ShouldNotLeakData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/cover", _updateMusicCoverDtoFixture.Create(coverPath: "/media/artists/cover.png"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId.ToString(), libraryId.ToString(), "..\\..\\evil.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("..\\", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId.ToString(), libraryId.ToString(), "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the multipart PUT request that uploads a cover to the artist identified by the route.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>The configured upload request.</returns>
|
||||
private static HttpRequestMessage CreateUploadRequest(string artistId, string libraryId, string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "cover", fileName);
|
||||
return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/api-update-cover?libraryId={Uri.EscapeDataString(libraryId)}")
|
||||
{
|
||||
Content = form
|
||||
};
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="DeleteMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteMusicTrackEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task DeleteMusicTrack_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverDeleteAnotherTrack(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(maliciousId, maliciousId, maliciousId, libraryId.ToString());
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task DeleteMusicTrack_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), maliciousLibraryId);
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicTrack_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId.ToString());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicTrack_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete request for the track identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="trackId">The raw route value of the track Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
/// <returns>The configured delete request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(string artistId, string albumId, string trackId, string libraryId)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/albums/{Uri.EscapeDataString(albumId)}/tracks/{Uri.EscapeDataString(trackId)}/api-delete-track?libraryId={Uri.EscapeDataString(libraryId)}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.EditMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.EditMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="EditMusicTrackViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EditMusicTrackViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EditMusicTrackViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public EditMusicTrackViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditMusicTrack_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task EditMusicTrack_WithSQLInjectionInRouteId_ShouldNormalizeTheIdWithoutLeakingData(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create();
|
||||
expectedTrack.Metadata!.Title = "A track";
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}", expectedTrack);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}", expectedAlbum);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(maliciousId)}/albums/{Uri.EscapeDataString(maliciousId)}/tracks/{Uri.EscapeDataString(maliciousId)}?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}");
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}");
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetAlbumTracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
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.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetAlbumTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetAlbumTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedMusicTrackLiteDtoFixture _paginatedMusicTrackLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetAlbumTracksEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenCalledWithoutAuthentication_ShouldRedirectToLoginWithoutCallingApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/api-get-tracks?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task GetAlbumTracks_WithSQLInjectionInArtistId_ShouldNormalizeTheIdWithoutLeakingData(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{albumId}/tracks/lite", _paginatedMusicTrackLiteDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(maliciousId)}/albums/{albumId}/tracks/api-get-tracks?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using (JsonDocument json = JsonDocument.Parse(content))
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousId, content, StringComparison.Ordinal);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}/artists/{normalizedId}/albums/{albumId}/tracks/lite");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task GetAlbumTracks_WithSQLInjectionInAlbumId_ShouldNormalizeTheIdWithoutLeakingData(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{normalizedId}/tracks/lite", _paginatedMusicTrackLiteDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{Uri.EscapeDataString(maliciousId)}/tracks/api-get-tracks?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using (JsonDocument json = JsonDocument.Parse(content))
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousId, content, StringComparison.Ordinal);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{normalizedId}/tracks/lite");
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
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.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMusicTrackEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicTrack_WhenCalledWithoutAuthentication_ShouldRedirectToLoginWithoutCallingApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/api-get-track?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task GetMusicTrack_WithSQLInjectionInRouteId_ShouldNormalizeTheIdWithoutLeakingData(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}", expectedTrack);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(maliciousId)}/albums/{Uri.EscapeDataString(maliciousId)}/tracks/{Uri.EscapeDataString(maliciousId)}/api-get-track?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The route values are normalized to Guids before they are substituted into the upstream URL, so a crafted route value can never escape
|
||||
// its URL segment or reach a different track lookup; the Web layer must not fail local binding, leak stack traces or database details.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using (JsonDocument json = JsonDocument.Parse(content))
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousId, content, StringComparison.Ordinal);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}");
|
||||
}
|
||||
}
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.SaveMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.SaveMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="SaveMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicTrackRequestFixture _updateMusicTrackRequestFixture = new();
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SaveMusicTrackEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task SaveMusicTrack_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverCallAnotherTrack(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}", _musicTrackDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(maliciousId, maliciousId, maliciousId, libraryId.ToString(), _updateMusicTrackRequestFixture.Create());
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The route is authoritative and its values are normalized to Guids before they are substituted into the upstream URL, so a crafted
|
||||
// route value can never escape its URL segment or redirect the update to another track, and the response must not leak stack traces
|
||||
// or database details.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task SaveMusicTrack_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", _musicTrackDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), maliciousLibraryId, _updateMusicTrackRequestFixture.Create());
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task SaveMusicTrack_WithSQLInjectionInPostedTitle_ShouldNotLeakOrExecuteIt(string maliciousTitle)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
request.Metadata!.Title = maliciousTitle;
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create(id: trackId);
|
||||
expectedTrack.Metadata!.Title = maliciousTitle;
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", expectedTrack);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId.ToString(), request);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" && putRequest.Data is UpdateMusicTrackRequest forwarded && forwarded.Metadata!.Title == maliciousTitle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicTrack_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId.ToString(), _updateMusicTrackRequestFixture.Create());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicTrack_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), _updateMusicTrackRequestFixture.Create());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that PUTs the given <paramref name="request"/> to the track identified by the route,
|
||||
/// with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="trackId">The raw route value of the track Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
/// <param name="request">The track data to send.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(string artistId, string albumId, string trackId, string libraryId, UpdateMusicTrackRequest request)
|
||||
{
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/albums/{Uri.EscapeDataString(albumId)}/tracks/{Uri.EscapeDataString(trackId)}/api-save-track?libraryId={Uri.EscapeDataString(libraryId)}")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicAlbumEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteMusicAlbumEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteMusicAlbumEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<DeleteMusicAlbumEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldDeleteAlbumViaApiAndReturnSuccessWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, albumId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out JsonElement _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", "not-a-guid", libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreMissing_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId, albumId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the album identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(artistId, albumId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the album identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the album deletion is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId)
|
||||
{
|
||||
return ApiRoutes.Music.DELETE_ALBUM
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString());
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetArtistAlbums;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetArtistAlbums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetArtistAlbumsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetArtistAlbumsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetArtistAlbumsEndpoint _sut;
|
||||
private readonly GetArtistAlbumsLiteRequestFixture _getArtistAlbumsLiteRequestFixture = new();
|
||||
private readonly PaginatedMusicAlbumLiteDtoFixture _paginatedMusicAlbumLiteDtoFixture = new();
|
||||
private readonly MusicAlbumLiteDtoFixture _musicAlbumLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetArtistAlbumsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetArtistAlbumsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetArtistAlbumsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithPagination_ShouldRequestAlbumsWithQueryParameters()
|
||||
{
|
||||
// Arrange
|
||||
GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(currentPage: 2, perPage: 48);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicAlbumLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicAlbumLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicAlbumLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId))}?currentPage=2&perPage=48"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithoutPagination_ShouldRequestAlbumsWithoutQueryParameters()
|
||||
{
|
||||
// Arrange
|
||||
GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicAlbumLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicAlbumLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicAlbumLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId))),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyCurrentPageIsProvided_ShouldAppendOnlyCurrentPage()
|
||||
{
|
||||
// Arrange
|
||||
GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(currentPage: 3);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicAlbumLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicAlbumLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicAlbumLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId))}?currentPage=3"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyPerPageIsProvided_ShouldAppendOnlyPerPage()
|
||||
{
|
||||
// Arrange
|
||||
GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(perPage: 24);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicAlbumLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicAlbumLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicAlbumLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId))}?perPage=24"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(artistId: "not-a-guid", currentPage: 1, perPage: 20);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicAlbumLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicAlbumLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicAlbumLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Empty)}?currentPage=1&perPage=20"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsPaginatedAlbums_ShouldReturnSuccessJsonWithAlbums()
|
||||
{
|
||||
// Arrange
|
||||
GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create();
|
||||
PaginatedMusicAlbumLiteDto expectedResponse = _paginatedMusicAlbumLiteDtoFixture.Create(
|
||||
data: [_musicAlbumLiteDtoFixture.Create(title: "Test Album")],
|
||||
currentPage: 1,
|
||||
perPage: 20,
|
||||
count: 1,
|
||||
numberOfPages: 1);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicAlbumLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = jsonDocument.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("data").GetArrayLength());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the artist album retrieval is expected to be sent to, without query parameters.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId)
|
||||
{
|
||||
return ApiRoutes.Music.GET_ARTIST_ALBUMS_LITE
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString());
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicAlbumEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetMusicAlbumEndpoint _sut;
|
||||
private readonly GetMusicAlbumViewRequestFixture _getMusicAlbumViewRequestFixture = new();
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetMusicAlbumEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetMusicAlbumEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestAlbumFromApiWithNormalizedIds()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicAlbumViewRequest request = _getMusicAlbumViewRequestFixture.Create();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<MusicAlbumDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedAlbum);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicAlbumDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Parse(request.AlbumId))),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicAlbumViewRequest request = _getMusicAlbumViewRequestFixture.Create(artistId: "not-a-guid", albumId: "' OR '1'='1");
|
||||
_mockApiHttpClient.GetAsync<MusicAlbumDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicAlbumDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicAlbumDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreEmpty_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicAlbumViewRequest request = _getMusicAlbumViewRequestFixture.Create(artistId: string.Empty, albumId: string.Empty);
|
||||
_mockApiHttpClient.GetAsync<MusicAlbumDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicAlbumDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicAlbumDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsAlbum_ShouldReturnSuccessJsonWithAlbum()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicAlbumViewRequest request = _getMusicAlbumViewRequestFixture.Create();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<MusicAlbumDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedAlbum);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedAlbum.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the album retrieval is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId)
|
||||
{
|
||||
return ApiRoutes.Music.GET_ALBUM
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString());
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.SaveMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.SaveMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SaveMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicAlbumEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly SaveMusicAlbumEndpoint _sut;
|
||||
private readonly UpdateMusicAlbumRequestFixture _updateMusicAlbumRequestFixture = new();
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public SaveMusicAlbumEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<SaveMusicAlbumEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldForwardUpdateMusicAlbumRequestToApiWithRouteAndQueryIds()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicAlbumRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedAlbum);
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, artistId, albumId)),
|
||||
Arg.Is<UpdateMusicAlbumRequest>(forwardedRequest => forwardedRequest == request),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
const string MALICIOUS_ARTIST_ID = "not-a-guid";
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicAlbumRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicAlbumDtoFixture.Create());
|
||||
ConfigureRequest(MALICIOUS_ARTIST_ID, albumId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, Guid.Empty, albumId)),
|
||||
Arg.Any<UpdateMusicAlbumRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAlbumRouteIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string MALICIOUS_ALBUM_ID = "' OR '1'='1";
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicAlbumRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicAlbumDtoFixture.Create());
|
||||
ConfigureRequest(artistId.ToString(), MALICIOUS_ALBUM_ID, libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, artistId, Guid.Empty)),
|
||||
Arg.Any<UpdateMusicAlbumRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreMissing_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicAlbumRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicAlbumDtoFixture.Create());
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<UpdateMusicAlbumRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string MALICIOUS_LIBRARY_ID = "not-a-guid";
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicAlbumRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicAlbumDtoFixture.Create());
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), MALICIOUS_LIBRARY_ID);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty, artistId, albumId)),
|
||||
Arg.Any<UpdateMusicAlbumRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsUpdatedAlbum_ShouldReturnSuccessJsonWithAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicAlbumRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedAlbum);
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedAlbum.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the album identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(artistId, albumId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the album identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the album update is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId)
|
||||
{
|
||||
return ApiRoutes.Music.UPDATE_ALBUM
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString());
|
||||
}
|
||||
}
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateAlbumCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumCoverEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly UpdateAlbumCoverEndpoint _sut;
|
||||
private readonly UpdateMusicCoverDtoFixture _updateMusicCoverDtoFixture = new();
|
||||
private static readonly Guid s_libraryId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateAlbumCoverEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<UpdateAlbumCoverEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithFile_ShouldUploadCoverToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/albums/cover.jpg"));
|
||||
ConfigureRequest(artistId, albumId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId, albumId)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Is<string>(fileName => fileName == "cover.jpg"),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldUploadCoverWithEmptyIds()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/albums/cover.jpg"));
|
||||
ConfigureRequest("not-a-guid", "not-a-guid", [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldUploadCoverWithEmptyLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/albums/cover.jpg"));
|
||||
ConfigureRequest(artistId, albumId, [1, 2, 3], "cover.jpg");
|
||||
// The query value is normalized to a Guid before it is substituted into the upstream URL, so a crafted value can never escape its segment.
|
||||
_sut.HttpContext.Request.QueryString = new QueryString("?libraryId=not-a-library-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty.ToString(), artistId, albumId)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldUploadCoverWithEmptyLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/albums/cover.jpg"));
|
||||
ConfigureRequest(artistId, albumId, [1, 2, 3], "cover.jpg");
|
||||
_sut.HttpContext.Request.QueryString = new QueryString(string.Empty);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty.ToString(), artistId, albumId)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsCoverPath_ShouldReturnSuccessJsonWithPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/albums/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
ConfigureRequest(artistId, albumId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFormHasNoFile_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/albums/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
ConfigureRequestWithoutFiles(artistId, albumId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId, albumId)),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRequestIsNotMultipart_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/albums/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
_sut.HttpContext.Request.ContentType = "application/json";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId, albumId)),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFormIsMalformed_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/albums/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
ConfigureMalformedRequest(artistId, albumId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId, albumId)),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request carrying a single file.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist.</param>
|
||||
/// <param name="albumId">The route Id of the album whose cover is uploaded.</param>
|
||||
/// <param name="content">The bytes of the uploaded file.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
private void ConfigureRequest(Guid artistId, Guid albumId, byte[] content, string fileName)
|
||||
{
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), content, fileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request carrying a single file.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="content">The bytes of the uploaded file.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, byte[] content, string fileName)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
MemoryStream coverStream = new(content);
|
||||
IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName);
|
||||
FormFileCollection files = [formFile];
|
||||
IFormCollection form = new FormCollection([], files);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request without any file.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist.</param>
|
||||
/// <param name="albumId">The route Id of the album whose cover is uploaded.</param>
|
||||
private void ConfigureRequestWithoutFiles(Guid artistId, Guid albumId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
IFormCollection form = new FormCollection([]);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request whose body cannot be parsed.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist.</param>
|
||||
/// <param name="albumId">The route Id of the album whose cover is uploaded.</param>
|
||||
private void ConfigureMalformedRequest(Guid artistId, Guid albumId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
IFormCollection malformedForm = Substitute.For<IFormCollection>();
|
||||
malformedForm.Files.Returns(_ => throw new InvalidDataException("Malformed multipart body."));
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(malformedForm));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the cover upload is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The raw Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(string libraryId, Guid artistId, Guid albumId)
|
||||
{
|
||||
return ApiRoutes.Music.UPDATE_ALBUM_COVER
|
||||
.Replace("{libraryId}", libraryId)
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString());
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicArtistEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteMusicArtistEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteMusicArtistEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<DeleteMusicArtistEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldDeleteArtistViaApiAndReturnSuccessWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), libraryId.ToString());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out JsonElement _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the artist identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the artist deletion is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId)
|
||||
{
|
||||
return ApiRoutes.Music.DELETE_ARTIST
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString());
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicArtistEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetMusicArtistEndpoint _sut;
|
||||
private readonly GetMusicArtistViewRequestFixture _getMusicArtistViewRequestFixture = new();
|
||||
private readonly MusicArtistDtoFixture _musicArtistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetMusicArtistEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetMusicArtistEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestArtistFromApiWithNormalizedIds()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicArtistViewRequest request = _getMusicArtistViewRequestFixture.Create();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<MusicArtistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedArtist);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicArtistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId))),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteArtistIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicArtistViewRequest request = _getMusicArtistViewRequestFixture.Create(artistId: "not-a-guid");
|
||||
_mockApiHttpClient.GetAsync<MusicArtistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicArtistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicArtistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Empty)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteArtistIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicArtistViewRequest request = _getMusicArtistViewRequestFixture.Create(artistId: string.Empty);
|
||||
_mockApiHttpClient.GetAsync<MusicArtistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicArtistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicArtistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Empty)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsArtist_ShouldReturnSuccessJsonWithArtist()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicArtistViewRequest request = _getMusicArtistViewRequestFixture.Create();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<MusicArtistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedArtist);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedArtist.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicArtistViewRequest request = _getMusicArtistViewRequestFixture.Create();
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
_mockApiHttpClient.GetAsync<MusicArtistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicArtistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicArtistDto>(
|
||||
Arg.Any<string>(),
|
||||
Arg.Is(cancellationTokenSource.Token));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the artist retrieval is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId)
|
||||
{
|
||||
return ApiRoutes.Music.GET_ARTIST
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString());
|
||||
}
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Enums.Common;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetMusicArtistsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicArtistsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetMusicArtistsEndpoint _sut;
|
||||
private readonly GetMusicArtistsLiteRequestFixture _getMusicArtistsLiteRequestFixture = new();
|
||||
private readonly PaginatedMusicArtistLiteDtoFixture _paginatedMusicArtistLiteDtoFixture = new();
|
||||
private readonly MusicArtistLiteDtoFixture _musicArtistLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicArtistsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetMusicArtistsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetMusicArtistsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithAllParameters_ShouldBuildExactQueryString()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
const string SEARCH_TERM = " The Beatles ";
|
||||
const string FILTER_ALPHA_KEY = "B";
|
||||
const string SORT_BY = "name asc";
|
||||
GetMusicArtistsLiteRequest request = _getMusicArtistsLiteRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
currentPage: 2,
|
||||
perPage: 48,
|
||||
searchTerm: SEARCH_TERM,
|
||||
filterAlphaKey: FILTER_ALPHA_KEY,
|
||||
shouldIgnoreThePrefixForAlphaPicker: true,
|
||||
sortBy: SORT_BY,
|
||||
sortOrder: SortOrder.Descending);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicArtistLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicArtistLiteDtoFixture.Create());
|
||||
string expectedEndpoint = $"{BuildExpectedEndpoint(libraryId)}?currentPage=2&perPage=48" +
|
||||
$"&searchTerm={Uri.EscapeDataString(SEARCH_TERM)}" +
|
||||
$"&filterAlphaKey={Uri.EscapeDataString(FILTER_ALPHA_KEY)}" +
|
||||
"&shouldIgnoreThePrefixForAlphaPicker=True" +
|
||||
$"&sortBy={Uri.EscapeDataString(SORT_BY)}" +
|
||||
"&sortOrder=Descending";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicArtistLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOptionalParametersAreOmitted_ShouldAppendOnlyTheIgnorePrefixFlag()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
GetMusicArtistsLiteRequest request = _getMusicArtistsLiteRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false,
|
||||
includeSearchTerm: false,
|
||||
includeFilterAlphaKey: false,
|
||||
includeSortBy: false,
|
||||
includeSortOrder: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicArtistLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicArtistLiteDtoFixture.Create());
|
||||
string expectedEndpoint = $"{BuildExpectedEndpoint(libraryId)}?shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicArtistLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSearchTermHasSpecialCharacters_ShouldEscapeIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
const string SEARCH_TERM = "rock & roll";
|
||||
GetMusicArtistsLiteRequest request = _getMusicArtistsLiteRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
searchTerm: SEARCH_TERM,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false,
|
||||
includeFilterAlphaKey: false,
|
||||
includeSortBy: false,
|
||||
includeSortOrder: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicArtistLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicArtistLiteDtoFixture.Create());
|
||||
string expectedEndpoint = $"{BuildExpectedEndpoint(libraryId)}?searchTerm={Uri.EscapeDataString(SEARCH_TERM)}&shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicArtistLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSearchTermAndAlphaKeyAndSortByAreWhitespace_ShouldOmitThem()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
GetMusicArtistsLiteRequest request = _getMusicArtistsLiteRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
searchTerm: " ",
|
||||
filterAlphaKey: " ",
|
||||
sortBy: string.Empty,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false,
|
||||
includeSortOrder: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicArtistLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicArtistLiteDtoFixture.Create());
|
||||
string expectedEndpoint = $"{BuildExpectedEndpoint(libraryId)}?shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicArtistLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyCurrentPageIsProvided_ShouldAppendOnlyCurrentPageAndTheIgnorePrefixFlag()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
GetMusicArtistsLiteRequest request = _getMusicArtistsLiteRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
currentPage: 3,
|
||||
includePerPage: false,
|
||||
includeSearchTerm: false,
|
||||
includeFilterAlphaKey: false,
|
||||
includeSortBy: false,
|
||||
includeSortOrder: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicArtistLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicArtistLiteDtoFixture.Create());
|
||||
string expectedEndpoint = $"{BuildExpectedEndpoint(libraryId)}?currentPage=3&shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicArtistLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsPaginatedArtists_ShouldReturnSuccessJsonWithArtists()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicArtistsLiteRequest request = _getMusicArtistsLiteRequestFixture.Create();
|
||||
PaginatedMusicArtistLiteDto expectedResponse = _paginatedMusicArtistLiteDtoFixture.Create(
|
||||
data: [_musicArtistLiteDtoFixture.Create(name: "Test Artist")],
|
||||
currentPage: 1,
|
||||
perPage: 20,
|
||||
count: 1,
|
||||
numberOfPages: 1);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicArtistLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = jsonDocument.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("data").GetArrayLength());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the artist retrieval is expected to be sent to, without query parameters.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose artists are retrieved.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId)
|
||||
{
|
||||
return ApiRoutes.Music.GET_ARTISTS_LITE.Replace("{libraryId}", libraryId.ToString());
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.Index;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicArtistsIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtistsIndexViewEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly IUrlService _mockUrlService;
|
||||
private readonly ThemePageRenderer _mockThemePageRenderer;
|
||||
private readonly IAntiforgery _mockAntiforgery;
|
||||
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
|
||||
private readonly IStringLocalizer _mockStringLocalizer;
|
||||
private readonly MusicArtistsIndexViewEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly GetMusicArtistsViewRequestFixture _getMusicArtistsViewRequestFixture = new();
|
||||
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtistsIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public MusicArtistsIndexViewEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockUrlService = Substitute.For<IUrlService>();
|
||||
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
|
||||
_mockAntiforgery = Substitute.For<IAntiforgery>();
|
||||
_mockAntiforgery.GetAndStoreTokens(Arg.Any<HttpContext>())
|
||||
.Returns(new AntiforgeryTokenSet("request-token", "cookie-token", "__RequestVerificationToken", "RequestVerificationToken"));
|
||||
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
|
||||
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(new LocalizedString[] { new("Search", "Search") });
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_sut = Factory.Create<MusicArtistsIndexViewEndpoint>(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/library/audio-library/music-library/artists";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: null), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
|
||||
Assert.Equal("http://localhost/en-us", redirectResult.Url);
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
_mockAntiforgery.DidNotReceive().GetAndStoreTokens(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdProvided_ShouldRenderThemedPageThroughTheSharedView()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedLibrary);
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTISTS).Returns("http://localhost/en-us/library/audio-library/music-library/artists/api-get-artists");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.ARTIST, Arg.Any<object>()).Returns("http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.DELETE_ARTIST, Arg.Any<object>()).Returns("http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000/api-delete-artist");
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>content</section>", script: "<script>script</script>")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: expectedLibrary.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", expectedLibrary.Id.ToString())),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
page.PageKey == "library/audio-library/music-library/artists/index" &&
|
||||
page.Title == expectedLibrary.Title &&
|
||||
page.PageData.ContainsKey("libraryId") &&
|
||||
page.PageData.ContainsKey("settingsUrl") &&
|
||||
page.PageData.ContainsKey("strings") &&
|
||||
string.Equals(
|
||||
page.PageData["itemsUrl"] as string,
|
||||
"http://localhost/en-us/library/audio-library/music-library/artists/api-get-artists",
|
||||
StringComparison.Ordinal) &&
|
||||
string.Equals(
|
||||
page.PageData["artistUrl"] as string,
|
||||
"http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000",
|
||||
StringComparison.Ordinal) &&
|
||||
string.Equals(
|
||||
page.PageData["deleteUrl"] as string,
|
||||
"http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000/api-delete-artist",
|
||||
StringComparison.Ordinal)),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockAntiforgery.Received(1).GetAndStoreTokens(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToRazorView()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedLibrary);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<ThemePageRenderResultDto>.Failure(Error.Failure("Theme.Render", "The page could not be rendered.")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: expectedLibrary.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.SaveMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.SaveMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SaveMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicArtistEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly SaveMusicArtistEndpoint _sut;
|
||||
private readonly UpdateMusicArtistRequestFixture _updateMusicArtistRequestFixture = new();
|
||||
private readonly MusicArtistDtoFixture _musicArtistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public SaveMusicArtistEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<SaveMusicArtistEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldForwardUpdateMusicArtistRequestToApiWithRouteAndQueryIds()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicArtistRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedArtist);
|
||||
ConfigureRequest(artistId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, artistId)),
|
||||
Arg.Is<UpdateMusicArtistRequest>(forwardedRequest => forwardedRequest == request),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
const string MALICIOUS_ARTIST_ID = "not-a-guid";
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicArtistRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicArtistDtoFixture.Create());
|
||||
ConfigureRequest(MALICIOUS_ARTIST_ID, libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, Guid.Empty)),
|
||||
Arg.Any<UpdateMusicArtistRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicArtistRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicArtistDtoFixture.Create());
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, Guid.Empty)),
|
||||
Arg.Any<UpdateMusicArtistRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string MALICIOUS_LIBRARY_ID = "not-a-guid";
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicArtistRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicArtistDtoFixture.Create());
|
||||
ConfigureRequest(artistId.ToString(), MALICIOUS_LIBRARY_ID);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty, artistId)),
|
||||
Arg.Any<UpdateMusicArtistRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsUpdatedArtist_ShouldReturnSuccessJsonWithArtist()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicArtistRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedArtist);
|
||||
ConfigureRequest(artistId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedArtist.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the artist identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(artistId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the artist identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the artist update is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId)
|
||||
{
|
||||
return ApiRoutes.Music.UPDATE_ARTIST
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString());
|
||||
}
|
||||
}
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateArtistCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateArtistCoverEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly UpdateArtistCoverEndpoint _sut;
|
||||
private readonly UpdateMusicCoverDtoFixture _updateMusicCoverDtoFixture = new();
|
||||
private static readonly Guid s_libraryId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateArtistCoverEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<UpdateArtistCoverEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithFile_ShouldUploadCoverToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/artists/cover.jpg"));
|
||||
ConfigureRequest(artistId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Is<string>(fileName => fileName == "cover.jpg"),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldUploadCoverWithEmptyId()
|
||||
{
|
||||
// Arrange
|
||||
const string MALICIOUS_ARTIST_ID = "not-a-guid";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/artists/cover.jpg"));
|
||||
ConfigureRequest(MALICIOUS_ARTIST_ID, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), Guid.Empty)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldUploadCoverWithEmptyLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/artists/cover.jpg"));
|
||||
ConfigureRequest(artistId, [1, 2, 3], "cover.jpg");
|
||||
// The query value is normalized to a Guid before it is substituted into the upstream URL, so a crafted value can never escape its segment.
|
||||
_sut.HttpContext.Request.QueryString = new QueryString("?libraryId=not-a-library-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty.ToString(), artistId)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldUploadCoverWithEmptyLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/artists/cover.jpg"));
|
||||
ConfigureRequest(artistId, [1, 2, 3], "cover.jpg");
|
||||
_sut.HttpContext.Request.QueryString = new QueryString(string.Empty);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty.ToString(), artistId)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsCoverPath_ShouldReturnSuccessJsonWithPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/artists/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
ConfigureRequest(artistId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFormHasNoFile_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/artists/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
ConfigureRequestWithoutFiles(artistId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId)),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRequestIsNotMultipart_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/artists/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
_sut.HttpContext.Request.ContentType = "application/json";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId)),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFormIsMalformed_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/artists/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
ConfigureMalformedRequest(artistId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId)),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request carrying a single file.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist whose cover is uploaded.</param>
|
||||
/// <param name="content">The bytes of the uploaded file.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
private void ConfigureRequest(Guid artistId, byte[] content, string fileName)
|
||||
{
|
||||
ConfigureRequest(artistId.ToString(), content, fileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request carrying a single file.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="content">The bytes of the uploaded file.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
private void ConfigureRequest(string artistId, byte[] content, string fileName)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
MemoryStream coverStream = new(content);
|
||||
IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName);
|
||||
FormFileCollection files = [formFile];
|
||||
IFormCollection form = new FormCollection([], files);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request without any file.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist whose cover is uploaded.</param>
|
||||
private void ConfigureRequestWithoutFiles(Guid artistId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
IFormCollection form = new FormCollection([]);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request whose body cannot be parsed.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist whose cover is uploaded.</param>
|
||||
private void ConfigureMalformedRequest(Guid artistId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
IFormCollection malformedForm = Substitute.For<IFormCollection>();
|
||||
malformedForm.Files.Returns(_ => throw new InvalidDataException("Malformed multipart body."));
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(malformedForm));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the cover upload is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The raw Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(string libraryId, Guid artistId)
|
||||
{
|
||||
return ApiRoutes.Music.UPDATE_ARTIST_COVER
|
||||
.Replace("{libraryId}", libraryId)
|
||||
.Replace("{artistId}", artistId.ToString());
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicTrackEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteMusicTrackEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteMusicTrackEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<DeleteMusicTrackEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldDeleteTrackViaApiAndReturnSuccessWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, albumId, trackId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out JsonElement _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", "not-a-guid", "not-a-guid", libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, Guid.Empty, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreMissing_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, Guid.Empty, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the track identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="trackId">The raw route value of the track Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, string trackId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(artistId, albumId, trackId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the track identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="trackId">The raw route value of the track Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, string trackId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the track deletion is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <param name="trackId">The normalized Id of the track.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return ApiRoutes.Music.DELETE_TRACK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString());
|
||||
}
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetAlbumTracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetAlbumTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAlbumTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetAlbumTracksEndpoint _sut;
|
||||
private readonly GetAlbumTracksLiteRequestFixture _getAlbumTracksLiteRequestFixture = new();
|
||||
private readonly PaginatedMusicTrackLiteDtoFixture _paginatedMusicTrackLiteDtoFixture = new();
|
||||
private readonly MusicTrackLiteDtoFixture _musicTrackLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetAlbumTracksEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetAlbumTracksEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithPagination_ShouldRequestTracksWithQueryParameters()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(currentPage: 2, perPage: 48);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicTrackLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicTrackLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Parse(request.AlbumId))}?currentPage=2&perPage=48"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithoutPagination_ShouldRequestTracksWithoutQueryParameters()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicTrackLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicTrackLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Parse(request.AlbumId))),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyCurrentPageIsProvided_ShouldAppendOnlyCurrentPage()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(currentPage: 3);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicTrackLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicTrackLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Parse(request.AlbumId))}?currentPage=3"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyPerPageIsProvided_ShouldAppendOnlyPerPage()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(perPage: 24);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicTrackLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicTrackLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Parse(request.AlbumId))}?perPage=24"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(artistId: "not-a-guid", currentPage: 1, perPage: 20);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicTrackLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicTrackLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Empty, Guid.Parse(request.AlbumId))}?currentPage=1&perPage=20"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAlbumIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(albumId: "' OR '1'='1", currentPage: 1, perPage: 20);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicTrackLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicTrackLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Empty)}?currentPage=1&perPage=20"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistIdAndAlbumIdAreMissing_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(artistId: string.Empty, albumId: string.Empty, currentPage: 1, perPage: 20);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicTrackLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedMusicTrackLiteDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Empty, Guid.Empty)}?currentPage=1&perPage=20"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsPaginatedTracks_ShouldReturnSuccessJsonWithTracks()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create();
|
||||
PaginatedMusicTrackLiteDto expectedResponse = _paginatedMusicTrackLiteDtoFixture.Create(
|
||||
data: [_musicTrackLiteDtoFixture.Create(title: "Test Track")],
|
||||
currentPage: 1,
|
||||
perPage: 20,
|
||||
count: 1,
|
||||
numberOfPages: 1);
|
||||
_mockApiHttpClient.GetAsync<PaginatedMusicTrackLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = jsonDocument.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("data").GetArrayLength());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the album track retrieval is expected to be sent to, without query parameters.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId)
|
||||
{
|
||||
return ApiRoutes.Music.GET_ALBUM_TRACKS_LITE
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString());
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicTrackEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetMusicTrackEndpoint _sut;
|
||||
private readonly GetMusicTrackViewRequestFixture _getMusicTrackViewRequestFixture = new();
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetMusicTrackEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetMusicTrackEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestTrackFromApiWithNormalizedIds()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicTrackViewRequest request = _getMusicTrackViewRequestFixture.Create();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<MusicTrackDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedTrack);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicTrackDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Parse(request.AlbumId), Guid.Parse(request.TrackId))),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicTrackViewRequest request = _getMusicTrackViewRequestFixture.Create(artistId: "not-a-guid", albumId: "' OR '1'='1", trackId: "'; DROP TABLE Tracks; --");
|
||||
_mockApiHttpClient.GetAsync<MusicTrackDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicTrackDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Empty, Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreEmpty_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicTrackViewRequest request = _getMusicTrackViewRequestFixture.Create(artistId: string.Empty, albumId: string.Empty, trackId: string.Empty);
|
||||
_mockApiHttpClient.GetAsync<MusicTrackDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicTrackDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Empty, Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsTrack_ShouldReturnSuccessJsonWithTrack()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicTrackViewRequest request = _getMusicTrackViewRequestFixture.Create();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<MusicTrackDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedTrack);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedTrack.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the track retrieval is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <param name="trackId">The normalized Id of the track.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return ApiRoutes.Music.GET_TRACK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString());
|
||||
}
|
||||
}
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.SaveMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.SaveMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SaveMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicTrackEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly SaveMusicTrackEndpoint _sut;
|
||||
private readonly UpdateMusicTrackRequestFixture _updateMusicTrackRequestFixture = new();
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public SaveMusicTrackEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<SaveMusicTrackEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldForwardUpdateMusicTrackRequestToApiWithRouteAndQueryIds()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedTrack);
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, artistId, albumId, trackId)),
|
||||
Arg.Is<UpdateMusicTrackRequest>(forwardedRequest => forwardedRequest == request),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
const string MALICIOUS_ARTIST_ID = "not-a-guid";
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
ConfigureRequest(MALICIOUS_ARTIST_ID, albumId.ToString(), trackId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId)),
|
||||
Arg.Any<UpdateMusicTrackRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAlbumRouteIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string MALICIOUS_ALBUM_ID = "' OR '1'='1";
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
ConfigureRequest(artistId.ToString(), MALICIOUS_ALBUM_ID, trackId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId)),
|
||||
Arg.Any<UpdateMusicTrackRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTrackRouteIdIsNotParseable_ShouldForwardGuidEmptyTrackIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string MALICIOUS_TRACK_ID = "'; DROP TABLE Tracks; --";
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), MALICIOUS_TRACK_ID, libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty)),
|
||||
Arg.Any<UpdateMusicTrackRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreMissing_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, Guid.Empty, Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<UpdateMusicTrackRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
const string MALICIOUS_LIBRARY_ID = "not-a-guid";
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), MALICIOUS_LIBRARY_ID);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId)),
|
||||
Arg.Any<UpdateMusicTrackRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsUpdatedTrack_ShouldReturnSuccessJsonWithTrack()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedTrack);
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedTrack.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the track identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="trackId">The raw route value of the track Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, string trackId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(artistId, albumId, trackId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the track identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="trackId">The raw route value of the track Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, string trackId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the track update is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <param name="trackId">The normalized Id of the track.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return ApiRoutes.Music.UPDATE_TRACK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user