mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 05:11:10 +00:00
Adds the MusicBrainz music metadata plugin, its fixtures, and its unit test suite
This commit is contained in:
1 parent
1ffa14cec4
commit
0abda472c6
101 files changed
+11461
No files matched your search
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzAliasResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzAliasResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzAliasResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional. The name of the alias.</param>
|
||||
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="sortName">Optional. The sort name of the alias.</param>
|
||||
/// <param name="includeSortName">Whether the sort name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="type">Optional. The type of the alias.</param>
|
||||
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="locale">Optional. The locale the alias is used in.</param>
|
||||
/// <param name="includeLocale">Whether the locale should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="isPrimary">Optional. Whether this is the primary alias.</param>
|
||||
/// <param name="includePrimary">Whether the primary flag should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="begin">Optional. The begin date of the alias.</param>
|
||||
/// <param name="includeBegin">Whether the begin date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="end">Optional. The end date of the alias.</param>
|
||||
/// <param name="includeEnd">Whether the end date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="isEnded">Optional. Whether the alias has ended.</param>
|
||||
/// <param name="includeEnded">Whether the ended flag should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzAliasResponse"/> instance.</returns>
|
||||
public MusicBrainzAliasResponse Create(
|
||||
string? name = null,
|
||||
bool includeName = true,
|
||||
string? sortName = null,
|
||||
bool includeSortName = true,
|
||||
string? type = null,
|
||||
bool includeType = true,
|
||||
string? locale = null,
|
||||
bool includeLocale = true,
|
||||
bool? isPrimary = null,
|
||||
bool includePrimary = true,
|
||||
string? begin = null,
|
||||
bool includeBegin = true,
|
||||
string? end = null,
|
||||
bool includeEnd = true,
|
||||
bool? isEnded = null,
|
||||
bool includeEnded = true)
|
||||
{
|
||||
return new MusicBrainzAliasResponse
|
||||
{
|
||||
Name = includeName ? name ?? _faker.Name.FullName() : null,
|
||||
SortName = includeSortName ? sortName ?? _faker.Name.FullName() : null,
|
||||
Type = includeType ? type ?? _faker.PickRandom("Artist name", "Legal name") : null,
|
||||
Locale = includeLocale ? locale ?? _faker.PickRandom("en", "de", "fr") : null,
|
||||
IsPrimary = includePrimary ? isPrimary ?? _faker.Random.Bool() : null,
|
||||
Begin = includeBegin ? begin ?? _faker.Date.Past(50).ToString("yyyy-MM-dd") : null,
|
||||
End = includeEnd ? end ?? _faker.Date.Past(5).ToString("yyyy-MM-dd") : null,
|
||||
IsEnded = includeEnded ? isEnded ?? _faker.Random.Bool() : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzAliasResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzAliasResponse"/> instances.</returns>
|
||||
public List<MusicBrainzAliasResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzAreaResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzAreaResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzAreaResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The MusicBrainz identifier of the area.</param>
|
||||
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="name">Optional. The name of the area.</param>
|
||||
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="sortName">Optional. The sort name of the area.</param>
|
||||
/// <param name="includeSortName">Whether the sort name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="disambiguation">Optional. The disambiguation comment of the area.</param>
|
||||
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="type">Optional. The MusicBrainz type of the area.</param>
|
||||
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="iso3166Part1Codes">Optional. The ISO 3166-1 codes of the area.</param>
|
||||
/// <param name="iso3166Part2Codes">Optional. The ISO 3166-2 codes of the area.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzAreaResponse"/> instance.</returns>
|
||||
public MusicBrainzAreaResponse Create(
|
||||
string? id = null,
|
||||
bool includeId = true,
|
||||
string? name = null,
|
||||
bool includeName = true,
|
||||
string? sortName = null,
|
||||
bool includeSortName = true,
|
||||
string? disambiguation = null,
|
||||
bool includeDisambiguation = true,
|
||||
string? type = null,
|
||||
bool includeType = true,
|
||||
List<string>? iso3166Part1Codes = null,
|
||||
List<string>? iso3166Part2Codes = null)
|
||||
{
|
||||
return new MusicBrainzAreaResponse
|
||||
{
|
||||
Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
|
||||
Name = includeName ? name ?? _faker.Address.Country() : null,
|
||||
SortName = includeSortName ? sortName ?? _faker.Address.Country() : null,
|
||||
Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
|
||||
Type = includeType ? type ?? _faker.PickRandom("Country", "City", "Area") : null,
|
||||
Iso3166Part1Codes = iso3166Part1Codes ?? [_faker.Address.CountryCode()],
|
||||
Iso3166Part2Codes = iso3166Part2Codes ?? [_faker.Random.String2(5, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")]
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzAreaResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzAreaResponse"/> instances.</returns>
|
||||
public List<MusicBrainzAreaResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzArtistCreditResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzArtistCreditResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzArtistResponseFixture _musicBrainzArtistResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzArtistCreditResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional. The credited name of the artist.</param>
|
||||
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="joinPhrase">Optional. The join phrase that follows the credit.</param>
|
||||
/// <param name="includeJoinPhrase">Whether the join phrase should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="artist">Optional. The artist the credit refers to.</param>
|
||||
/// <param name="includeArtist">Whether the artist should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzArtistCreditResponse"/> instance.</returns>
|
||||
public MusicBrainzArtistCreditResponse Create(
|
||||
string? name = null,
|
||||
bool includeName = true,
|
||||
string? joinPhrase = null,
|
||||
bool includeJoinPhrase = true,
|
||||
MusicBrainzArtistResponse? artist = null,
|
||||
bool includeArtist = true)
|
||||
{
|
||||
string? resolvedName = includeName ? name ?? _faker.Name.FullName() : null;
|
||||
return new MusicBrainzArtistCreditResponse
|
||||
{
|
||||
Name = resolvedName,
|
||||
JoinPhrase = includeJoinPhrase ? joinPhrase ?? _faker.PickRandom(" & ", " feat. ", ", ") : null,
|
||||
Artist = includeArtist ? artist ?? _musicBrainzArtistResponseFixture.Create(name: resolvedName) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzArtistCreditResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzArtistCreditResponse"/> instances.</returns>
|
||||
public List<MusicBrainzArtistCreditResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzArtistResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzArtistResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzAreaResponseFixture _musicBrainzAreaResponseFixture = new();
|
||||
private readonly MusicBrainzAliasResponseFixture _musicBrainzAliasResponseFixture = new();
|
||||
private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new();
|
||||
private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new();
|
||||
private readonly MusicBrainzLifeSpanResponseFixture _musicBrainzLifeSpanResponseFixture = new();
|
||||
private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzArtistResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The MusicBrainz identifier of the artist.</param>
|
||||
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="name">Optional. The name of the artist.</param>
|
||||
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="sortName">Optional. The sort name of the artist.</param>
|
||||
/// <param name="includeSortName">Whether the sort name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="disambiguation">Optional. The disambiguation comment of the artist.</param>
|
||||
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="type">Optional. The MusicBrainz type of the artist.</param>
|
||||
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="gender">Optional. The gender of the artist.</param>
|
||||
/// <param name="includeGender">Whether the gender should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="country">Optional. The ISO 3166-1 alpha-2 code of the country of the artist.</param>
|
||||
/// <param name="includeCountry">Whether the country should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="area">Optional. The area the artist is primarily identified with.</param>
|
||||
/// <param name="includeArea">Whether the area should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="beginArea">Optional. The area the artist began in.</param>
|
||||
/// <param name="includeBeginArea">Whether the begin area should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="endArea">Optional. The area the artist ended in.</param>
|
||||
/// <param name="includeEndArea">Whether the end area should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="lifeSpan">Optional. The life span of the artist.</param>
|
||||
/// <param name="includeLifeSpan">Whether the life span should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="isnis">Optional. The ISNI codes of the artist.</param>
|
||||
/// <param name="ipis">Optional. The IPI codes of the artist.</param>
|
||||
/// <param name="aliases">Optional. The alternative names of the artist.</param>
|
||||
/// <param name="tags">Optional. The tags of the artist.</param>
|
||||
/// <param name="genres">Optional. The genres of the artist.</param>
|
||||
/// <param name="relations">Optional. The relationships of the artist to other entities.</param>
|
||||
/// <param name="rating">Optional. The aggregated rating of the artist.</param>
|
||||
/// <param name="includeRating">Whether the rating should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzArtistResponse"/> instance.</returns>
|
||||
public MusicBrainzArtistResponse Create(
|
||||
string? id = null,
|
||||
bool includeId = true,
|
||||
string? name = null,
|
||||
bool includeName = true,
|
||||
string? sortName = null,
|
||||
bool includeSortName = true,
|
||||
string? disambiguation = null,
|
||||
bool includeDisambiguation = true,
|
||||
string? type = null,
|
||||
bool includeType = true,
|
||||
string? gender = null,
|
||||
bool includeGender = true,
|
||||
string? country = null,
|
||||
bool includeCountry = true,
|
||||
MusicBrainzAreaResponse? area = null,
|
||||
bool includeArea = false,
|
||||
MusicBrainzAreaResponse? beginArea = null,
|
||||
bool includeBeginArea = false,
|
||||
MusicBrainzAreaResponse? endArea = null,
|
||||
bool includeEndArea = false,
|
||||
MusicBrainzLifeSpanResponse? lifeSpan = null,
|
||||
bool includeLifeSpan = false,
|
||||
List<string>? isnis = null,
|
||||
List<string>? ipis = null,
|
||||
List<MusicBrainzAliasResponse>? aliases = null,
|
||||
List<MusicBrainzTagResponse>? tags = null,
|
||||
List<MusicBrainzTagResponse>? genres = null,
|
||||
List<MusicBrainzRelationResponse>? relations = null,
|
||||
MusicBrainzRatingResponse? rating = null,
|
||||
bool includeRating = false)
|
||||
{
|
||||
return new MusicBrainzArtistResponse
|
||||
{
|
||||
Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
|
||||
Name = includeName ? name ?? _faker.Name.FullName() : null,
|
||||
SortName = includeSortName ? sortName ?? _faker.Name.FullName() : null,
|
||||
Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
|
||||
Type = includeType ? type ?? _faker.PickRandom("Person", "Group", "Orchestra") : null,
|
||||
Gender = includeGender ? gender ?? _faker.PickRandom("Male", "Female") : null,
|
||||
Country = includeCountry ? country ?? _faker.Address.CountryCode() : null,
|
||||
Area = includeArea ? area ?? _musicBrainzAreaResponseFixture.Create() : null,
|
||||
BeginArea = includeBeginArea ? beginArea ?? _musicBrainzAreaResponseFixture.Create() : null,
|
||||
EndArea = includeEndArea ? endArea ?? _musicBrainzAreaResponseFixture.Create() : null,
|
||||
LifeSpan = includeLifeSpan ? lifeSpan ?? _musicBrainzLifeSpanResponseFixture.Create() : null,
|
||||
Isnis = isnis ?? [_faker.Random.String2(16, "0123456789")],
|
||||
Ipis = ipis ?? [_faker.Random.String2(11, "0123456789")],
|
||||
Aliases = aliases ?? [.. _musicBrainzAliasResponseFixture.CreateMany(2)],
|
||||
Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
|
||||
Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
|
||||
Relations = relations ?? [.. _musicBrainzRelationResponseFixture.CreateMany(2)],
|
||||
Rating = includeRating ? rating ?? _musicBrainzRatingResponseFixture.Create() : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzArtistResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzArtistResponse"/> instances.</returns>
|
||||
public List<MusicBrainzArtistResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzArtistSearchResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzArtistSearchResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzArtistResponseFixture _musicBrainzArtistResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzArtistSearchResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Optional. The total number of matching artists.</param>
|
||||
/// <param name="offset">Optional. The offset of the returned artists.</param>
|
||||
/// <param name="artists">Optional. The matching artists.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzArtistSearchResponse"/> instance.</returns>
|
||||
public MusicBrainzArtistSearchResponse Create(
|
||||
int? count = null,
|
||||
int? offset = null,
|
||||
List<MusicBrainzArtistResponse>? artists = null)
|
||||
{
|
||||
List<MusicBrainzArtistResponse> resolvedArtists = artists ?? [.. _musicBrainzArtistResponseFixture.CreateMany(2)];
|
||||
return new MusicBrainzArtistSearchResponse
|
||||
{
|
||||
Count = count ?? resolvedArtists.Count,
|
||||
Offset = offset ?? _faker.Random.Int(0, 100),
|
||||
Artists = resolvedArtists
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzArtistSearchResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzArtistSearchResponse"/> instances.</returns>
|
||||
public List<MusicBrainzArtistSearchResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzLabelInfoResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzLabelInfoResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzLabelResponseFixture _musicBrainzLabelResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzLabelInfoResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="catalogNumber">Optional. The catalog number assigned by the label.</param>
|
||||
/// <param name="includeCatalogNumber">Whether the catalog number should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="label">Optional. The label that issued the release.</param>
|
||||
/// <param name="includeLabel">Whether the label should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzLabelInfoResponse"/> instance.</returns>
|
||||
public MusicBrainzLabelInfoResponse Create(
|
||||
string? catalogNumber = null,
|
||||
bool includeCatalogNumber = true,
|
||||
MusicBrainzLabelResponse? label = null,
|
||||
bool includeLabel = true)
|
||||
{
|
||||
return new MusicBrainzLabelInfoResponse
|
||||
{
|
||||
CatalogNumber = includeCatalogNumber ? catalogNumber ?? _faker.Random.AlphaNumeric(8).ToUpperInvariant() : null,
|
||||
Label = includeLabel ? label ?? _musicBrainzLabelResponseFixture.Create() : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzLabelInfoResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzLabelInfoResponse"/> instances.</returns>
|
||||
public List<MusicBrainzLabelInfoResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzLabelResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzLabelResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzLabelResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The MusicBrainz identifier of the label.</param>
|
||||
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="name">Optional. The name of the label.</param>
|
||||
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="disambiguation">Optional. The disambiguation comment of the label.</param>
|
||||
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="labelCode">Optional. The label code of the label.</param>
|
||||
/// <param name="includeLabelCode">Whether the label code should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzLabelResponse"/> instance.</returns>
|
||||
public MusicBrainzLabelResponse Create(
|
||||
string? id = null,
|
||||
bool includeId = true,
|
||||
string? name = null,
|
||||
bool includeName = true,
|
||||
string? disambiguation = null,
|
||||
bool includeDisambiguation = true,
|
||||
int? labelCode = null,
|
||||
bool includeLabelCode = true)
|
||||
{
|
||||
return new MusicBrainzLabelResponse
|
||||
{
|
||||
Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
|
||||
Name = includeName ? name ?? _faker.Company.CompanyName() : null,
|
||||
Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
|
||||
LabelCode = includeLabelCode ? labelCode ?? _faker.Random.Int(1, 9999) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzLabelResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzLabelResponse"/> instances.</returns>
|
||||
public List<MusicBrainzLabelResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzLifeSpanResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzLifeSpanResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzLifeSpanResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="begin">Optional. The begin date of the life span.</param>
|
||||
/// <param name="includeBegin">Whether the begin date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="end">Optional. The end date of the life span.</param>
|
||||
/// <param name="includeEnd">Whether the end date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="isEnded">Optional. Whether the life span has ended.</param>
|
||||
/// <param name="includeEnded">Whether the ended flag should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzLifeSpanResponse"/> instance.</returns>
|
||||
public MusicBrainzLifeSpanResponse Create(
|
||||
string? begin = null,
|
||||
bool includeBegin = true,
|
||||
string? end = null,
|
||||
bool includeEnd = true,
|
||||
bool? isEnded = null,
|
||||
bool includeEnded = true)
|
||||
{
|
||||
return new MusicBrainzLifeSpanResponse
|
||||
{
|
||||
Begin = includeBegin ? begin ?? _faker.Date.Past(60).ToString("yyyy-MM-dd") : null,
|
||||
End = includeEnd ? end ?? _faker.Date.Past(5).ToString("yyyy-MM-dd") : null,
|
||||
IsEnded = includeEnded ? isEnded ?? _faker.Random.Bool() : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzLifeSpanResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzLifeSpanResponse"/> instances.</returns>
|
||||
public List<MusicBrainzLifeSpanResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzMediumResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzMediumResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzTrackResponseFixture _musicBrainzTrackResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzMediumResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="position">Optional. The position of the medium within its release.</param>
|
||||
/// <param name="title">Optional. The title of the medium.</param>
|
||||
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="format">Optional. The format of the medium.</param>
|
||||
/// <param name="includeFormat">Whether the format should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="trackCount">Optional. The number of tracks of the medium.</param>
|
||||
/// <param name="tracks">Optional. The tracks of the medium.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzMediumResponse"/> instance.</returns>
|
||||
public MusicBrainzMediumResponse Create(
|
||||
int? position = null,
|
||||
string? title = null,
|
||||
bool includeTitle = true,
|
||||
string? format = null,
|
||||
bool includeFormat = true,
|
||||
int? trackCount = null,
|
||||
List<MusicBrainzTrackResponse>? tracks = null)
|
||||
{
|
||||
List<MusicBrainzTrackResponse> resolvedTracks = tracks ?? [.. _musicBrainzTrackResponseFixture.CreateMany(2)];
|
||||
return new MusicBrainzMediumResponse
|
||||
{
|
||||
Position = position ?? _faker.Random.Int(1, 4),
|
||||
Title = includeTitle ? title ?? _faker.Lorem.Sentence(2) : null,
|
||||
Format = includeFormat ? format ?? _faker.PickRandom("CD", "Vinyl", "Digital Media") : null,
|
||||
TrackCount = trackCount ?? resolvedTracks.Count,
|
||||
Tracks = resolvedTracks
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzMediumResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzMediumResponse"/> instances.</returns>
|
||||
public List<MusicBrainzMediumResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(index => Create(position: index + 1))];
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzRatingResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzRatingResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzRatingResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The average rating value.</param>
|
||||
/// <param name="includeValue">Whether the value should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="votesCount">Optional. The number of votes that contributed to the rating.</param>
|
||||
/// <param name="includeVotesCount">Whether the votes count should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzRatingResponse"/> instance.</returns>
|
||||
public MusicBrainzRatingResponse Create(
|
||||
decimal? value = null,
|
||||
bool includeValue = true,
|
||||
int? votesCount = null,
|
||||
bool includeVotesCount = true)
|
||||
{
|
||||
return new MusicBrainzRatingResponse
|
||||
{
|
||||
Value = includeValue ? value ?? _faker.Random.Decimal(1m, 5m) : null,
|
||||
VotesCount = includeVotesCount ? votesCount ?? _faker.Random.Int(1, 500) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzRatingResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzRatingResponse"/> instances.</returns>
|
||||
public List<MusicBrainzRatingResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzRecordingListResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzRecordingListResponseFixture
|
||||
{
|
||||
private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzRecordingListResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="recordings">Optional. The recordings that carry the looked up ISRC.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzRecordingListResponse"/> instance.</returns>
|
||||
public MusicBrainzRecordingListResponse Create(List<MusicBrainzRecordingResponse>? recordings = null)
|
||||
{
|
||||
return new MusicBrainzRecordingListResponse
|
||||
{
|
||||
Recordings = recordings ?? [.. _musicBrainzRecordingResponseFixture.CreateMany(2)]
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzRecordingListResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzRecordingListResponse"/> instances.</returns>
|
||||
public List<MusicBrainzRecordingListResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzRecordingResponse"/> record.
|
||||
/// The releases of the recording default to an empty list, because a recording embedded in a release does not carry them.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzRecordingResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new();
|
||||
private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new();
|
||||
private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new();
|
||||
private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzRecordingResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The MusicBrainz identifier of the recording.</param>
|
||||
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="title">Optional. The title of the recording.</param>
|
||||
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="disambiguation">Optional. The disambiguation comment of the recording.</param>
|
||||
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="length">Optional. The length of the recording in milliseconds.</param>
|
||||
/// <param name="includeLength">Whether the length should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="isVideo">Optional. Whether the recording is a video recording.</param>
|
||||
/// <param name="includeVideo">Whether the video flag should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="firstReleaseDate">Optional. The date the recording was first released.</param>
|
||||
/// <param name="includeFirstReleaseDate">Whether the first release date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="artistCredit">Optional. The artist credit of the recording.</param>
|
||||
/// <param name="isrcs">Optional. The ISRCs of the recording.</param>
|
||||
/// <param name="releases">Optional. The releases the recording appears on.</param>
|
||||
/// <param name="tags">Optional. The tags of the recording.</param>
|
||||
/// <param name="genres">Optional. The genres of the recording.</param>
|
||||
/// <param name="relations">Optional. The relationships of the recording to other entities.</param>
|
||||
/// <param name="rating">Optional. The aggregated rating of the recording.</param>
|
||||
/// <param name="includeRating">Whether the rating should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzRecordingResponse"/> instance.</returns>
|
||||
public MusicBrainzRecordingResponse Create(
|
||||
string? id = null,
|
||||
bool includeId = true,
|
||||
string? title = null,
|
||||
bool includeTitle = true,
|
||||
string? disambiguation = null,
|
||||
bool includeDisambiguation = true,
|
||||
long? length = null,
|
||||
bool includeLength = true,
|
||||
bool? isVideo = null,
|
||||
bool includeVideo = true,
|
||||
string? firstReleaseDate = null,
|
||||
bool includeFirstReleaseDate = true,
|
||||
List<MusicBrainzArtistCreditResponse>? artistCredit = null,
|
||||
List<string>? isrcs = null,
|
||||
List<MusicBrainzReleaseResponse>? releases = null,
|
||||
List<MusicBrainzTagResponse>? tags = null,
|
||||
List<MusicBrainzTagResponse>? genres = null,
|
||||
List<MusicBrainzRelationResponse>? relations = null,
|
||||
MusicBrainzRatingResponse? rating = null,
|
||||
bool includeRating = false)
|
||||
{
|
||||
return new MusicBrainzRecordingResponse
|
||||
{
|
||||
Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
|
||||
Title = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null,
|
||||
Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
|
||||
Length = includeLength ? length ?? _faker.Random.Long(30_000, 600_000) : null,
|
||||
IsVideo = includeVideo ? isVideo ?? _faker.Random.Bool() : null,
|
||||
FirstReleaseDate = includeFirstReleaseDate ? firstReleaseDate ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null,
|
||||
ArtistCredit = artistCredit ?? [.. _musicBrainzArtistCreditResponseFixture.CreateMany(2)],
|
||||
Isrcs = isrcs ?? [$"US{_faker.Random.AlphaNumeric(10).ToUpperInvariant()}"],
|
||||
Releases = releases ?? [],
|
||||
Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
|
||||
Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
|
||||
Relations = relations ?? [.. _musicBrainzRelationResponseFixture.CreateMany(2)],
|
||||
Rating = includeRating ? rating ?? _musicBrainzRatingResponseFixture.Create() : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzRecordingResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzRecordingResponse"/> instances.</returns>
|
||||
public List<MusicBrainzRecordingResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzRecordingSearchResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzRecordingSearchResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzRecordingSearchResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Optional. The total number of matching recordings.</param>
|
||||
/// <param name="offset">Optional. The offset of the returned recordings.</param>
|
||||
/// <param name="recordings">Optional. The matching recordings.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzRecordingSearchResponse"/> instance.</returns>
|
||||
public MusicBrainzRecordingSearchResponse Create(
|
||||
int? count = null,
|
||||
int? offset = null,
|
||||
List<MusicBrainzRecordingResponse>? recordings = null)
|
||||
{
|
||||
List<MusicBrainzRecordingResponse> resolvedRecordings = recordings ?? [.. _musicBrainzRecordingResponseFixture.CreateMany(2)];
|
||||
return new MusicBrainzRecordingSearchResponse
|
||||
{
|
||||
Count = count ?? resolvedRecordings.Count,
|
||||
Offset = offset ?? _faker.Random.Int(0, 100),
|
||||
Recordings = resolvedRecordings
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzRecordingSearchResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzRecordingSearchResponse"/> instances.</returns>
|
||||
public List<MusicBrainzRecordingSearchResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzRelationResponse"/> record.
|
||||
/// The nested artist, work and url targets are optional, because a relation usually targets only one of them.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzRelationResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
// The artist and work fixtures each compose a relation fixture of their own, so holding them eagerly here would recurse forever; they are
|
||||
// therefore created on first use. The URL fixture has no such dependency, so it is held directly.
|
||||
private readonly Lazy<MusicBrainzArtistResponseFixture> _musicBrainzArtistResponseFixture = new(() => new MusicBrainzArtistResponseFixture());
|
||||
private readonly Lazy<MusicBrainzWorkResponseFixture> _musicBrainzWorkResponseFixture = new(() => new MusicBrainzWorkResponseFixture());
|
||||
private readonly MusicBrainzUrlResponseFixture _musicBrainzUrlResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzRelationResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="type">Optional. The type of the relationship.</param>
|
||||
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="typeId">Optional. The MusicBrainz identifier of the type of the relationship.</param>
|
||||
/// <param name="includeTypeId">Whether the type identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="direction">Optional. The direction of the relationship.</param>
|
||||
/// <param name="includeDirection">Whether the direction should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="targetType">Optional. The type of the entity the relationship targets.</param>
|
||||
/// <param name="includeTargetType">Whether the target type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="artist">Optional. The artist the relationship targets.</param>
|
||||
/// <param name="includeArtist">Whether the artist should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="work">Optional. The work the relationship targets.</param>
|
||||
/// <param name="includeWork">Whether the work should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="url">Optional. The URL the relationship targets.</param>
|
||||
/// <param name="includeUrl">Whether the URL should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="attributes">Optional. The attributes of the relationship.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzRelationResponse"/> instance.</returns>
|
||||
public MusicBrainzRelationResponse Create(
|
||||
string? type = null,
|
||||
bool includeType = true,
|
||||
string? typeId = null,
|
||||
bool includeTypeId = true,
|
||||
string? direction = null,
|
||||
bool includeDirection = true,
|
||||
string? targetType = null,
|
||||
bool includeTargetType = true,
|
||||
MusicBrainzArtistResponse? artist = null,
|
||||
bool includeArtist = false,
|
||||
MusicBrainzWorkResponse? work = null,
|
||||
bool includeWork = false,
|
||||
MusicBrainzUrlResponse? url = null,
|
||||
bool includeUrl = false,
|
||||
List<string>? attributes = null)
|
||||
{
|
||||
return new MusicBrainzRelationResponse
|
||||
{
|
||||
Type = includeType ? type ?? _faker.PickRandom("producer", "composer", "performer") : null,
|
||||
TypeId = includeTypeId ? typeId ?? Guid.NewGuid().ToString() : null,
|
||||
Direction = includeDirection ? direction ?? "backward" : null,
|
||||
TargetType = includeTargetType ? targetType ?? "artist" : null,
|
||||
Artist = includeArtist ? artist ?? _musicBrainzArtistResponseFixture.Value.Create() : null,
|
||||
Work = includeWork ? work ?? _musicBrainzWorkResponseFixture.Value.Create() : null,
|
||||
Url = includeUrl ? url ?? _musicBrainzUrlResponseFixture.Create() : null,
|
||||
Attributes = attributes ?? []
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzRelationResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzRelationResponse"/> instances.</returns>
|
||||
public List<MusicBrainzRelationResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzReleaseBrowseResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzReleaseBrowseResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzReleaseResponseFixture _musicBrainzReleaseResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzReleaseBrowseResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="releases">Optional. The releases returned by the browse request.</param>
|
||||
/// <param name="releaseCount">Optional. The total number of releases linked to the browsed entity.</param>
|
||||
/// <param name="releaseOffset">Optional. The offset of the returned releases.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzReleaseBrowseResponse"/> instance.</returns>
|
||||
public MusicBrainzReleaseBrowseResponse Create(
|
||||
List<MusicBrainzReleaseResponse>? releases = null,
|
||||
int? releaseCount = null,
|
||||
int? releaseOffset = null)
|
||||
{
|
||||
List<MusicBrainzReleaseResponse> resolvedReleases = releases ?? [.. _musicBrainzReleaseResponseFixture.CreateMany(2)];
|
||||
return new MusicBrainzReleaseBrowseResponse
|
||||
{
|
||||
Releases = resolvedReleases,
|
||||
ReleaseCount = releaseCount ?? resolvedReleases.Count,
|
||||
ReleaseOffset = releaseOffset ?? _faker.Random.Int(0, 100)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzReleaseBrowseResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzReleaseBrowseResponse"/> instances.</returns>
|
||||
public List<MusicBrainzReleaseBrowseResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzReleaseEventResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzReleaseEventResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzAreaResponseFixture _musicBrainzAreaResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzReleaseEventResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="date">Optional. The date of the release event.</param>
|
||||
/// <param name="includeDate">Whether the date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="area">Optional. The area of the release event.</param>
|
||||
/// <param name="includeArea">Whether the area should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzReleaseEventResponse"/> instance.</returns>
|
||||
public MusicBrainzReleaseEventResponse Create(
|
||||
string? date = null,
|
||||
bool includeDate = true,
|
||||
MusicBrainzAreaResponse? area = null,
|
||||
bool includeArea = true)
|
||||
{
|
||||
return new MusicBrainzReleaseEventResponse
|
||||
{
|
||||
Date = includeDate ? date ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null,
|
||||
Area = includeArea ? area ?? _musicBrainzAreaResponseFixture.Create() : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzReleaseEventResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzReleaseEventResponse"/> instances.</returns>
|
||||
public List<MusicBrainzReleaseEventResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzReleaseGroupResponse"/> record.
|
||||
/// The releases of the release group default to an empty list, because they are only returned by a dedicated browse request.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzReleaseGroupResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new();
|
||||
private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new();
|
||||
private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzReleaseGroupResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The MusicBrainz identifier of the release group.</param>
|
||||
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="title">Optional. The title of the release group.</param>
|
||||
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="disambiguation">Optional. The disambiguation comment of the release group.</param>
|
||||
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="primaryType">Optional. The primary type of the release group.</param>
|
||||
/// <param name="includePrimaryType">Whether the primary type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="secondaryTypes">Optional. The secondary types of the release group.</param>
|
||||
/// <param name="firstReleaseDate">Optional. The date the release group was first released.</param>
|
||||
/// <param name="includeFirstReleaseDate">Whether the first release date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="artistCredit">Optional. The artist credit of the release group.</param>
|
||||
/// <param name="releases">Optional. The releases of the release group.</param>
|
||||
/// <param name="tags">Optional. The tags of the release group.</param>
|
||||
/// <param name="genres">Optional. The genres of the release group.</param>
|
||||
/// <param name="rating">Optional. The aggregated rating of the release group.</param>
|
||||
/// <param name="includeRating">Whether the rating should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzReleaseGroupResponse"/> instance.</returns>
|
||||
public MusicBrainzReleaseGroupResponse Create(
|
||||
string? id = null,
|
||||
bool includeId = true,
|
||||
string? title = null,
|
||||
bool includeTitle = true,
|
||||
string? disambiguation = null,
|
||||
bool includeDisambiguation = true,
|
||||
string? primaryType = null,
|
||||
bool includePrimaryType = true,
|
||||
List<string>? secondaryTypes = null,
|
||||
string? firstReleaseDate = null,
|
||||
bool includeFirstReleaseDate = true,
|
||||
List<MusicBrainzArtistCreditResponse>? artistCredit = null,
|
||||
List<MusicBrainzReleaseResponse>? releases = null,
|
||||
List<MusicBrainzTagResponse>? tags = null,
|
||||
List<MusicBrainzTagResponse>? genres = null,
|
||||
MusicBrainzRatingResponse? rating = null,
|
||||
bool includeRating = false)
|
||||
{
|
||||
return new MusicBrainzReleaseGroupResponse
|
||||
{
|
||||
Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
|
||||
Title = includeTitle ? title ?? _faker.Commerce.ProductName() : null,
|
||||
Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
|
||||
PrimaryType = includePrimaryType ? primaryType ?? _faker.PickRandom("Album", "Single", "EP") : null,
|
||||
SecondaryTypes = secondaryTypes ?? [],
|
||||
FirstReleaseDate = includeFirstReleaseDate ? firstReleaseDate ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null,
|
||||
ArtistCredit = artistCredit ?? [.. _musicBrainzArtistCreditResponseFixture.CreateMany(2)],
|
||||
Releases = releases ?? [],
|
||||
Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
|
||||
Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
|
||||
Rating = includeRating ? rating ?? _musicBrainzRatingResponseFixture.Create() : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzReleaseGroupResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzReleaseGroupResponse"/> instances.</returns>
|
||||
public List<MusicBrainzReleaseGroupResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzReleaseGroupSearchResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzReleaseGroupSearchResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzReleaseGroupResponseFixture _musicBrainzReleaseGroupResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzReleaseGroupSearchResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Optional. The total number of matching release groups.</param>
|
||||
/// <param name="offset">Optional. The offset of the returned release groups.</param>
|
||||
/// <param name="releaseGroups">Optional. The matching release groups.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzReleaseGroupSearchResponse"/> instance.</returns>
|
||||
public MusicBrainzReleaseGroupSearchResponse Create(
|
||||
int? count = null,
|
||||
int? offset = null,
|
||||
List<MusicBrainzReleaseGroupResponse>? releaseGroups = null)
|
||||
{
|
||||
List<MusicBrainzReleaseGroupResponse> resolvedReleaseGroups = releaseGroups ?? [.. _musicBrainzReleaseGroupResponseFixture.CreateMany(2)];
|
||||
return new MusicBrainzReleaseGroupSearchResponse
|
||||
{
|
||||
Count = count ?? resolvedReleaseGroups.Count,
|
||||
Offset = offset ?? _faker.Random.Int(0, 100),
|
||||
ReleaseGroups = resolvedReleaseGroups
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzReleaseGroupSearchResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzReleaseGroupSearchResponse"/> instances.</returns>
|
||||
public List<MusicBrainzReleaseGroupSearchResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzReleaseResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzReleaseResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new();
|
||||
private readonly MusicBrainzReleaseGroupResponseFixture _musicBrainzReleaseGroupResponseFixture = new();
|
||||
private readonly MusicBrainzLabelInfoResponseFixture _musicBrainzLabelInfoResponseFixture = new();
|
||||
private readonly MusicBrainzMediumResponseFixture _musicBrainzMediumResponseFixture = new();
|
||||
private readonly MusicBrainzReleaseEventResponseFixture _musicBrainzReleaseEventResponseFixture = new();
|
||||
private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new();
|
||||
private readonly MusicBrainzTextRepresentationResponseFixture _musicBrainzTextRepresentationResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzReleaseResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The MusicBrainz identifier of the release.</param>
|
||||
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="title">Optional. The title of the release.</param>
|
||||
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="disambiguation">Optional. The disambiguation comment of the release.</param>
|
||||
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="status">Optional. The status of the release.</param>
|
||||
/// <param name="includeStatus">Whether the status should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="date">Optional. The date the release was issued.</param>
|
||||
/// <param name="includeDate">Whether the date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="country">Optional. The ISO 3166-1 alpha-2 code of the country the release was issued in.</param>
|
||||
/// <param name="includeCountry">Whether the country should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="releaseEvents">Optional. The release events of the release.</param>
|
||||
/// <param name="barcode">Optional. The barcode of the release.</param>
|
||||
/// <param name="includeBarcode">Whether the barcode should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="packaging">Optional. The outermost packaging of the release.</param>
|
||||
/// <param name="includePackaging">Whether the packaging should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="textRepresentation">Optional. The language and script of the titles of the release.</param>
|
||||
/// <param name="includeTextRepresentation">Whether the text representation should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="artistCredit">Optional. The artist credit of the release.</param>
|
||||
/// <param name="releaseGroup">Optional. The release group the release belongs to.</param>
|
||||
/// <param name="includeReleaseGroup">Whether the release group should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="labelInfo">Optional. The label information of the release.</param>
|
||||
/// <param name="media">Optional. The media of the release.</param>
|
||||
/// <param name="asin">Optional. The ASIN of the release.</param>
|
||||
/// <param name="includeAsin">Whether the ASIN should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="tags">Optional. The tags of the release.</param>
|
||||
/// <param name="genres">Optional. The genres of the release.</param>
|
||||
/// <param name="relations">Optional. The relationships of the release to other entities.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzReleaseResponse"/> instance.</returns>
|
||||
public MusicBrainzReleaseResponse Create(
|
||||
string? id = null,
|
||||
bool includeId = true,
|
||||
string? title = null,
|
||||
bool includeTitle = true,
|
||||
string? disambiguation = null,
|
||||
bool includeDisambiguation = true,
|
||||
string? status = null,
|
||||
bool includeStatus = true,
|
||||
string? date = null,
|
||||
bool includeDate = true,
|
||||
string? country = null,
|
||||
bool includeCountry = true,
|
||||
List<MusicBrainzReleaseEventResponse>? releaseEvents = null,
|
||||
string? barcode = null,
|
||||
bool includeBarcode = true,
|
||||
string? packaging = null,
|
||||
bool includePackaging = true,
|
||||
MusicBrainzTextRepresentationResponse? textRepresentation = null,
|
||||
bool includeTextRepresentation = true,
|
||||
List<MusicBrainzArtistCreditResponse>? artistCredit = null,
|
||||
MusicBrainzReleaseGroupResponse? releaseGroup = null,
|
||||
bool includeReleaseGroup = true,
|
||||
List<MusicBrainzLabelInfoResponse>? labelInfo = null,
|
||||
List<MusicBrainzMediumResponse>? media = null,
|
||||
string? asin = null,
|
||||
bool includeAsin = true,
|
||||
List<MusicBrainzTagResponse>? tags = null,
|
||||
List<MusicBrainzTagResponse>? genres = null,
|
||||
List<MusicBrainzRelationResponse>? relations = null)
|
||||
{
|
||||
return new MusicBrainzReleaseResponse
|
||||
{
|
||||
Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
|
||||
Title = includeTitle ? title ?? _faker.Commerce.ProductName() : null,
|
||||
Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
|
||||
Status = includeStatus ? status ?? _faker.PickRandom("Official", "Promotion", "Bootleg") : null,
|
||||
Date = includeDate ? date ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null,
|
||||
Country = includeCountry ? country ?? _faker.Address.CountryCode() : null,
|
||||
ReleaseEvents = releaseEvents ?? [.. _musicBrainzReleaseEventResponseFixture.CreateMany(1)],
|
||||
Barcode = includeBarcode ? barcode ?? _faker.Random.AlphaNumeric(12) : null,
|
||||
Packaging = includePackaging ? packaging ?? _faker.PickRandom("Jewel Case", "Digipak") : null,
|
||||
TextRepresentation = includeTextRepresentation ? textRepresentation ?? _musicBrainzTextRepresentationResponseFixture.Create() : null,
|
||||
ArtistCredit = artistCredit ?? [.. _musicBrainzArtistCreditResponseFixture.CreateMany(2)],
|
||||
ReleaseGroup = includeReleaseGroup ? releaseGroup ?? _musicBrainzReleaseGroupResponseFixture.Create() : null,
|
||||
LabelInfo = labelInfo ?? [.. _musicBrainzLabelInfoResponseFixture.CreateMany(1)],
|
||||
Media = media ?? [.. _musicBrainzMediumResponseFixture.CreateMany(1)],
|
||||
Asin = includeAsin ? asin ?? _faker.Random.AlphaNumeric(10) : null,
|
||||
Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
|
||||
Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
|
||||
Relations = relations ?? []
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzReleaseResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzReleaseResponse"/> instances.</returns>
|
||||
public List<MusicBrainzReleaseResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzTagResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzTagResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzTagResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The MusicBrainz identifier of a genre tag.</param>
|
||||
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="name">Optional. The name of the tag.</param>
|
||||
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="disambiguation">Optional. The disambiguation comment of a genre tag.</param>
|
||||
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="count">Optional. The number of votes the tag received.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzTagResponse"/> instance.</returns>
|
||||
public MusicBrainzTagResponse Create(
|
||||
string? id = null,
|
||||
bool includeId = true,
|
||||
string? name = null,
|
||||
bool includeName = true,
|
||||
string? disambiguation = null,
|
||||
bool includeDisambiguation = true,
|
||||
int? count = null)
|
||||
{
|
||||
return new MusicBrainzTagResponse
|
||||
{
|
||||
Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
|
||||
Name = includeName ? name ?? _faker.Lorem.Word() : null,
|
||||
Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
|
||||
Count = count ?? _faker.Random.Int(0, 100)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzTagResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzTagResponse"/> instances.</returns>
|
||||
public List<MusicBrainzTagResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzTextRepresentationResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzTextRepresentationResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzTextRepresentationResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="language">Optional. The ISO 639-3 language code of the release.</param>
|
||||
/// <param name="includeLanguage">Whether the language should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="script">Optional. The ISO 15924 script code of the release.</param>
|
||||
/// <param name="includeScript">Whether the script should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzTextRepresentationResponse"/> instance.</returns>
|
||||
public MusicBrainzTextRepresentationResponse Create(
|
||||
string? language = null,
|
||||
bool includeLanguage = true,
|
||||
string? script = null,
|
||||
bool includeScript = true)
|
||||
{
|
||||
return new MusicBrainzTextRepresentationResponse
|
||||
{
|
||||
Language = includeLanguage ? language ?? _faker.PickRandom("eng", "deu", "fra") : null,
|
||||
Script = includeScript ? script ?? _faker.PickRandom("Latn", "Cyrl", "Arab") : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzTextRepresentationResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzTextRepresentationResponse"/> instances.</returns>
|
||||
public List<MusicBrainzTextRepresentationResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzTrackResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzTrackResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzTrackResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The MusicBrainz identifier of the track.</param>
|
||||
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="number">Optional. The track number, as displayed on the medium.</param>
|
||||
/// <param name="includeNumber">Whether the number should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="position">Optional. The position of the track within its medium.</param>
|
||||
/// <param name="title">Optional. The title of the track.</param>
|
||||
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="length">Optional. The length of the track in milliseconds.</param>
|
||||
/// <param name="includeLength">Whether the length should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="recording">Optional. The recording the track is a performance of.</param>
|
||||
/// <param name="includeRecording">Whether the recording should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzTrackResponse"/> instance.</returns>
|
||||
public MusicBrainzTrackResponse Create(
|
||||
string? id = null,
|
||||
bool includeId = true,
|
||||
string? number = null,
|
||||
bool includeNumber = true,
|
||||
int? position = null,
|
||||
string? title = null,
|
||||
bool includeTitle = true,
|
||||
long? length = null,
|
||||
bool includeLength = true,
|
||||
MusicBrainzRecordingResponse? recording = null,
|
||||
bool includeRecording = true)
|
||||
{
|
||||
int resolvedPosition = position ?? _faker.Random.Int(1, 30);
|
||||
string? resolvedTitle = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null;
|
||||
return new MusicBrainzTrackResponse
|
||||
{
|
||||
Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
|
||||
Number = includeNumber ? number ?? resolvedPosition.ToString() : null,
|
||||
Position = resolvedPosition,
|
||||
Title = resolvedTitle,
|
||||
Length = includeLength ? length ?? _faker.Random.Long(30_000, 600_000) : null,
|
||||
Recording = includeRecording ? recording ?? _musicBrainzRecordingResponseFixture.Create(title: resolvedTitle) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzTrackResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzTrackResponse"/> instances.</returns>
|
||||
public List<MusicBrainzTrackResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(index => Create(position: index + 1))];
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzUrlResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzUrlResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzUrlResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The MusicBrainz identifier of the URL.</param>
|
||||
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="resource">Optional. The resource the URL points to.</param>
|
||||
/// <param name="includeResource">Whether the resource should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzUrlResponse"/> instance.</returns>
|
||||
public MusicBrainzUrlResponse Create(
|
||||
string? id = null,
|
||||
bool includeId = true,
|
||||
string? resource = null,
|
||||
bool includeResource = true)
|
||||
{
|
||||
return new MusicBrainzUrlResponse
|
||||
{
|
||||
Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
|
||||
Resource = includeResource ? resource ?? _faker.Internet.Url() : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzUrlResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzUrlResponse"/> instances.</returns>
|
||||
public List<MusicBrainzUrlResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzWorkResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzWorkResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new();
|
||||
private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzWorkResponse"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The MusicBrainz identifier of the work.</param>
|
||||
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="title">Optional. The title of the work.</param>
|
||||
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="type">Optional. The MusicBrainz type of the work.</param>
|
||||
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="disambiguation">Optional. The disambiguation comment of the work.</param>
|
||||
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="languages">Optional. The languages of the work.</param>
|
||||
/// <param name="iswcs">Optional. The ISWCs of the work.</param>
|
||||
/// <param name="relations">Optional. The relationships of the work to other entities.</param>
|
||||
/// <param name="tags">Optional. The tags of the work.</param>
|
||||
/// <param name="genres">Optional. The genres of the work.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzWorkResponse"/> instance.</returns>
|
||||
public MusicBrainzWorkResponse Create(
|
||||
string? id = null,
|
||||
bool includeId = true,
|
||||
string? title = null,
|
||||
bool includeTitle = true,
|
||||
string? type = null,
|
||||
bool includeType = true,
|
||||
string? disambiguation = null,
|
||||
bool includeDisambiguation = true,
|
||||
List<string>? languages = null,
|
||||
List<string>? iswcs = null,
|
||||
List<MusicBrainzRelationResponse>? relations = null,
|
||||
List<MusicBrainzTagResponse>? tags = null,
|
||||
List<MusicBrainzTagResponse>? genres = null)
|
||||
{
|
||||
return new MusicBrainzWorkResponse
|
||||
{
|
||||
Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
|
||||
Title = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null,
|
||||
Type = includeType ? type ?? _faker.PickRandom("Song", "Aria", "Symphony") : null,
|
||||
Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
|
||||
Languages = languages ?? [_faker.PickRandom("eng", "deu", "fra")],
|
||||
Iswcs = iswcs ?? [$"T-{_faker.Random.Int(100, 999)}.{_faker.Random.Int(100, 999)}.{_faker.Random.Int(100, 999)}-{_faker.Random.Int(1, 9)}"],
|
||||
Relations = relations ?? [.. _musicBrainzRelationResponseFixture.CreateMany(2)],
|
||||
Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
|
||||
Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)]
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzWorkResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzWorkResponse"/> instances.</returns>
|
||||
public List<MusicBrainzWorkResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicBrainzSettingsDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class MusicBrainzSettingsDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicBrainzSettingsDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="baseUrl">Optional. The base URL of the MusicBrainz web service.</param>
|
||||
/// <param name="doesAllowPrivateBaseUrl">Optional. Whether the base URL may point at a private or local host.</param>
|
||||
/// <param name="userAgent">Optional. The user agent sent with every request.</param>
|
||||
/// <param name="contactEmail">Optional. The contact email sent to the MusicBrainz API.</param>
|
||||
/// <param name="includeContactEmail">Whether the contact email should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="searchResultLimit">Optional. The maximum number of results returned by a single search.</param>
|
||||
/// <param name="releaseLookupLimit">Optional. The maximum number of releases fetched for a single release group.</param>
|
||||
/// <param name="minimumRequestInterval">Optional. The minimum interval between consecutive requests.</param>
|
||||
/// <returns>A configured <see cref="MusicBrainzSettingsDto"/> instance.</returns>
|
||||
public MusicBrainzSettingsDto Create(
|
||||
string? baseUrl = null,
|
||||
bool? doesAllowPrivateBaseUrl = null,
|
||||
string? userAgent = null,
|
||||
string? contactEmail = null,
|
||||
bool includeContactEmail = true,
|
||||
int? searchResultLimit = null,
|
||||
int? releaseLookupLimit = null,
|
||||
TimeSpan? minimumRequestInterval = null)
|
||||
{
|
||||
return new MusicBrainzSettingsDto
|
||||
{
|
||||
BaseUrl = baseUrl ?? _faker.Internet.Url(),
|
||||
DoesAllowPrivateBaseUrl = doesAllowPrivateBaseUrl ?? _faker.Random.Bool(),
|
||||
UserAgent = userAgent ?? $"Lumina-MusicBrainz/{_faker.Random.Int(1, 9)}.{_faker.Random.Int(0, 9)}",
|
||||
ContactEmail = includeContactEmail ? contactEmail ?? _faker.Internet.Email() : null,
|
||||
SearchResultLimit = searchResultLimit ?? _faker.Random.Int(1, 100),
|
||||
ReleaseLookupLimit = releaseLookupLimit ?? _faker.Random.Int(1, 100),
|
||||
MinimumRequestInterval = minimumRequestInterval ?? TimeSpan.FromSeconds(_faker.Random.Double(0, 5))
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicBrainzSettingsDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicBrainzSettingsDto"/> instances.</returns>
|
||||
public List<MusicBrainzSettingsDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture" />
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" />
|
||||
<PackageReference Include="Bogus" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.MusicBrainz\Lumina.Plugins.MusicBrainz.csproj" />
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("Lumina.Plugins.MusicBrainz.Fixtures")]
|
||||
[assembly: AssemblyProduct("Lumina.Plugins.MusicBrainz.Fixtures")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72")]
|
||||
|
||||
[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.UnitTests")]
|
||||
[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.IntegrationTests")]
|
||||
[assembly: InternalsVisibleTo("Lumina.Presentation.Api.SecurityTests")]
|
||||
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Lumina.Plugins.MusicBrainz.Common.DependencyInjection;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.MusicBrainz.Core;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Api;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Settings;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzServices"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzServicesTests
|
||||
{
|
||||
[Fact]
|
||||
public void AddMusicBrainzMetadataProviders_WhenServicesIsNull_ShouldThrowArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
IServiceCollection services = null!;
|
||||
|
||||
// Act
|
||||
Action act = () => services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.Throws<ArgumentNullException>(act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldReturnTheSameServiceCollection()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
IServiceCollection result = services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.Same(services, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheThreeMetadataProvidersForKeyedResolution()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
services.AddMusicBrainzMetadataProviders(pluginId: pluginId);
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(3, serviceProvider.GetKeyedServices<IMetadataProvider>(pluginId).Count());
|
||||
Assert.Empty(serviceProvider.GetKeyedServices<IMetadataProvider>(Guid.NewGuid()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheSettingsProviderAsScoped()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
ServiceDescriptor settingsProviderDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzSettingsProvider));
|
||||
Assert.Equal(ServiceLifetime.Scoped, settingsProviderDescriptor.Lifetime);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheThrottleAndTheResponseCacheAsSingletons()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
ServiceDescriptor throttleDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzRequestThrottle));
|
||||
ServiceDescriptor responseCacheDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzResponseCache));
|
||||
Assert.Equal(ServiceLifetime.Singleton, throttleDescriptor.Lifetime);
|
||||
Assert.Equal(ServiceLifetime.Singleton, responseCacheDescriptor.Lifetime);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheHttpClient()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid());
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(serviceProvider.GetService<MusicBrainzHttpClient>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddMusicBrainzMetadataProviders_WhenASettingsCallbackIsProvided_ShouldApplyItToTheDefaults()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
services.AddMusicBrainzMetadataProviders(pluginId: pluginId, settings => settings.BaseUrl = "http://custom.example/ws/2/");
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
using (IServiceScope scope = serviceProvider.CreateScope())
|
||||
{
|
||||
MusicBrainzSettingsProvider settingsProvider = scope.ServiceProvider.GetRequiredService<MusicBrainzSettingsProvider>();
|
||||
MusicBrainzSettingsDto settings = await settingsProvider.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("http://custom.example/ws/2/", settings.BaseUrl);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddMusicBrainzMetadataProviders_WhenCalledTwice_ShouldNotDuplicateTheTryAddServices()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
services.AddMusicBrainzMetadataProviders(pluginId: pluginId);
|
||||
services.AddMusicBrainzMetadataProviders(pluginId: pluginId);
|
||||
|
||||
// Assert
|
||||
// The settings provider, the throttle and the response cache are registered with TryAdd, so a second call must not add them again.
|
||||
Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzRequestThrottle));
|
||||
Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzResponseCache));
|
||||
Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzSettingsProvider));
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzAliasResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzAliasResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void IsEnded_WhenTheMusicBrainzApiReturnsNull_ShouldDeserializeAsNull()
|
||||
{
|
||||
// Arrange
|
||||
// the MusicBrainz search API can return a null ended flag for aliases, which used to break deserialization into a non-nullable boolean
|
||||
const string JSON = """{"name":"Rammstein","ended":null}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzAliasResponse? response = JsonSerializer.Deserialize<MusicBrainzAliasResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Null(response.IsEnded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsEnded_WhenTheMusicBrainzApiReturnsTrue_ShouldDeserializeAsTrue()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"name":"Rammstein","ended":true}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzAliasResponse? response = JsonSerializer.Deserialize<MusicBrainzAliasResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.True(response.IsEnded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"name": "Alias Name",
|
||||
"sort-name": "Alias Sort Name",
|
||||
"type": "Artist name",
|
||||
"locale": "en",
|
||||
"primary": true,
|
||||
"begin": "1994-01-01",
|
||||
"end": "2020-12-31",
|
||||
"ended": true
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzAliasResponse? response = JsonSerializer.Deserialize<MusicBrainzAliasResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("Alias Name", response.Name);
|
||||
Assert.Equal("Alias Sort Name", response.SortName);
|
||||
Assert.Equal("Artist name", response.Type);
|
||||
Assert.Equal("en", response.Locale);
|
||||
Assert.True(response.IsPrimary);
|
||||
Assert.Equal("1994-01-01", response.Begin);
|
||||
Assert.Equal("2020-12-31", response.End);
|
||||
Assert.True(response.IsEnded);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzAreaResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzAreaResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void SortNameTypeAndIsoCodes_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "c0e0e0e0-0000-0000-0000-000000000000",
|
||||
"name": "United Kingdom",
|
||||
"sort-name": "United Kingdom",
|
||||
"type": "Country",
|
||||
"iso-3166-1-codes": [ "GB" ],
|
||||
"iso-3166-2-codes": [ "GB-ENG" ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzAreaResponse? response = JsonSerializer.Deserialize<MusicBrainzAreaResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("United Kingdom", response.SortName);
|
||||
Assert.Equal("Country", response.Type);
|
||||
Assert.Equal("GB", Assert.Single(response.Iso3166Part1Codes));
|
||||
Assert.Equal("GB-ENG", Assert.Single(response.Iso3166Part2Codes));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "area-id",
|
||||
"name": "United Kingdom",
|
||||
"sort-name": "United Kingdom",
|
||||
"disambiguation": "The United Kingdom of Great Britain",
|
||||
"type": "Country",
|
||||
"iso-3166-1-codes": [ "GB" ],
|
||||
"iso-3166-2-codes": [ "GB-ENG" ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzAreaResponse? response = JsonSerializer.Deserialize<MusicBrainzAreaResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("area-id", response.Id);
|
||||
Assert.Equal("United Kingdom", response.Name);
|
||||
Assert.Equal("United Kingdom", response.SortName);
|
||||
Assert.Equal("The United Kingdom of Great Britain", response.Disambiguation);
|
||||
Assert.Equal("Country", response.Type);
|
||||
Assert.Equal("GB", Assert.Single(response.Iso3166Part1Codes));
|
||||
Assert.Equal("GB-ENG", Assert.Single(response.Iso3166Part2Codes));
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzArtistCreditResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzArtistCreditResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void NameJoinPhraseAndArtist_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"name":"Freddie Mercury","joinphrase":" & ","artist":{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Freddie Mercury"}}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzArtistCreditResponse? response = JsonSerializer.Deserialize<MusicBrainzArtistCreditResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("Freddie Mercury", response.Name);
|
||||
Assert.Equal(" & ", response.JoinPhrase);
|
||||
Assert.NotNull(response.Artist);
|
||||
Assert.Equal("Freddie Mercury", response.Artist.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"name": "Freddie Mercury",
|
||||
"joinphrase": " & ",
|
||||
"artist": { "id": "artist-id", "name": "Freddie Mercury" }
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzArtistCreditResponse? response = JsonSerializer.Deserialize<MusicBrainzArtistCreditResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("Freddie Mercury", response.Name);
|
||||
Assert.Equal(" & ", response.JoinPhrase);
|
||||
Assert.NotNull(response.Artist);
|
||||
Assert.Equal("artist-id", response.Artist.Id);
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzArtistResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzArtistResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void SortNameTypeCountryAndCodes_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "cb6c5931-436c-38c5-9d24-044f37d1fe35",
|
||||
"name": "Queen",
|
||||
"sort-name": "Queen",
|
||||
"type": "Group",
|
||||
"gender": null,
|
||||
"country": "GB",
|
||||
"life-span": { "begin": "1970", "ended": false },
|
||||
"ipis": [ "00000000000" ],
|
||||
"isnis": [ "0000000000000000" ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzArtistResponse? response = JsonSerializer.Deserialize<MusicBrainzArtistResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("Queen", response.SortName);
|
||||
Assert.Equal("Group", response.Type);
|
||||
Assert.Equal("GB", response.Country);
|
||||
Assert.Equal("00000000000", Assert.Single(response.Ipis));
|
||||
Assert.Equal("0000000000000000", Assert.Single(response.Isnis));
|
||||
Assert.NotNull(response.LifeSpan);
|
||||
Assert.Equal("1970", response.LifeSpan.Begin);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "artist-id",
|
||||
"name": "Queen",
|
||||
"sort-name": "Queen",
|
||||
"disambiguation": "UK rock band",
|
||||
"type": "Group",
|
||||
"gender": "Male",
|
||||
"country": "GB",
|
||||
"area": { "id": "area-id", "name": "United Kingdom" },
|
||||
"begin-area": { "id": "begin-area-id", "name": "London" },
|
||||
"end-area": { "id": "end-area-id", "name": "Montreux" },
|
||||
"life-span": { "begin": "1970", "end": "1991", "ended": true },
|
||||
"isnis": [ "isni-1" ],
|
||||
"ipis": [ "ipi-1" ],
|
||||
"aliases": [ { "name": "Queen alias" } ],
|
||||
"tags": [ { "name": "rock", "count": 5 } ],
|
||||
"genres": [ { "id": "genre-id", "name": "Rock" } ],
|
||||
"relations": [ { "type": "member of band", "artist": { "id": "member-id", "name": "Freddie Mercury" } } ],
|
||||
"rating": { "value": 4.5, "votes-count": 10 }
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzArtistResponse? response = JsonSerializer.Deserialize<MusicBrainzArtistResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("artist-id", response.Id);
|
||||
Assert.Equal("Queen", response.Name);
|
||||
Assert.Equal("Queen", response.SortName);
|
||||
Assert.Equal("UK rock band", response.Disambiguation);
|
||||
Assert.Equal("Group", response.Type);
|
||||
Assert.Equal("Male", response.Gender);
|
||||
Assert.Equal("GB", response.Country);
|
||||
Assert.NotNull(response.Area);
|
||||
Assert.Equal("United Kingdom", response.Area.Name);
|
||||
Assert.NotNull(response.BeginArea);
|
||||
Assert.Equal("London", response.BeginArea.Name);
|
||||
Assert.NotNull(response.EndArea);
|
||||
Assert.Equal("Montreux", response.EndArea.Name);
|
||||
Assert.NotNull(response.LifeSpan);
|
||||
Assert.Equal("1970", response.LifeSpan.Begin);
|
||||
Assert.Equal("isni-1", Assert.Single(response.Isnis));
|
||||
Assert.Equal("ipi-1", Assert.Single(response.Ipis));
|
||||
Assert.Equal("Queen alias", Assert.Single(response.Aliases).Name);
|
||||
Assert.Equal("rock", Assert.Single(response.Tags).Name);
|
||||
Assert.Equal("Rock", Assert.Single(response.Genres).Name);
|
||||
Assert.Equal("member of band", Assert.Single(response.Relations).Type);
|
||||
Assert.NotNull(response.Rating);
|
||||
Assert.Equal(4.5m, response.Rating.Value);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzArtistSearchResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzArtistSearchResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void CountOffsetAndArtists_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"count":1,"offset":0,"artists":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Queen"}]}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzArtistSearchResponse? response = JsonSerializer.Deserialize<MusicBrainzArtistSearchResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal(1, response.Count);
|
||||
Assert.Equal(0, response.Offset);
|
||||
Assert.Equal("Queen", Assert.Single(response.Artists).Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"count": 2,
|
||||
"offset": 1,
|
||||
"artists": [ { "id": "artist-id", "name": "Queen" } ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzArtistSearchResponse? response = JsonSerializer.Deserialize<MusicBrainzArtistSearchResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal(2, response.Count);
|
||||
Assert.Equal(1, response.Offset);
|
||||
Assert.Equal("artist-id", Assert.Single(response.Artists).Id);
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzLabelInfoResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzLabelInfoResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void CatalogNumberAndLabel_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"catalog-number":"EMC 4008","label":{"id":"f0e0e0e0-0000-0000-0000-000000000000","name":"EMI"}}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzLabelInfoResponse? response = JsonSerializer.Deserialize<MusicBrainzLabelInfoResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("EMC 4008", response.CatalogNumber);
|
||||
Assert.NotNull(response.Label);
|
||||
Assert.Equal("EMI", response.Label.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"catalog-number": "EMC 4008",
|
||||
"label": { "id": "label-id", "name": "EMI" }
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzLabelInfoResponse? response = JsonSerializer.Deserialize<MusicBrainzLabelInfoResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("EMC 4008", response.CatalogNumber);
|
||||
Assert.NotNull(response.Label);
|
||||
Assert.Equal("EMI", response.Label.Name);
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzLabelResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzLabelResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void NameDisambiguationAndLabelCode_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"id":"f0e0e0e0-0000-0000-0000-000000000000","name":"EMI","disambiguation":"EMI Records Ltd.","label-code":1234}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzLabelResponse? response = JsonSerializer.Deserialize<MusicBrainzLabelResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("EMI", response.Name);
|
||||
Assert.Equal("EMI Records Ltd.", response.Disambiguation);
|
||||
Assert.Equal(1234, response.LabelCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "label-id",
|
||||
"name": "EMI",
|
||||
"disambiguation": "EMI Records Ltd.",
|
||||
"label-code": 1234
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzLabelResponse? response = JsonSerializer.Deserialize<MusicBrainzLabelResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("label-id", response.Id);
|
||||
Assert.Equal("EMI", response.Name);
|
||||
Assert.Equal("EMI Records Ltd.", response.Disambiguation);
|
||||
Assert.Equal(1234, response.LabelCode);
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzLifeSpanResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzLifeSpanResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void IsEnded_WhenTheMusicBrainzApiReturnsNull_ShouldDeserializeAsNull()
|
||||
{
|
||||
// Arrange
|
||||
// the MusicBrainz search API returns a null ended flag for artists whose end status is unknown, which used to break deserialization into a non-nullable boolean
|
||||
const string JSON = """{"begin":"1994-01","ended":null}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzLifeSpanResponse? response = JsonSerializer.Deserialize<MusicBrainzLifeSpanResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Null(response.IsEnded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsEnded_WhenTheMusicBrainzApiReturnsTrue_ShouldDeserializeAsTrue()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"begin":"1970-06-27","ended":true}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzLifeSpanResponse? response = JsonSerializer.Deserialize<MusicBrainzLifeSpanResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.True(response.IsEnded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"begin": "1970-06-27",
|
||||
"end": "1991-11-24",
|
||||
"ended": true
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzLifeSpanResponse? response = JsonSerializer.Deserialize<MusicBrainzLifeSpanResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("1970-06-27", response.Begin);
|
||||
Assert.Equal("1991-11-24", response.End);
|
||||
Assert.True(response.IsEnded);
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzMediumResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzMediumResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void PositionFormatAndTrackCount_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"position":1,"title":"Disc 1","format":"CD","track-count":12}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzMediumResponse? response = JsonSerializer.Deserialize<MusicBrainzMediumResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal(1, response.Position);
|
||||
Assert.Equal("Disc 1", response.Title);
|
||||
Assert.Equal("CD", response.Format);
|
||||
Assert.Equal(12, response.TrackCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"position": 2,
|
||||
"title": "Disc 2",
|
||||
"format": "Vinyl",
|
||||
"track-count": 8,
|
||||
"tracks": [ { "id": "track-id", "number": "A1", "position": 1, "title": "Death on Two Legs" } ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzMediumResponse? response = JsonSerializer.Deserialize<MusicBrainzMediumResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal(2, response.Position);
|
||||
Assert.Equal("Disc 2", response.Title);
|
||||
Assert.Equal("Vinyl", response.Format);
|
||||
Assert.Equal(8, response.TrackCount);
|
||||
Assert.Equal("track-id", Assert.Single(response.Tracks).Id);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzRatingResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzRatingResponseTests
|
||||
{
|
||||
private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
NumberHandling = JsonNumberHandling.AllowReadingFromString
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void ValueAndVotesCount_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"value":4.5,"votes-count":10}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzRatingResponse? response = JsonSerializer.Deserialize<MusicBrainzRatingResponse>(JSON, s_serializerOptions);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal(4.5m, response.Value);
|
||||
Assert.Equal(10, response.VotesCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValueAndVotesCount_WhenTheMusicBrainzApiReturnsStrings_ShouldStillDeserializeThem()
|
||||
{
|
||||
// Arrange
|
||||
// The MusicBrainz search API sometimes returns the rating numbers as strings.
|
||||
const string JSON = """{"value":"4.5","votes-count":"10"}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzRatingResponse? response = JsonSerializer.Deserialize<MusicBrainzRatingResponse>(JSON, s_serializerOptions);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal(4.5m, response.Value);
|
||||
Assert.Equal(10, response.VotesCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"value":4.5,"votes-count":10}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzRatingResponse? response = JsonSerializer.Deserialize<MusicBrainzRatingResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal(4.5m, response.Value);
|
||||
Assert.Equal(10, response.VotesCount);
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzRecordingListResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzRecordingListResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void Recordings_WhenReturnedByTheMusicBrainzIsrcLookup_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs","isrcs":["GBUM71029604"]}]}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzRecordingListResponse? response = JsonSerializer.Deserialize<MusicBrainzRecordingListResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
MusicBrainzRecordingResponse recording = Assert.Single(response.Recordings);
|
||||
Assert.Equal("Death on Two Legs", recording.Title);
|
||||
Assert.Equal("GBUM71029604", Assert.Single(recording.Isrcs));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"recordings": [ { "id": "recording-id", "title": "Death on Two Legs", "isrcs": [ "GBUM71029604" ] } ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzRecordingListResponse? response = JsonSerializer.Deserialize<MusicBrainzRecordingListResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
MusicBrainzRecordingResponse recording = Assert.Single(response.Recordings);
|
||||
Assert.Equal("recording-id", recording.Id);
|
||||
Assert.Equal("Death on Two Legs", recording.Title);
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzRecordingResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzRecordingResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void IsVideo_WhenTheMusicBrainzApiReturnsNull_ShouldDeserializeAsNull()
|
||||
{
|
||||
// Arrange
|
||||
// The MusicBrainz search API returns a null video flag for most recordings, which used to break deserialization into a non-nullable boolean.
|
||||
const string JSON = """{"id":"8778bb30-2f72-4bc8-8b71-cdbe084036c3","title":"A Kind of Magic","video":null}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzRecordingResponse? response = JsonSerializer.Deserialize<MusicBrainzRecordingResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Null(response.IsVideo);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsVideo_WhenTheMusicBrainzApiReturnsFalse_ShouldDeserializeAsFalse()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"id":"8778bb30-2f72-4bc8-8b71-cdbe084036c3","title":"A Kind of Magic","video":false}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzRecordingResponse? response = JsonSerializer.Deserialize<MusicBrainzRecordingResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.False(response.IsVideo);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "recording-id",
|
||||
"title": "Bohemian Rhapsody",
|
||||
"disambiguation": "album version",
|
||||
"length": 354000,
|
||||
"video": true,
|
||||
"first-release-date": "1975-10-31",
|
||||
"artist-credit": [ { "name": "Queen", "artist": { "id": "artist-id", "name": "Queen" } } ],
|
||||
"isrcs": [ "GBUM71029604" ],
|
||||
"releases": [ { "id": "release-id", "title": "A Night at the Opera" } ],
|
||||
"tags": [ { "name": "rock", "count": 5 } ],
|
||||
"genres": [ { "id": "genre-id", "name": "Rock" } ],
|
||||
"relations": [ { "type": "performance", "work": { "id": "work-id", "title": "Bohemian Rhapsody" } } ],
|
||||
"rating": { "value": 4.5, "votes-count": 10 }
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzRecordingResponse? response = JsonSerializer.Deserialize<MusicBrainzRecordingResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("recording-id", response.Id);
|
||||
Assert.Equal("Bohemian Rhapsody", response.Title);
|
||||
Assert.Equal("album version", response.Disambiguation);
|
||||
Assert.Equal(354000, response.Length);
|
||||
Assert.True(response.IsVideo);
|
||||
Assert.Equal("1975-10-31", response.FirstReleaseDate);
|
||||
Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name);
|
||||
Assert.Equal("GBUM71029604", Assert.Single(response.Isrcs));
|
||||
Assert.Equal("release-id", Assert.Single(response.Releases).Id);
|
||||
Assert.Equal("rock", Assert.Single(response.Tags).Name);
|
||||
Assert.Equal("Rock", Assert.Single(response.Genres).Name);
|
||||
Assert.Equal("performance", Assert.Single(response.Relations).Type);
|
||||
Assert.NotNull(response.Rating);
|
||||
Assert.Equal(4.5m, response.Rating.Value);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzRecordingSearchResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzRecordingSearchResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void CountOffsetAndRecordings_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"count":1,"offset":0,"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs"}]}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzRecordingSearchResponse? response = JsonSerializer.Deserialize<MusicBrainzRecordingSearchResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal(1, response.Count);
|
||||
Assert.Equal(0, response.Offset);
|
||||
Assert.Equal("Death on Two Legs", Assert.Single(response.Recordings).Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"count": 3,
|
||||
"offset": 2,
|
||||
"recordings": [ { "id": "recording-id", "title": "Death on Two Legs" } ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzRecordingSearchResponse? response = JsonSerializer.Deserialize<MusicBrainzRecordingSearchResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal(3, response.Count);
|
||||
Assert.Equal(2, response.Offset);
|
||||
Assert.Equal("recording-id", Assert.Single(response.Recordings).Id);
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzRelationResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzRelationResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void TypeTargetTypeArtistAndAttributes_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"type": "producer",
|
||||
"type-id": "d0e0e0e0-0000-0000-0000-000000000000",
|
||||
"direction": "backward",
|
||||
"target-type": "artist",
|
||||
"artist": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", "name": "Roy Thomas Baker" },
|
||||
"attributes": [ "producer" ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzRelationResponse? response = JsonSerializer.Deserialize<MusicBrainzRelationResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("producer", response.Type);
|
||||
Assert.Equal("backward", response.Direction);
|
||||
Assert.Equal("artist", response.TargetType);
|
||||
Assert.NotNull(response.Artist);
|
||||
Assert.Equal("Roy Thomas Baker", response.Artist.Name);
|
||||
Assert.Equal("producer", Assert.Single(response.Attributes));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"type": "producer",
|
||||
"type-id": "type-id",
|
||||
"direction": "backward",
|
||||
"target-type": "artist",
|
||||
"artist": { "id": "artist-id", "name": "Roy Thomas Baker" },
|
||||
"work": { "id": "work-id", "title": "Bohemian Rhapsody" },
|
||||
"url": { "id": "url-id", "resource": "https://example.com/" },
|
||||
"attributes": [ "producer" ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzRelationResponse? response = JsonSerializer.Deserialize<MusicBrainzRelationResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("producer", response.Type);
|
||||
Assert.Equal("type-id", response.TypeId);
|
||||
Assert.Equal("backward", response.Direction);
|
||||
Assert.Equal("artist", response.TargetType);
|
||||
Assert.NotNull(response.Artist);
|
||||
Assert.Equal("Roy Thomas Baker", response.Artist.Name);
|
||||
Assert.NotNull(response.Work);
|
||||
Assert.Equal("Bohemian Rhapsody", response.Work.Title);
|
||||
Assert.NotNull(response.Url);
|
||||
Assert.Equal("https://example.com/", response.Url.Resource);
|
||||
Assert.Equal("producer", Assert.Single(response.Attributes));
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzReleaseBrowseResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzReleaseBrowseResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void ReleaseCountReleaseOffsetAndReleases_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"release-count":5,"release-offset":2,"releases":[{"id":"11111111-1111-1111-1111-111111111111","title":"A Night at the Opera"}]}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzReleaseBrowseResponse? response = JsonSerializer.Deserialize<MusicBrainzReleaseBrowseResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal(5, response.ReleaseCount);
|
||||
Assert.Equal(2, response.ReleaseOffset);
|
||||
Assert.Equal("A Night at the Opera", Assert.Single(response.Releases).Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"releases": [ { "id": "release-id", "title": "A Night at the Opera" } ],
|
||||
"release-count": 5,
|
||||
"release-offset": 2
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzReleaseBrowseResponse? response = JsonSerializer.Deserialize<MusicBrainzReleaseBrowseResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("release-id", Assert.Single(response.Releases).Id);
|
||||
Assert.Equal(5, response.ReleaseCount);
|
||||
Assert.Equal(2, response.ReleaseOffset);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzReleaseEventResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzReleaseEventResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void DateAndArea_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"date":"1975-11-21","area":{"id":"c0e0e0e0-0000-0000-0000-000000000000","name":"United Kingdom","iso-3166-1-codes":["GB"]}}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzReleaseEventResponse? response = JsonSerializer.Deserialize<MusicBrainzReleaseEventResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("1975-11-21", response.Date);
|
||||
Assert.NotNull(response.Area);
|
||||
Assert.Equal("United Kingdom", response.Area.Name);
|
||||
Assert.Equal("GB", Assert.Single(response.Area.Iso3166Part1Codes));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"date": "1975-11-21",
|
||||
"area": { "id": "area-id", "name": "United Kingdom" }
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzReleaseEventResponse? response = JsonSerializer.Deserialize<MusicBrainzReleaseEventResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("1975-11-21", response.Date);
|
||||
Assert.NotNull(response.Area);
|
||||
Assert.Equal("area-id", response.Area.Id);
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzReleaseGroupResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzReleaseGroupResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void PrimaryTypeSecondaryTypesAndFirstReleaseDate_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "22222222-2222-2222-2222-222222222222",
|
||||
"title": "A Night at the Opera",
|
||||
"primary-type": "Album",
|
||||
"secondary-types": [ "Live" ],
|
||||
"first-release-date": "1975-11-21",
|
||||
"artist-credit": [ { "name": "Queen", "artist": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35" } } ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzReleaseGroupResponse? response = JsonSerializer.Deserialize<MusicBrainzReleaseGroupResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("Album", response.PrimaryType);
|
||||
Assert.Equal("Live", Assert.Single(response.SecondaryTypes));
|
||||
Assert.Equal("1975-11-21", response.FirstReleaseDate);
|
||||
Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "release-group-id",
|
||||
"title": "A Night at the Opera",
|
||||
"disambiguation": "1975 album",
|
||||
"primary-type": "Album",
|
||||
"secondary-types": [ "Live" ],
|
||||
"first-release-date": "1975-11-21",
|
||||
"artist-credit": [ { "name": "Queen", "artist": { "id": "artist-id" } } ],
|
||||
"releases": [ { "id": "release-id", "title": "A Night at the Opera" } ],
|
||||
"tags": [ { "name": "rock", "count": 5 } ],
|
||||
"genres": [ { "id": "genre-id", "name": "Rock" } ],
|
||||
"rating": { "value": 4.5, "votes-count": 10 }
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzReleaseGroupResponse? response = JsonSerializer.Deserialize<MusicBrainzReleaseGroupResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("release-group-id", response.Id);
|
||||
Assert.Equal("A Night at the Opera", response.Title);
|
||||
Assert.Equal("1975 album", response.Disambiguation);
|
||||
Assert.Equal("Album", response.PrimaryType);
|
||||
Assert.Equal("Live", Assert.Single(response.SecondaryTypes));
|
||||
Assert.Equal("1975-11-21", response.FirstReleaseDate);
|
||||
Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name);
|
||||
Assert.Equal("release-id", Assert.Single(response.Releases).Id);
|
||||
Assert.Equal("rock", Assert.Single(response.Tags).Name);
|
||||
Assert.Equal("Rock", Assert.Single(response.Genres).Name);
|
||||
Assert.NotNull(response.Rating);
|
||||
Assert.Equal(4.5m, response.Rating.Value);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzReleaseGroupSearchResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzReleaseGroupSearchResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void CountOffsetAndReleaseGroups_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"count":2,"offset":1,"release-groups":[{"id":"22222222-2222-2222-2222-222222222222","title":"A Night at the Opera"}]}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzReleaseGroupSearchResponse? response = JsonSerializer.Deserialize<MusicBrainzReleaseGroupSearchResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal(2, response.Count);
|
||||
Assert.Equal(1, response.Offset);
|
||||
Assert.Equal("A Night at the Opera", Assert.Single(response.ReleaseGroups).Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"count": 2,
|
||||
"offset": 1,
|
||||
"release-groups": [ { "id": "release-group-id", "title": "A Night at the Opera" } ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzReleaseGroupSearchResponse? response = JsonSerializer.Deserialize<MusicBrainzReleaseGroupSearchResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal(2, response.Count);
|
||||
Assert.Equal(1, response.Offset);
|
||||
Assert.Equal("release-group-id", Assert.Single(response.ReleaseGroups).Id);
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzReleaseResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzReleaseResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void Media_WhenTheRequestIncludesRecordings_ShouldDeserializeTheTracksAndTheirRecordingsWithTheirWorks()
|
||||
{
|
||||
// Arrange
|
||||
// The recordings included in a release lookup already carry the fields the per track lookups return, including the work of each recording.
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "1e14b2d6-8652-3dcc-b60b-4fb5fe79e024",
|
||||
"title": "A Night at the Opera",
|
||||
"media": [
|
||||
{
|
||||
"position": 1,
|
||||
"track-count": 1,
|
||||
"tracks": [
|
||||
{
|
||||
"id": "b1e2c3d4-0000-0000-0000-000000000000",
|
||||
"number": "1",
|
||||
"position": 1,
|
||||
"title": "Death on Two Legs",
|
||||
"length": 223293,
|
||||
"recording": {
|
||||
"id": "cb6c5931-436c-38c5-9d24-044f37d1fe35",
|
||||
"title": "Death on Two Legs (Dedicated To...)",
|
||||
"video": null,
|
||||
"isrcs": [ "GBUM71029604" ],
|
||||
"relations": [
|
||||
{
|
||||
"target-type": "work",
|
||||
"type": "performance",
|
||||
"work": {
|
||||
"id": "d0e0e0e0-0000-0000-0000-000000000000",
|
||||
"title": "Death on Two Legs",
|
||||
"type": "Song",
|
||||
"languages": [ "eng" ],
|
||||
"iswcs": [ "T-010.154.482-4" ]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzReleaseResponse? response = JsonSerializer.Deserialize<MusicBrainzReleaseResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
MusicBrainzMediumResponse medium = Assert.Single(response.Media);
|
||||
Assert.Equal(1, medium.TrackCount);
|
||||
MusicBrainzTrackResponse track = Assert.Single(medium.Tracks);
|
||||
Assert.Equal(1, track.Position);
|
||||
Assert.NotNull(track.Recording);
|
||||
Assert.Equal("cb6c5931-436c-38c5-9d24-044f37d1fe35", track.Recording.Id);
|
||||
Assert.Equal("Death on Two Legs (Dedicated To...)", track.Recording.Title);
|
||||
Assert.Null(track.Recording.IsVideo);
|
||||
Assert.Equal("GBUM71029604", Assert.Single(track.Recording.Isrcs));
|
||||
MusicBrainzRelationResponse relation = Assert.Single(track.Recording.Relations);
|
||||
Assert.NotNull(relation.Work);
|
||||
Assert.Equal("Death on Two Legs", relation.Work.Title);
|
||||
Assert.Equal("eng", Assert.Single(relation.Work.Languages));
|
||||
Assert.Equal("T-010.154.482-4", Assert.Single(relation.Work.Iswcs));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "release-id",
|
||||
"title": "A Night at the Opera",
|
||||
"disambiguation": "1975 album",
|
||||
"status": "Official",
|
||||
"date": "1975-11-21",
|
||||
"country": "GB",
|
||||
"release-events": [ { "date": "1975-11-21", "area": { "id": "area-id", "name": "United Kingdom" } } ],
|
||||
"barcode": "0094639819524",
|
||||
"packaging": "Jewel Case",
|
||||
"text-representation": { "language": "eng", "script": "Latn" },
|
||||
"artist-credit": [ { "name": "Queen", "artist": { "id": "artist-id", "name": "Queen" } } ],
|
||||
"release-group": { "id": "release-group-id", "title": "A Night at the Opera" },
|
||||
"label-info": [ { "catalog-number": "EMC 4008", "label": { "id": "label-id", "name": "EMI" } } ],
|
||||
"media": [ { "position": 1, "title": "Disc 1", "format": "CD", "track-count": 12 } ],
|
||||
"asin": "B000000000",
|
||||
"tags": [ { "name": "rock", "count": 5 } ],
|
||||
"genres": [ { "id": "genre-id", "name": "Rock" } ],
|
||||
"relations": [ { "type": "producer", "artist": { "id": "artist-id", "name": "Roy Thomas Baker" } } ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzReleaseResponse? response = JsonSerializer.Deserialize<MusicBrainzReleaseResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("release-id", response.Id);
|
||||
Assert.Equal("A Night at the Opera", response.Title);
|
||||
Assert.Equal("1975 album", response.Disambiguation);
|
||||
Assert.Equal("Official", response.Status);
|
||||
Assert.Equal("1975-11-21", response.Date);
|
||||
Assert.Equal("GB", response.Country);
|
||||
Assert.Equal("1975-11-21", Assert.Single(response.ReleaseEvents).Date);
|
||||
Assert.Equal("0094639819524", response.Barcode);
|
||||
Assert.Equal("Jewel Case", response.Packaging);
|
||||
Assert.NotNull(response.TextRepresentation);
|
||||
Assert.Equal("eng", response.TextRepresentation.Language);
|
||||
Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name);
|
||||
Assert.NotNull(response.ReleaseGroup);
|
||||
Assert.Equal("A Night at the Opera", response.ReleaseGroup.Title);
|
||||
Assert.Equal("EMC 4008", Assert.Single(response.LabelInfo).CatalogNumber);
|
||||
Assert.Equal(1, Assert.Single(response.Media).Position);
|
||||
Assert.Equal("B000000000", response.Asin);
|
||||
Assert.Equal("rock", Assert.Single(response.Tags).Name);
|
||||
Assert.Equal("Rock", Assert.Single(response.Genres).Name);
|
||||
Assert.Equal("producer", Assert.Single(response.Relations).Type);
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzTagResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzTagResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void NameCountAndDisambiguation_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"name":"rock","disambiguation":"genre","count":5}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzTagResponse? response = JsonSerializer.Deserialize<MusicBrainzTagResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("rock", response.Name);
|
||||
Assert.Equal("genre", response.Disambiguation);
|
||||
Assert.Equal(5, response.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "genre-id",
|
||||
"name": "rock",
|
||||
"disambiguation": "genre",
|
||||
"count": 5
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzTagResponse? response = JsonSerializer.Deserialize<MusicBrainzTagResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("genre-id", response.Id);
|
||||
Assert.Equal("rock", response.Name);
|
||||
Assert.Equal("genre", response.Disambiguation);
|
||||
Assert.Equal(5, response.Count);
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzTextRepresentationResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzTextRepresentationResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void LanguageAndScript_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"language":"eng","script":"Latn"}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzTextRepresentationResponse? response = JsonSerializer.Deserialize<MusicBrainzTextRepresentationResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("eng", response.Language);
|
||||
Assert.Equal("Latn", response.Script);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"language":"eng","script":"Latn"}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzTextRepresentationResponse? response = JsonSerializer.Deserialize<MusicBrainzTextRepresentationResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("eng", response.Language);
|
||||
Assert.Equal("Latn", response.Script);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzTrackResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzTrackResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void NumberPositionLengthAndRecording_WhenTheTrackCarriesARecording_ShouldDeserializeAllOfThem()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "b1e2c3d4-0000-0000-0000-000000000000",
|
||||
"number": "A1",
|
||||
"position": 2,
|
||||
"title": "Death on Two Legs",
|
||||
"length": 223293,
|
||||
"recording": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", "title": "Death on Two Legs (Dedicated To...)" }
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzTrackResponse? response = JsonSerializer.Deserialize<MusicBrainzTrackResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("A1", response.Number);
|
||||
Assert.Equal(2, response.Position);
|
||||
Assert.Equal(223293, response.Length);
|
||||
Assert.NotNull(response.Recording);
|
||||
Assert.Equal("cb6c5931-436c-38c5-9d24-044f37d1fe35", response.Recording.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "track-id",
|
||||
"number": "A1",
|
||||
"position": 2,
|
||||
"title": "Death on Two Legs",
|
||||
"length": 223293,
|
||||
"recording": { "id": "recording-id", "title": "Death on Two Legs (Dedicated To...)" }
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzTrackResponse? response = JsonSerializer.Deserialize<MusicBrainzTrackResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("track-id", response.Id);
|
||||
Assert.Equal("A1", response.Number);
|
||||
Assert.Equal(2, response.Position);
|
||||
Assert.Equal("Death on Two Legs", response.Title);
|
||||
Assert.Equal(223293, response.Length);
|
||||
Assert.NotNull(response.Recording);
|
||||
Assert.Equal("recording-id", response.Recording.Id);
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzUrlResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzUrlResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void Resource_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"id":"e0e0e0e0-0000-0000-0000-000000000000","resource":"https://www.queenonline.com/"}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzUrlResponse? response = JsonSerializer.Deserialize<MusicBrainzUrlResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("e0e0e0e0-0000-0000-0000-000000000000", response.Id);
|
||||
Assert.Equal("https://www.queenonline.com/", response.Resource);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"id":"url-id","resource":"https://www.queenonline.com/"}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzUrlResponse? response = JsonSerializer.Deserialize<MusicBrainzUrlResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("url-id", response.Id);
|
||||
Assert.Equal("https://www.queenonline.com/", response.Resource);
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzWorkResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzWorkResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void TypeLanguagesAndIswcs_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"id":"d0e0e0e0-0000-0000-0000-000000000000","title":"Death on Two Legs","type":"Song","languages":["eng"],"iswcs":["T-010.154.482-4"]}""";
|
||||
|
||||
// Act
|
||||
MusicBrainzWorkResponse? response = JsonSerializer.Deserialize<MusicBrainzWorkResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("Song", response.Type);
|
||||
Assert.Equal("eng", Assert.Single(response.Languages));
|
||||
Assert.Equal("T-010.154.482-4", Assert.Single(response.Iswcs));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"id": "work-id",
|
||||
"title": "Bohemian Rhapsody",
|
||||
"type": "Song",
|
||||
"disambiguation": "studio version",
|
||||
"languages": [ "eng" ],
|
||||
"iswcs": [ "T-010.154.482-4" ],
|
||||
"relations": [ { "type": "composer", "artist": { "id": "artist-id", "name": "Freddie Mercury" } } ],
|
||||
"tags": [ { "name": "rock", "count": 5 } ],
|
||||
"genres": [ { "id": "genre-id", "name": "Rock" } ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
MusicBrainzWorkResponse? response = JsonSerializer.Deserialize<MusicBrainzWorkResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("work-id", response.Id);
|
||||
Assert.Equal("Bohemian Rhapsody", response.Title);
|
||||
Assert.Equal("Song", response.Type);
|
||||
Assert.Equal("studio version", response.Disambiguation);
|
||||
Assert.Equal("eng", Assert.Single(response.Languages));
|
||||
Assert.Equal("T-010.154.482-4", Assert.Single(response.Iswcs));
|
||||
Assert.Equal("composer", Assert.Single(response.Relations).Type);
|
||||
Assert.Equal("rock", Assert.Single(response.Tags).Name);
|
||||
Assert.Equal("Rock", Assert.Single(response.Genres).Name);
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers;
|
||||
|
||||
/// <summary>
|
||||
/// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class StubHttpMessageHandler : HttpMessageHandler
|
||||
{
|
||||
private readonly Func<HttpRequestMessage, int, HttpResponseMessage> _responseFactory;
|
||||
private int _callCount;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the requests that were sent through the handler.
|
||||
/// </summary>
|
||||
public List<HttpRequestMessage> Requests { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of requests that were sent through the handler.
|
||||
/// </summary>
|
||||
public int CallCount => _callCount;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StubHttpMessageHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="responseFactory">The factory that produces the response of a request, given the request and its one based call index.</param>
|
||||
public StubHttpMessageHandler(Func<HttpRequestMessage, int, HttpResponseMessage> responseFactory)
|
||||
{
|
||||
_responseFactory = responseFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends the provided request, producing its response through the configured factory.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to send.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The response produced for the request.</returns>
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
int callIndex = Interlocked.Increment(ref _callCount);
|
||||
Requests.Add(request);
|
||||
try
|
||||
{
|
||||
return Task.FromResult(_responseFactory(request, callIndex));
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// A response factory may throw to simulate a transport failure, which is surfaced as a faulted task.
|
||||
return Task.FromException<HttpResponseMessage>(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
+578
@@ -0,0 +1,578 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.MusicBrainz.Core;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Api;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Settings;
|
||||
using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzHttpClient"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzHttpClientTests
|
||||
{
|
||||
private const string RECORDING_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs","video":null}""";
|
||||
|
||||
private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheSameRecordingIsRequestedTwice_ShouldServeTheSecondRequestFromTheCache()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordingId = Guid.NewGuid();
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero);
|
||||
|
||||
// Act
|
||||
MusicBrainzRecordingResponse? first = await client.GetRecordingAsync(recordingId, CancellationToken.None);
|
||||
MusicBrainzRecordingResponse? second = await client.GetRecordingAsync(recordingId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(first);
|
||||
Assert.NotNull(second);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheBaseUrlIsNotTheRealService_ShouldNotThrottleTheRequests()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost:5000/", TimeSpan.FromSeconds(1));
|
||||
|
||||
// Act
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
stopwatch.Stop();
|
||||
|
||||
// Assert
|
||||
// The configured minimum request interval is one second, but a base URL that is not the real MusicBrainz service is not throttled.
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(500));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("https://musicbrainz.org/ws/2/")] // the real service
|
||||
[InlineData("https://mirror.musicbrainz.org/ws/2/")] // a subdomain of the real service
|
||||
public async Task GetRecordingAsync_WhenTheBaseUrlIsTheRealService_ShouldThrottleTheRequests(string baseUrl)
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, HttpClient _) = CreateClient(baseUrl, TimeSpan.FromMilliseconds(100));
|
||||
|
||||
// Act
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
stopwatch.Stop();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
Assert.True(stopwatch.Elapsed >= TimeSpan.FromMilliseconds(50), $"The elapsed time {stopwatch.Elapsed} was shorter than the expected throttle interval.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheBaseUrlIsNotAnAbsoluteUri_ShouldThrow()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, _, _) = CreateClient("not-a-url", TimeSpan.Zero);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<UriFormatException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheRequestIsNotAuthorized_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound));
|
||||
|
||||
// Act
|
||||
MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation()
|
||||
{
|
||||
// Arrange
|
||||
using (CancellationTokenSource cancellationTokenSource = new())
|
||||
{
|
||||
cancellationTokenSource.Cancel();
|
||||
(MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetRecordingAsync(Guid.NewGuid(), cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheFirstAttemptReturns503_ShouldRetryAndSucceed()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => callIndex == 1
|
||||
? new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
|
||||
: Json(RECORDING_JSON));
|
||||
|
||||
// Act
|
||||
MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheFirstAttemptIsRateLimited_ShouldRetryAndSucceed()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => callIndex == 1
|
||||
? new HttpResponseMessage(HttpStatusCode.TooManyRequests)
|
||||
: Json(RECORDING_JSON));
|
||||
|
||||
// Act
|
||||
MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheFirstAttemptThrowsATransportException_ShouldRetryAndSucceed()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => callIndex == 1
|
||||
? throw new HttpRequestException("Transient failure.")
|
||||
: Json(RECORDING_JSON));
|
||||
|
||||
// Act
|
||||
MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenEveryAttemptFails_ShouldThrowAfterExhaustingTheRetries()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => new HttpResponseMessage(HttpStatusCode.InternalServerError));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
Assert.Equal(4, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheContactEmailIsConfigured_ShouldIncludeItInTheUserAgent()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, contactEmail: "contact@example.com");
|
||||
|
||||
// Act
|
||||
await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
string userAgent = handler.Requests[0].Headers.UserAgent.ToString();
|
||||
Assert.Contains("Lumina-Test/1.0", userAgent);
|
||||
Assert.Contains("contact@example.com", userAgent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheContactEmailIsNotConfigured_ShouldNotIncludeItInTheUserAgent()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero);
|
||||
|
||||
// Act
|
||||
await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
string userAgent = handler.Requests[0].Headers.UserAgent.ToString();
|
||||
Assert.Equal("Lumina-Test/1.0", userAgent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheUserAgentIsAlreadySet_ShouldNotOverrideIt()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler handler = new((request, callIndex) => Json(RECORDING_JSON));
|
||||
HttpClient httpClient = new(handler);
|
||||
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Custom/9.9");
|
||||
MusicBrainzHttpClient client = CreateMusicBrainzHttpClient(httpClient, "http://localhost/", TimeSpan.Zero, null);
|
||||
|
||||
// Act
|
||||
await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Custom/9.9", handler.Requests[0].Headers.UserAgent.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAsync_WhenTheArtistExists_ShouldDeserializeIt()
|
||||
{
|
||||
// Arrange
|
||||
const string ARTIST_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Queen","type":"Group"}""";
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(ARTIST_JSON));
|
||||
|
||||
// Act
|
||||
MusicBrainzArtistResponse? result = await client.GetArtistAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Queen", result.Name);
|
||||
Assert.Contains("inc=aliases+tags+genres+url-rels+artist-rels+ratings", handler.Requests[0].RequestUri!.Query);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchArtistsAsync_WhenTheSearchReturnsArtists_ShouldReturnThem()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":1,"artists":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Queen"}]}""";
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(SEARCH_JSON));
|
||||
|
||||
// Act
|
||||
IReadOnlyList<MusicBrainzArtistResponse> result = await client.SearchArtistsAsync("Queen", 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Queen", Assert.Single(result).Name);
|
||||
Assert.Contains("limit=10", handler.Requests[0].RequestUri!.Query);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchArtistsAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null"));
|
||||
|
||||
// Act
|
||||
IReadOnlyList<MusicBrainzArtistResponse> result = await client.SearchArtistsAsync("Queen", 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, "limit=1")] // a limit below the minimum is clamped up
|
||||
[InlineData(200, "limit=100")] // a limit above the maximum is clamped down
|
||||
[InlineData(50, "limit=50")] // a limit within the range is kept
|
||||
public async Task SearchArtistsAsync_WhenTheLimitIsOutOfRange_ShouldClampIt(int requestedLimit, string expectedQuery)
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("""{"artists":[]}"""));
|
||||
|
||||
// Act
|
||||
await client.SearchArtistsAsync("Queen", requestedLimit, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Contains(expectedQuery, handler.Requests[0].RequestUri!.Query);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReleaseGroupAsync_WhenTheReleaseGroupExists_ShouldDeserializeIt()
|
||||
{
|
||||
// Arrange
|
||||
const string RELEASE_GROUP_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"A Night at the Opera"}""";
|
||||
(MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(RELEASE_GROUP_JSON));
|
||||
|
||||
// Act
|
||||
MusicBrainzReleaseGroupResponse? result = await client.GetReleaseGroupAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("A Night at the Opera", result.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchReleaseGroupsAsync_WhenTheSearchReturnsReleaseGroups_ShouldReturnThem()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":1,"release-groups":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"A Night at the Opera"}]}""";
|
||||
(MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(SEARCH_JSON));
|
||||
|
||||
// Act
|
||||
IReadOnlyList<MusicBrainzReleaseGroupResponse> result = await client.SearchReleaseGroupsAsync("Opera", 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("A Night at the Opera", Assert.Single(result).Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchReleaseGroupsAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null"));
|
||||
|
||||
// Act
|
||||
IReadOnlyList<MusicBrainzReleaseGroupResponse> result = await client.SearchReleaseGroupsAsync("Opera", 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReleaseAsync_WhenTheReleaseExists_ShouldDeserializeIt()
|
||||
{
|
||||
// Arrange
|
||||
const string RELEASE_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"A Night at the Opera"}""";
|
||||
(MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(RELEASE_JSON));
|
||||
|
||||
// Act
|
||||
MusicBrainzReleaseResponse? result = await client.GetReleaseAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("A Night at the Opera", result.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BrowseReleasesByReleaseGroupAsync_WhenReleasesExist_ShouldReturnThem()
|
||||
{
|
||||
// Arrange
|
||||
const string BROWSE_JSON = """{"release-count":1,"releases":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"A Night at the Opera"}]}""";
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(BROWSE_JSON));
|
||||
|
||||
// Act
|
||||
IReadOnlyList<MusicBrainzReleaseResponse> result = await client.BrowseReleasesByReleaseGroupAsync(Guid.NewGuid(), 25, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("A Night at the Opera", Assert.Single(result).Title);
|
||||
Assert.Contains("inc=artist-credits+labels+media", handler.Requests[0].RequestUri!.Query);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BrowseReleasesByReleaseGroupAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null"));
|
||||
|
||||
// Act
|
||||
IReadOnlyList<MusicBrainzReleaseResponse> result = await client.BrowseReleasesByReleaseGroupAsync(Guid.NewGuid(), 25, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchRecordingsAsync_WhenTheSearchReturnsRecordings_ShouldReturnThem()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":1,"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs"}]}""";
|
||||
(MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(SEARCH_JSON));
|
||||
|
||||
// Act
|
||||
IReadOnlyList<MusicBrainzRecordingResponse> result = await client.SearchRecordingsAsync("Death", 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Death on Two Legs", Assert.Single(result).Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchRecordingsAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null"));
|
||||
|
||||
// Act
|
||||
IReadOnlyList<MusicBrainzRecordingResponse> result = await client.SearchRecordingsAsync("Death", 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingsByIsrcAsync_WhenRecordingsExist_ShouldReturnThem()
|
||||
{
|
||||
// Arrange
|
||||
const string ISRC_JSON = """{"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs"}]}""";
|
||||
(MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(ISRC_JSON));
|
||||
|
||||
// Act
|
||||
IReadOnlyList<MusicBrainzRecordingResponse> result = await client.GetRecordingsByIsrcAsync("US1A2B3C4D5E", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Death on Two Legs", Assert.Single(result).Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingsByIsrcAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null"));
|
||||
|
||||
// Act
|
||||
IReadOnlyList<MusicBrainzRecordingResponse> result = await client.GetRecordingsByIsrcAsync("US1A2B3C4D5E", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetWorkAsync_WhenTheWorkExists_ShouldDeserializeIt()
|
||||
{
|
||||
// Arrange
|
||||
const string WORK_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs","type":"Song"}""";
|
||||
(MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(WORK_JSON));
|
||||
|
||||
// Act
|
||||
MusicBrainzWorkResponse? result = await client.GetWorkAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Death on Two Legs", result.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReleaseWithRecordingsAsync_WhenTheReleaseExists_ShouldDeserializeItsTracks()
|
||||
{
|
||||
// Arrange
|
||||
const string RELEASE_JSON = """
|
||||
{
|
||||
"id": "cb6c5931-436c-38c5-9d24-044f37d1fe35",
|
||||
"title": "A Night at the Opera",
|
||||
"media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "Death on Two Legs", "recording": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", "title": "Death on Two Legs" } } ] } ]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(RELEASE_JSON));
|
||||
|
||||
// Act
|
||||
MusicBrainzReleaseResponse? result = await client.GetReleaseWithRecordingsAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Contains("inc=recordings", handler.Requests[0].RequestUri!.Query);
|
||||
Assert.Single(Assert.Single(result.Media).Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheFirstAttemptIsRateLimitedWithRetryAfter_ShouldHonorTheRequestedDelay()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) =>
|
||||
{
|
||||
if (callIndex != 1)
|
||||
return Json(RECORDING_JSON);
|
||||
HttpResponseMessage rateLimited = new(HttpStatusCode.TooManyRequests);
|
||||
rateLimited.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.Zero);
|
||||
return rateLimited;
|
||||
});
|
||||
|
||||
// Act
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
stopwatch.Stop();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
// The requested delay of zero is honored instead of the default five hundred millisecond backoff of the first retry.
|
||||
Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(400), $"The elapsed time {stopwatch.Elapsed} shows the Retry-After header was ignored.");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("A & B")] // ampersand query separator
|
||||
[InlineData("Title #fragment")] // fragment separator
|
||||
[InlineData("A?B")] // query separator
|
||||
[InlineData("../../secret")] // path traversal
|
||||
[InlineData("A\" OR \"B")] // quote escape
|
||||
public async Task SearchArtistsAsync_WhenTheQueryContainsReservedCharacters_ShouldKeepThemInsideTheQueryString(string searchTerm)
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://musicbrainz.example/ws/2/", TimeSpan.Zero, (request, callIndex) => Json("""{"artists":[]}"""));
|
||||
|
||||
// Act
|
||||
await client.SearchArtistsAsync(searchTerm, 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Uri requestUri = handler.Requests[0].RequestUri!;
|
||||
Assert.Equal("musicbrainz.example", requestUri.Host);
|
||||
Assert.Equal("/ws/2/artist", requestUri.AbsolutePath);
|
||||
Assert.Equal(string.Empty, requestUri.Fragment);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MusicBrainzHttpClient"/> whose requests are answered by a stub handler, returning the recording JSON by default.
|
||||
/// </summary>
|
||||
/// <param name="baseUrl">The base URL of the MusicBrainz web service the client points to.</param>
|
||||
/// <param name="minimumRequestInterval">The minimum request interval configured for the client.</param>
|
||||
/// <param name="responseFactory">Optional. The factory that produces the response of a request.</param>
|
||||
/// <param name="contactEmail">Optional. The contact email configured for the client.</param>
|
||||
/// <returns>The created client, its stub handler and the underlying HTTP client.</returns>
|
||||
private (MusicBrainzHttpClient Client, StubHttpMessageHandler Handler, HttpClient HttpClient) CreateClient(
|
||||
string baseUrl,
|
||||
TimeSpan minimumRequestInterval,
|
||||
Func<HttpRequestMessage, int, HttpResponseMessage>? responseFactory = null,
|
||||
string? contactEmail = null)
|
||||
{
|
||||
StubHttpMessageHandler handler = new(responseFactory ?? ((request, callIndex) => Json(RECORDING_JSON)));
|
||||
HttpClient httpClient = new(handler);
|
||||
MusicBrainzHttpClient client = CreateMusicBrainzHttpClient(httpClient, baseUrl, minimumRequestInterval, contactEmail);
|
||||
return (client, handler, httpClient);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MusicBrainzHttpClient"/> around the provided <see cref="HttpClient"/>.
|
||||
/// </summary>
|
||||
/// <param name="httpClient">The underlying HTTP client.</param>
|
||||
/// <param name="baseUrl">The base URL of the MusicBrainz web service the client points to.</param>
|
||||
/// <param name="minimumRequestInterval">The minimum request interval configured for the client.</param>
|
||||
/// <param name="contactEmail">Optional. The contact email configured for the client.</param>
|
||||
/// <returns>The created client.</returns>
|
||||
private MusicBrainzHttpClient CreateMusicBrainzHttpClient(HttpClient httpClient, string baseUrl, TimeSpan minimumRequestInterval, string? contactEmail)
|
||||
{
|
||||
MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create(
|
||||
baseUrl: baseUrl,
|
||||
userAgent: "Lumina-Test/1.0",
|
||||
contactEmail: contactEmail,
|
||||
includeContactEmail: contactEmail is not null,
|
||||
searchResultLimit: 10,
|
||||
releaseLookupLimit: 25,
|
||||
minimumRequestInterval: minimumRequestInterval));
|
||||
return new MusicBrainzHttpClient(httpClient, settingsProvider, new MusicBrainzRequestThrottle(), new MusicBrainzResponseCache());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an OK response with the provided JSON body.
|
||||
/// </summary>
|
||||
/// <param name="json">The JSON body of the response.</param>
|
||||
/// <returns>The created response.</returns>
|
||||
private static HttpResponseMessage Json(string json)
|
||||
{
|
||||
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Core.Api;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzRequestThrottle"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzRequestThrottleTests
|
||||
{
|
||||
private readonly MusicBrainzRequestThrottle _sut = new();
|
||||
|
||||
[Fact]
|
||||
public async Task WaitAsync_WhenTheMinimumIntervalHasNotElapsed_ShouldDelayTheSecondRequest()
|
||||
{
|
||||
// Arrange
|
||||
TimeSpan minimumRequestInterval = TimeSpan.FromMilliseconds(200);
|
||||
|
||||
// Act
|
||||
await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None);
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None);
|
||||
stopwatch.Stop();
|
||||
|
||||
// Assert
|
||||
// The second request must wait for the remainder of the interval, which is close to the configured interval.
|
||||
Assert.True(stopwatch.Elapsed >= TimeSpan.FromMilliseconds(150), $"The elapsed time {stopwatch.Elapsed} was shorter than the expected minimum interval.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WaitAsync_WhenTheMinimumIntervalIsZero_ShouldNotDelayTheRequests()
|
||||
{
|
||||
// Arrange
|
||||
TimeSpan minimumRequestInterval = TimeSpan.Zero;
|
||||
|
||||
// Act
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None);
|
||||
await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None);
|
||||
stopwatch.Stop();
|
||||
|
||||
// Assert
|
||||
Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(500), $"The elapsed time {stopwatch.Elapsed} shows an unexpected delay.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WaitAsync_WhenTheMinimumIntervalIsNegative_ShouldNotDelayTheRequests()
|
||||
{
|
||||
// Arrange
|
||||
TimeSpan minimumRequestInterval = TimeSpan.FromSeconds(-1);
|
||||
|
||||
// Act
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None);
|
||||
await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None);
|
||||
stopwatch.Stop();
|
||||
|
||||
// Assert
|
||||
Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(500), $"The elapsed time {stopwatch.Elapsed} shows an unexpected delay.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WaitAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldThrowOperationCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using (CancellationTokenSource cancellationTokenSource = new())
|
||||
{
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.WaitAsync(TimeSpan.FromMilliseconds(100), cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WaitAsync_WhenCalledConcurrently_ShouldSpaceOutEveryRequest()
|
||||
{
|
||||
// Arrange
|
||||
TimeSpan minimumRequestInterval = TimeSpan.FromMilliseconds(150);
|
||||
|
||||
// Act
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
await Task.WhenAll(
|
||||
_sut.WaitAsync(minimumRequestInterval, CancellationToken.None),
|
||||
_sut.WaitAsync(minimumRequestInterval, CancellationToken.None),
|
||||
_sut.WaitAsync(minimumRequestInterval, CancellationToken.None));
|
||||
stopwatch.Stop();
|
||||
|
||||
// Assert
|
||||
// Three requests spaced by the interval take at least two intervals in total.
|
||||
Assert.True(stopwatch.Elapsed >= TimeSpan.FromMilliseconds(250), $"The elapsed time {stopwatch.Elapsed} was shorter than the expected total interval.");
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.MusicBrainz.Core.Api;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzResponseCache"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzResponseCacheTests
|
||||
{
|
||||
private readonly MusicBrainzResponseCache _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void TryGet_WhenTheKeyWasNeverCached_ShouldReturnFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.TryGet("missing", out string? json);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
Assert.Null(json);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryGet_WhenTheKeyWasCached_ShouldReturnTheCachedBody()
|
||||
{
|
||||
// Arrange
|
||||
_sut.Set("key", "{\"id\":\"1\"}");
|
||||
|
||||
// Act
|
||||
bool result = _sut.TryGet("key", out string? json);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
Assert.Equal("{\"id\":\"1\"}", json);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_WhenTheKeyAlreadyExists_ShouldReplaceTheCachedBody()
|
||||
{
|
||||
// Arrange
|
||||
_sut.Set("key", "a-longer-value");
|
||||
_sut.Set("key", "short");
|
||||
|
||||
// Act
|
||||
bool result = _sut.TryGet("key", out string? json);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
Assert.Equal("short", json);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_WhenTheValueFitsTheCharacterBudgetExactly_ShouldCacheIt()
|
||||
{
|
||||
// Arrange
|
||||
MusicBrainzResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 3, timeToLive: TimeSpan.FromMinutes(1));
|
||||
|
||||
// Act
|
||||
sut.Set("exact", "abc");
|
||||
|
||||
// Assert
|
||||
Assert.True(sut.TryGet("exact", out string? json));
|
||||
Assert.Equal("abc", json);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_WhenTheValueExceedsTheWholeCharacterBudget_ShouldNotCacheIt()
|
||||
{
|
||||
// Arrange
|
||||
MusicBrainzResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 3, timeToLive: TimeSpan.FromMinutes(1));
|
||||
|
||||
// Act
|
||||
sut.Set("oversized", "abcd");
|
||||
|
||||
// Assert
|
||||
Assert.False(sut.TryGet("oversized", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_WhenTheCharacterBudgetIsExceeded_ShouldEvictTheOldestEntryAndKeepTheNewestOne()
|
||||
{
|
||||
// Arrange
|
||||
MusicBrainzResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 10, timeToLive: TimeSpan.FromMinutes(1));
|
||||
sut.Set("oldest", "1234567890");
|
||||
|
||||
// Act
|
||||
sut.Set("newest", "x");
|
||||
|
||||
// Assert
|
||||
Assert.False(sut.TryGet("oldest", out _));
|
||||
Assert.True(sut.TryGet("newest", out string? json));
|
||||
Assert.Equal("x", json);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_WhenTheEntryCountBudgetIsExceeded_ShouldEvictTheOldestEntriesAndKeepTheNewestOne()
|
||||
{
|
||||
// Arrange
|
||||
MusicBrainzResponseCache sut = new(maximumEntryCount: 3, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMinutes(1));
|
||||
sut.Set("entry-1", "1");
|
||||
sut.Set("entry-2", "2");
|
||||
sut.Set("entry-3", "3");
|
||||
|
||||
// Act
|
||||
sut.Set("entry-4", "4");
|
||||
|
||||
// Assert
|
||||
// The oldest entries are trimmed to the lower water mark, while the most recently cached one always survives.
|
||||
Assert.False(sut.TryGet("entry-1", out _));
|
||||
Assert.False(sut.TryGet("entry-2", out _));
|
||||
Assert.True(sut.TryGet("entry-3", out _));
|
||||
Assert.True(sut.TryGet("entry-4", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_WhenTheEntryCountBudgetIsExceededByOne_ShouldEvictTheOldestEntryAndKeepTheNewOne()
|
||||
{
|
||||
// Arrange
|
||||
MusicBrainzResponseCache sut = new(maximumEntryCount: 1, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMinutes(1));
|
||||
sut.Set("entry-1", "1");
|
||||
|
||||
// Act
|
||||
sut.Set("entry-2", "2");
|
||||
|
||||
// Assert
|
||||
Assert.True(sut.TryGet("entry-2", out _));
|
||||
Assert.False(sut.TryGet("entry-1", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryGet_WhenTheCachedEntryExpired_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicBrainzResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMilliseconds(-1));
|
||||
sut.Set("expired", "value");
|
||||
|
||||
// Act
|
||||
bool result = sut.TryGet("expired", out string? json);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
Assert.Null(json);
|
||||
}
|
||||
}
|
||||
+1508
File diff suppressed because it is too large.
Load diff
+592
@@ -0,0 +1,592 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Plugins.MusicBrainz.Core;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Api;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Settings;
|
||||
using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzAlbumMetadataProvider"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzAlbumMetadataProviderTests
|
||||
{
|
||||
private static readonly Guid s_releaseId = Guid.Parse("11111111-1111-1111-1111-111111111111");
|
||||
private static readonly Guid s_releaseGroupId = Guid.Parse("22222222-2222-2222-2222-222222222222");
|
||||
|
||||
private readonly AlbumMetadataLookupDtoFixture _albumMetadataLookupDtoFixture = new();
|
||||
private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Name_WhenCalled_ShouldReturnTheProviderDisplayName()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzAlbumMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
|
||||
// Act
|
||||
string result = sut.Name;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("MusicBrainz", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzAlbumMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
|
||||
// Act
|
||||
IReadOnlyList<LibraryType> result = sut.SupportedLibraryTypes;
|
||||
|
||||
// Assert
|
||||
Assert.Equal([LibraryType.Music], result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequiresWebAccess_WhenCalled_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzAlbumMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
|
||||
// Act
|
||||
bool result = sut.RequiresWebAccess;
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task GetSearchResultsAsync_WhenTheTitleIsMissing_ShouldReturnAnEmptyCollectionWithoutAnyRequest(string? title)
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: title);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<AlbumMetadataDto> result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
Assert.Equal(0, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenTheSearchReturnsReleaseGroups_ShouldMapEveryTitledOneAndSkipTheUntitledOnes()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """
|
||||
{
|
||||
"count": 3,
|
||||
"release-groups": [
|
||||
{ "id": "22222222-2222-2222-2222-222222222222", "title": "The Album", "primary-type": "Album" },
|
||||
{ "id": "33333333-3333-3333-3333-333333333333", "title": "Other Album" },
|
||||
{ "id": "44444444-4444-4444-4444-444444444444", "title": null }
|
||||
]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: " The \"Album\" ", artistName: " The Artist ");
|
||||
|
||||
// Act
|
||||
IReadOnlyList<AlbumMetadataDto> result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.Equal("The Album", result[0].Title);
|
||||
Assert.Equal("Other Album", result[1].Title);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
Assert.Contains("limit=10", handler.Requests[0].RequestUri!.Query);
|
||||
// the quotes are removed from the built query, and the artist constraint is appended
|
||||
string query = Uri.UnescapeDataString(handler.Requests[0].RequestUri!.Query);
|
||||
Assert.Contains("releasegroup:\"The Album\"", query);
|
||||
Assert.Contains("AND artist:\"The Artist\"", query);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseAndTheArtistArePresent_ShouldMapBothTheReleaseGroupAndTheRelease()
|
||||
{
|
||||
// Arrange
|
||||
string releaseJson = ReleaseJson(s_releaseId, "The Release", s_releaseGroupId, "The Album", "1975-06-01", "Official", "1975-11-21", "US");
|
||||
string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01");
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : releaseJson));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("The Album", result.Title);
|
||||
Assert.Equal(s_releaseId, result.MusicBrainzReleaseId);
|
||||
Assert.Equal(s_releaseGroupId, result.MusicBrainzReleaseGroupId);
|
||||
Assert.Equal("The Release", result.ReleaseTitle);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseIdentifierIsPresentButTheReleaseIsNotFound_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseCarriesAnUnparsableReleaseGroupIdentifier_ShouldMapOnlyTheRelease()
|
||||
{
|
||||
// Arrange
|
||||
const string RELEASE_JSON = """
|
||||
{
|
||||
"id": "11111111-1111-1111-1111-111111111111",
|
||||
"title": "The Release",
|
||||
"release-group": { "id": "not-a-guid", "title": "The Album" }
|
||||
}
|
||||
""";
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(RELEASE_JSON));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("The Release", result.Title);
|
||||
Assert.Null(result.MusicBrainzReleaseGroupId);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseDoesNotReferenceAReleaseGroup_ShouldMapOnlyTheRelease()
|
||||
{
|
||||
// Arrange
|
||||
const string RELEASE_JSON = """{"id":"11111111-1111-1111-1111-111111111111","title":"The Release"}""";
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(RELEASE_JSON));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("The Release", result.Title);
|
||||
Assert.Null(result.MusicBrainzReleaseGroupId);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenThereIsNeitherAnIdentifierNorATitle_ShouldReturnNullWithoutAnyRequest()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: " ");
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
Assert.Equal(0, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenOnlyTheTitleIsPresent_ShouldSearchAndResolveTheFirstReleaseGroup()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":1,"release-groups":[{"id":"22222222-2222-2222-2222-222222222222","title":"The Album"}]}""";
|
||||
const string BROWSE_JSON = """{"release-count":0,"releases":[]}""";
|
||||
string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01");
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(Route(request, SEARCH_JSON, releaseGroupJson, BROWSE_JSON)));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: "The Album");
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("The Album", result.Title);
|
||||
Assert.Equal(s_releaseGroupId, result.MusicBrainzReleaseGroupId);
|
||||
// the search, the detail lookup and the release browse are all used
|
||||
Assert.Equal(3, handler.CallCount);
|
||||
Assert.Contains("limit=1", handler.Requests[0].RequestUri!.Query);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheTitleSearchReturnsNothing_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":0,"release-groups":[]}""";
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: "The Album");
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheSearchResultIdentifierIsNotAGuid_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":1,"release-groups":[{"id":"not-a-guid","title":"The Album"}]}""";
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: "The Album");
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseGroupIdentifierIsPresent_ShouldFetchItDirectly()
|
||||
{
|
||||
// Arrange
|
||||
string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01");
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseGroupJson));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(s_releaseGroupId, result.MusicBrainzReleaseGroupId);
|
||||
Assert.Contains($"/release-group/{s_releaseGroupId:D}", handler.Requests[0].RequestUri!.AbsolutePath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseGroupIsUnknownButATitleIsPresent_ShouldFallBackToTheTitleSearch()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":1,"release-groups":[{"id":"22222222-2222-2222-2222-222222222222","title":"The Album"}]}""";
|
||||
const string BROWSE_JSON = """{"release-count":0,"releases":[]}""";
|
||||
string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01");
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) =>
|
||||
request.RequestUri!.Query.Contains("query=")
|
||||
? Json(SEARCH_JSON)
|
||||
: request.RequestUri.AbsolutePath.Contains("/release-group/")
|
||||
? callIndex == 1
|
||||
? new HttpResponseMessage(HttpStatusCode.NotFound)
|
||||
: Json(releaseGroupJson)
|
||||
: Json(BROWSE_JSON));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, title: "The Album");
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("The Album", result.Title);
|
||||
Assert.Equal(s_releaseGroupId, result.MusicBrainzReleaseGroupId);
|
||||
Assert.Equal(4, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseGroupIdentifierIsPresentButTheDetailIsMissing_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheLocalTrackCountIsUnknown_ShouldNotSelectAnyRelease()
|
||||
{
|
||||
// Arrange
|
||||
string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01");
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseGroupJson));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: null);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.MusicBrainzReleaseId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenNoReleaseMatchesTheLocalTrackCount_ShouldNotSelectAnyRelease()
|
||||
{
|
||||
// Arrange
|
||||
string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01");
|
||||
const string BROWSE_JSON = """{"release-count":1,"releases":[{"id":"11111111-1111-1111-1111-111111111111","title":"The Release","media":[{"position":1,"track-count":9}]}]}""";
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 12);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.MusicBrainzReleaseId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenSeveralReleasesMatch_ShouldSelectTheBestScoredOne()
|
||||
{
|
||||
// Arrange
|
||||
string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01");
|
||||
const string BROWSE_JSON = """
|
||||
{
|
||||
"release-count": 3,
|
||||
"releases": [
|
||||
{ "id": "11111111-1111-1111-1111-111111111111", "title": "Bootleg Edition", "status": "Bootleg", "date": "1975", "media": [ { "position": 1, "track-count": 2 } ] },
|
||||
{ "id": "22222222-2222-2222-2222-222222222222", "title": "Official Edition", "status": "Official", "date": "1975-11-21", "barcode": "123", "label-info": [ { "catalog-number": "CAT" } ], "media": [ { "position": 1, "track-count": 2 } ] },
|
||||
{ "id": "33333333-3333-3333-3333-333333333333", "title": "Promotion Edition", "status": "Promotion", "date": "1980-01-01", "media": [ { "position": 1, "track-count": 2 } ] }
|
||||
]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 2, releaseYear: 1975);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(Guid.Parse("22222222-2222-2222-2222-222222222222"), result.MusicBrainzReleaseId);
|
||||
Assert.Equal("Official Edition", result.ReleaseTitle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenSeveralReleasesScoreTheSame_ShouldSelectTheFirstOne()
|
||||
{
|
||||
// Arrange
|
||||
string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01");
|
||||
const string BROWSE_JSON = """
|
||||
{
|
||||
"release-count": 2,
|
||||
"releases": [
|
||||
{ "id": "11111111-1111-1111-1111-111111111111", "title": "First Edition", "status": "Official", "date": "1975-11-21", "media": [ { "position": 1, "track-count": 2 } ] },
|
||||
{ "id": "22222222-2222-2222-2222-222222222222", "title": "Second Edition", "status": "Official", "date": "1975-11-21", "media": [ { "position": 1, "track-count": 2 } ] }
|
||||
]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 2, releaseYear: 1975);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(Guid.Parse("11111111-1111-1111-1111-111111111111"), result.MusicBrainzReleaseId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseDateIsUnparsable_ShouldStillSelectTheMatchingRelease()
|
||||
{
|
||||
// Arrange
|
||||
string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01");
|
||||
const string BROWSE_JSON = """
|
||||
{
|
||||
"release-count": 2,
|
||||
"releases": [
|
||||
{ "id": "11111111-1111-1111-1111-111111111111", "title": "Unparsable Edition", "status": "Official", "date": "not a date", "media": [ { "position": 1, "track-count": 2 } ] },
|
||||
{ "id": "22222222-2222-2222-2222-222222222222", "title": "Matching Edition", "status": "Official", "date": "1975-06-01", "media": [ { "position": 1, "track-count": 2 } ] }
|
||||
]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 2, releaseYear: 1975);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(Guid.Parse("22222222-2222-2222-2222-222222222222"), result.MusicBrainzReleaseId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseCarriesSeveralCatalogNumbers_ShouldMapAllOfThem()
|
||||
{
|
||||
// Arrange
|
||||
const string RELEASE_JSON = """
|
||||
{
|
||||
"id": "11111111-1111-1111-1111-111111111111",
|
||||
"title": "A Night at the Opera",
|
||||
"release-group": { "id": "22222222-2222-2222-2222-222222222222", "title": "A Night at the Opera", "primary-type": "Album" },
|
||||
"label-info": [
|
||||
{ "catalog-number": "EMC 4008", "label": { "name": "EMI" } },
|
||||
{ "catalog-number": "0C 066-98 485", "label": { "name": "EMI" } },
|
||||
{ "catalog-number": "EMC 4008", "label": { "name": "EMI" } }
|
||||
]
|
||||
}
|
||||
""";
|
||||
string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "A Night at the Opera", "Album", "1975-11-21");
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : RELEASE_JSON));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.NotNull(result.CatalogNumbers);
|
||||
// every distinct catalog number is kept, while the duplicates are removed.
|
||||
Assert.Equal(["EMC 4008", "0C 066-98 485"], result.CatalogNumbers);
|
||||
Assert.Equal("EMI", result.Label);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheMatchingReleaseHasNoMedia_ShouldStillSelectIt()
|
||||
{
|
||||
// Arrange
|
||||
string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01");
|
||||
const string BROWSE_JSON = """{"release-count":1,"releases":[{"id":"11111111-1111-1111-1111-111111111111","title":"Empty Edition","status":"Official","media":[]}]}""";
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 0);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(Guid.Parse("11111111-1111-1111-1111-111111111111"), result.MusicBrainzReleaseId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseDatesAreMissingOrTooShort_ShouldStillSelectAMatchingRelease()
|
||||
{
|
||||
// Arrange
|
||||
string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01");
|
||||
const string BROWSE_JSON = """
|
||||
{
|
||||
"release-count": 2,
|
||||
"releases": [
|
||||
{ "id": "11111111-1111-1111-1111-111111111111", "status": "Official", "media": [ { "position": 1, "track-count": 2 } ] },
|
||||
{ "id": "22222222-2222-2222-2222-222222222222", "status": "Official", "date": "75", "media": [ { "position": 1, "track-count": 2 } ] }
|
||||
]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON));
|
||||
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 2, releaseYear: 1975);
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(Guid.Parse("11111111-1111-1111-1111-111111111111"), result.MusicBrainzReleaseId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MusicBrainzAlbumMetadataProvider"/> whose requests are answered by the provided stub handler.
|
||||
/// </summary>
|
||||
/// <param name="responseFactory">The factory that produces the response of a request.</param>
|
||||
/// <returns>The created provider and its stub handler.</returns>
|
||||
private (MusicBrainzAlbumMetadataProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func<HttpRequestMessage, int, HttpResponseMessage> responseFactory)
|
||||
{
|
||||
StubHttpMessageHandler handler = new(responseFactory);
|
||||
MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create(
|
||||
baseUrl: "http://localhost/",
|
||||
searchResultLimit: 10,
|
||||
releaseLookupLimit: 25,
|
||||
minimumRequestInterval: TimeSpan.Zero));
|
||||
MusicBrainzHttpClient httpClient = new(new HttpClient(handler), settingsProvider, new MusicBrainzRequestThrottle(), new MusicBrainzResponseCache());
|
||||
return (new MusicBrainzAlbumMetadataProvider(httpClient, settingsProvider), handler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Routes a request to the search, release group or release browse JSON, based on the request URI.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to route.</param>
|
||||
/// <param name="searchString">The JSON returned for a search request.</param>
|
||||
/// <param name="releaseGroupJson">The JSON returned for a release group detail request.</param>
|
||||
/// <param name="browseJson">The JSON returned for a release browse request.</param>
|
||||
/// <returns>The JSON that answers the request.</returns>
|
||||
private static string Route(HttpRequestMessage request, string searchString, string releaseGroupJson, string browseJson)
|
||||
{
|
||||
if (request.RequestUri!.Query.Contains("query=", StringComparison.Ordinal))
|
||||
return searchString;
|
||||
return request.RequestUri.AbsolutePath.Contains("/release-group/", StringComparison.Ordinal) ? releaseGroupJson : browseJson;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the JSON of a release group response.
|
||||
/// </summary>
|
||||
/// <param name="id">The MusicBrainz identifier of the release group.</param>
|
||||
/// <param name="title">The title of the release group.</param>
|
||||
/// <param name="primaryType">The primary type of the release group.</param>
|
||||
/// <param name="firstReleaseDate">The first release date of the release group.</param>
|
||||
/// <returns>The JSON of the release group response.</returns>
|
||||
private static string ReleaseGroupJson(Guid id, string title, string primaryType, string firstReleaseDate)
|
||||
{
|
||||
return $$"""{"id":"{{id:D}}","title":"{{title}}","primary-type":"{{primaryType}}","first-release-date":"{{firstReleaseDate}}"}""";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the JSON of a release response.
|
||||
/// </summary>
|
||||
/// <param name="id">The MusicBrainz identifier of the release.</param>
|
||||
/// <param name="title">The title of the release.</param>
|
||||
/// <param name="releaseGroupId">The MusicBrainz identifier of the release group.</param>
|
||||
/// <param name="releaseGroupTitle">The title of the release group.</param>
|
||||
/// <param name="releaseGroupFirstReleaseDate">The first release date of the release group.</param>
|
||||
/// <param name="date">The date the release was issued.</param>
|
||||
/// <param name="status">The status of the release.</param>
|
||||
/// <param name="releaseDate">The date of the release.</param>
|
||||
/// <param name="country">The country the release was issued in.</param>
|
||||
/// <returns>The JSON of the release response.</returns>
|
||||
private static string ReleaseJson(Guid id, string title, Guid releaseGroupId, string releaseGroupTitle, string releaseGroupFirstReleaseDate, string status, string releaseDate, string country)
|
||||
{
|
||||
return $$"""
|
||||
{
|
||||
"id": "{{id:D}}",
|
||||
"title": "{{title}}",
|
||||
"status": "{{status}}",
|
||||
"date": "{{releaseDate}}",
|
||||
"country": "{{country}}",
|
||||
"release-group": { "id": "{{releaseGroupId:D}}", "title": "{{releaseGroupTitle}}", "primary-type": "Album", "first-release-date": "{{releaseGroupFirstReleaseDate}}" }
|
||||
}
|
||||
""";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an OK response with the provided JSON body.
|
||||
/// </summary>
|
||||
/// <param name="json">The JSON body of the response.</param>
|
||||
/// <returns>The created response.</returns>
|
||||
private static HttpResponseMessage Json(string json)
|
||||
{
|
||||
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||
}
|
||||
}
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Plugins.MusicBrainz.Core;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Api;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Settings;
|
||||
using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzArtistMetadataProvider"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzArtistMetadataProviderTests
|
||||
{
|
||||
private static readonly Guid s_artistId = Guid.Parse("11111111-1111-1111-1111-111111111111");
|
||||
|
||||
private readonly ArtistMetadataLookupDtoFixture _artistMetadataLookupDtoFixture = new();
|
||||
private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Name_WhenCalled_ShouldReturnTheProviderDisplayName()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzArtistMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
|
||||
// Act
|
||||
string result = sut.Name;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("MusicBrainz", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzArtistMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
|
||||
// Act
|
||||
IReadOnlyList<LibraryType> result = sut.SupportedLibraryTypes;
|
||||
|
||||
// Assert
|
||||
Assert.Equal([LibraryType.Music], result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequiresWebAccess_WhenCalled_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzArtistMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
|
||||
// Act
|
||||
bool result = sut.RequiresWebAccess;
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task GetSearchResultsAsync_WhenTheNameIsMissing_ShouldReturnAnEmptyCollectionWithoutAnyRequest(string? name)
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", name: name);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<ArtistMetadataDto> result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
Assert.Equal(0, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenTheSearchReturnsArtists_ShouldMapEveryNamedArtistAndSkipTheUnnamedOnes()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """
|
||||
{
|
||||
"count": 3,
|
||||
"artists": [
|
||||
{ "id": "11111111-1111-1111-1111-111111111111", "name": "The Artist" },
|
||||
{ "id": "22222222-2222-2222-2222-222222222222", "name": "Other Artist" },
|
||||
{ "id": "33333333-3333-3333-3333-333333333333", "name": null }
|
||||
]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON));
|
||||
ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", name: " The Artist ");
|
||||
|
||||
// Act
|
||||
IReadOnlyList<ArtistMetadataDto> result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.Equal("The Artist", result[0].Name);
|
||||
Assert.Equal("Other Artist", result[1].Name);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
// the name is trimmed and the configured search result limit is used
|
||||
Assert.Contains("limit=10", handler.Requests[0].RequestUri!.Query);
|
||||
Assert.Contains("query=The%20Artist", handler.Requests[0].RequestUri!.Query);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenTheSearchResponseIsEmpty_ShouldReturnAnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":0,"artists":[]}""";
|
||||
(MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON));
|
||||
ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist");
|
||||
|
||||
// Act
|
||||
IReadOnlyList<ArtistMetadataDto> result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheMusicBrainzIdentifierIsPresent_ShouldLookUpTheArtistByIdentifier()
|
||||
{
|
||||
// Arrange
|
||||
string artistJson = CreateArtistJson("The Artist", "Group", "11111111-1111-1111-1111-111111111111");
|
||||
(MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(artistJson));
|
||||
ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", musicBrainzArtistId: s_artistId);
|
||||
|
||||
// Act
|
||||
ArtistMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("The Artist", result.Name);
|
||||
Assert.Equal(MusicArtistType.Group, result.Type);
|
||||
Assert.Equal(s_artistId, result.MusicBrainzArtistId);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
Assert.Contains($"/artist/{s_artistId:D}", handler.Requests[0].RequestUri!.AbsolutePath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheIdentifierLookupReturnsNothing_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound));
|
||||
ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", musicBrainzArtistId: s_artistId);
|
||||
|
||||
// Act
|
||||
ArtistMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenThereIsNeitherAnIdentifierNorAName_ShouldReturnNullWithoutAnyRequest()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", name: " ");
|
||||
|
||||
// Act
|
||||
ArtistMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
Assert.Equal(0, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheNameSearchReturnsNothing_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":0,"artists":[]}""";
|
||||
(MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON));
|
||||
|
||||
// Act
|
||||
ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheSearchResultHasNoIdentifier_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":1,"artists":[{"id":null,"name":"The Artist"}]}""";
|
||||
(MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON));
|
||||
|
||||
// Act
|
||||
ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheSearchResultIdentifierIsNotAGuid_ShouldMapTheSearchResult()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":1,"artists":[{"id":"not-a-guid","name":"The Artist","type":"Group"}]}""";
|
||||
(MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON));
|
||||
|
||||
// Act
|
||||
ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("The Artist", result.Name);
|
||||
Assert.Equal(MusicArtistType.Group, result.Type);
|
||||
Assert.Null(result.MusicBrainzArtistId);
|
||||
// the search is used, and the per identifier lookup must not be requested
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheSearchResultIdentifierIsAGuid_ShouldResolveTheDetailedArtist()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":1,"artists":[{"id":"11111111-1111-1111-1111-111111111111","name":"The Artist"}]}""";
|
||||
string detailJson = CreateArtistJson("The Detailed Artist", "Person", "11111111-1111-1111-1111-111111111111");
|
||||
(MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => request.RequestUri!.AbsolutePath.Contains("/artist/") ? Json(detailJson) : Json(SEARCH_JSON));
|
||||
|
||||
// Act
|
||||
ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("The Detailed Artist", result.Name);
|
||||
Assert.Equal(MusicArtistType.Person, result.Type);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
Assert.Contains("limit=1", handler.Requests[0].RequestUri!.Query);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheDetailedArtistLookupReturnsNothing_ShouldMapTheSearchResult()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":1,"artists":[{"id":"11111111-1111-1111-1111-111111111111","name":"The Artist","type":"Group"}]}""";
|
||||
(MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => request.RequestUri!.AbsolutePath.Contains("/artist/") ? new HttpResponseMessage(HttpStatusCode.NotFound) : Json(SEARCH_JSON));
|
||||
|
||||
// Act
|
||||
ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("The Artist", result.Name);
|
||||
Assert.Equal(MusicArtistType.Group, result.Type);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MusicBrainzArtistMetadataProvider"/> whose requests are answered by the provided stub handler.
|
||||
/// </summary>
|
||||
/// <param name="responseFactory">The factory that produces the response of a request.</param>
|
||||
/// <returns>The created provider and its stub handler.</returns>
|
||||
private (MusicBrainzArtistMetadataProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func<HttpRequestMessage, int, HttpResponseMessage> responseFactory)
|
||||
{
|
||||
StubHttpMessageHandler handler = new(responseFactory);
|
||||
MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create(
|
||||
baseUrl: "http://localhost/",
|
||||
searchResultLimit: 10,
|
||||
releaseLookupLimit: 25,
|
||||
minimumRequestInterval: TimeSpan.Zero));
|
||||
MusicBrainzHttpClient httpClient = new(new HttpClient(handler), settingsProvider, new MusicBrainzRequestThrottle(), new MusicBrainzResponseCache());
|
||||
return (new MusicBrainzArtistMetadataProvider(httpClient, settingsProvider), handler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the JSON of an artist response.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <param name="type">The MusicBrainz type of the artist.</param>
|
||||
/// <param name="id">The MusicBrainz identifier of the artist.</param>
|
||||
/// <returns>The JSON of the artist response.</returns>
|
||||
private static string CreateArtistJson(string name, string type, string id)
|
||||
{
|
||||
return $$"""{"id":"{{id}}","name":"{{name}}","type":"{{type}}"}""";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an OK response with the provided JSON body.
|
||||
/// </summary>
|
||||
/// <param name="json">The JSON body of the response.</param>
|
||||
/// <returns>The created response.</returns>
|
||||
private static HttpResponseMessage Json(string json)
|
||||
{
|
||||
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Lumina.Plugins.MusicBrainz.Core;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Settings;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzPlugin"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzPluginTests
|
||||
{
|
||||
private readonly MusicBrainzPlugin _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void Id_WhenCalled_ShouldReturnStablePluginIdentifier()
|
||||
{
|
||||
// Act
|
||||
Guid result = _sut.Id;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MusicBrainzPlugin.s_pluginId, result);
|
||||
Assert.Equal(new Guid("f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3"), result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Name_WhenCalled_ShouldReturnPluginDisplayName()
|
||||
{
|
||||
// Act
|
||||
string result = _sut.Name;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("MusicBrainz Metadata", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Author_WhenCalled_ShouldReturnPluginAuthor()
|
||||
{
|
||||
// Act
|
||||
string result = _sut.Author;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Lumina", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Version_WhenCalled_ShouldReturnPluginVersion()
|
||||
{
|
||||
// Act
|
||||
Version result = _sut.Version;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(new Version(1, 0, 0), result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Description_WhenCalled_ShouldReturnPluginDescription()
|
||||
{
|
||||
// Act
|
||||
string result = _sut.Description;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Retrieves artist, album and track metadata from MusicBrainz.", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSettingsSchema_WhenCalled_ShouldReturnTheSixSettingDescriptors()
|
||||
{
|
||||
// Act
|
||||
IReadOnlyList<PluginSettingDescriptorDto> result = _sut.GetSettingsSchema();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(6, result.Count);
|
||||
Assert.Equal(
|
||||
[
|
||||
MusicBrainzSettingsKeys.BASE_URL,
|
||||
MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL,
|
||||
MusicBrainzSettingsKeys.CONTACT_EMAIL,
|
||||
MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT,
|
||||
MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT,
|
||||
MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS
|
||||
],
|
||||
result.Select(descriptor => descriptor.Key));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(MusicBrainzSettingsKeys.BASE_URL, "Base URL", PluginSettingType.Text, "https://musicbrainz.org/ws/2/")]
|
||||
[InlineData(MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL, "Allow LAN/Private Base URL", PluginSettingType.Boolean, "false")]
|
||||
[InlineData(MusicBrainzSettingsKeys.CONTACT_EMAIL, "Contact Email", PluginSettingType.Text, null)]
|
||||
[InlineData(MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT, "Search Result Limit", PluginSettingType.Number, "10")]
|
||||
[InlineData(MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT, "Release Lookup Limit", PluginSettingType.Number, "25")]
|
||||
[InlineData(MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, "Minimum Request Interval (seconds)", PluginSettingType.Number, "1.0")]
|
||||
public void GetSettingsSchema_WhenCalled_ShouldDescribeEachSettingCorrectly(string key, string label, PluginSettingType type, string? defaultValue)
|
||||
{
|
||||
// Act
|
||||
IReadOnlyList<PluginSettingDescriptorDto> result = _sut.GetSettingsSchema();
|
||||
|
||||
// Assert
|
||||
PluginSettingDescriptorDto descriptor = Assert.Single(result, candidate => candidate.Key == key);
|
||||
Assert.Equal(label, descriptor.Label);
|
||||
Assert.Equal(type, descriptor.Type);
|
||||
Assert.Equal(defaultValue, descriptor.DefaultValue);
|
||||
Assert.Null(descriptor.AllowedValues);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegisterServices_WhenCalled_ShouldRegisterTheThreeKeyedMetadataProviders()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
_sut.RegisterServices(services);
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(3, serviceProvider.GetKeyedServices<IMetadataProvider>(MusicBrainzPlugin.s_pluginId).Count());
|
||||
Assert.Empty(serviceProvider.GetKeyedServices<IMetadataProvider>(Guid.NewGuid()));
|
||||
}
|
||||
}
|
||||
+730
@@ -0,0 +1,730 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Plugins.MusicBrainz.Core;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Api;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Settings;
|
||||
using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzTrackMetadataProvider"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzTrackMetadataProviderTests
|
||||
{
|
||||
private static readonly Guid s_releaseId = Guid.Parse("11111111-1111-1111-1111-111111111111");
|
||||
private static readonly Guid s_recordingId = Guid.Parse("22222222-2222-2222-2222-222222222222");
|
||||
private static readonly Guid s_secondRecordingId = Guid.Parse("33333333-3333-3333-3333-333333333333");
|
||||
private static readonly Guid s_workId = Guid.Parse("44444444-4444-4444-4444-444444444444");
|
||||
|
||||
private readonly TrackMetadataLookupDtoFixture _trackMetadataLookupDtoFixture = new();
|
||||
private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Name_WhenCalled_ShouldReturnTheProviderDisplayName()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzTrackMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
|
||||
// Act
|
||||
string result = sut.Name;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("MusicBrainz", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzTrackMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
|
||||
// Act
|
||||
IReadOnlyList<LibraryType> result = sut.SupportedLibraryTypes;
|
||||
|
||||
// Assert
|
||||
Assert.Equal([LibraryType.Music], result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequiresWebAccess_WhenCalled_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzTrackMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
|
||||
// Act
|
||||
bool result = sut.RequiresWebAccess;
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task GetSearchResultsAsync_WhenTheTitleIsMissing_ShouldReturnAnEmptyCollectionWithoutAnyRequest(string? title)
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", title: title);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<AudioMetadataDto> result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
Assert.Equal(0, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenTheSearchReturnsRecordings_ShouldMapEveryTitledOneAndSkipTheUntitledOnes()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """
|
||||
{
|
||||
"count": 3,
|
||||
"recordings": [
|
||||
{ "id": "22222222-2222-2222-2222-222222222222", "title": "The Track" },
|
||||
{ "id": "33333333-3333-3333-3333-333333333333", "title": "Other Track" },
|
||||
{ "id": "44444444-4444-4444-4444-444444444444", "title": null }
|
||||
]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", title: " The \"Track\" ", artistName: "The Artist", releaseName: "The Album");
|
||||
|
||||
// Act
|
||||
IReadOnlyList<AudioMetadataDto> result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.Equal("The Track", result[0].Title);
|
||||
Assert.Equal("Other Track", result[1].Title);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
Assert.Contains("limit=10", handler.Requests[0].RequestUri!.Query);
|
||||
string query = Uri.UnescapeDataString(handler.Requests[0].RequestUri!.Query);
|
||||
Assert.Contains("recording:\"The Track\"", query);
|
||||
Assert.Contains("artist:\"The Artist\"", query);
|
||||
Assert.Contains("release:\"The Album\"", query);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseTracklistMatchesTheRecordingIdentifier_ShouldResolveTheTrackFromTheRelease()
|
||||
{
|
||||
// Arrange
|
||||
string releaseJson = TwoTrackReleaseJson();
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_secondRecordingId, trackNumber: 9, discNumber: 1);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(s_secondRecordingId, result.MusicBrainzRecordingId);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseTracklistDoesNotMatch_ShouldFallBackToTheRecordingIdentifier()
|
||||
{
|
||||
// Arrange
|
||||
Guid fallbackRecordingId = Guid.NewGuid();
|
||||
string releaseJson = TwoTrackReleaseJson();
|
||||
string recordingJson = RecordingJson(fallbackRecordingId, "Searched Track");
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(
|
||||
request.RequestUri!.AbsolutePath.Contains("/release/") ? releaseJson : recordingJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: fallbackRecordingId, trackNumber: 99);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The release has no matching track, so it falls through to the recording lookup.
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(fallbackRecordingId, result.MusicBrainzRecordingId);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseIsNotFound_ShouldFallBackToTheRecordingIdentifier()
|
||||
{
|
||||
// Arrange
|
||||
string recordingJson = RecordingJson(s_recordingId, "Searched Track");
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) =>
|
||||
request.RequestUri!.AbsolutePath.Contains("/release/") ? new HttpResponseMessage(HttpStatusCode.NotFound) : Json(recordingJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_recordingId);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(s_recordingId, result.MusicBrainzRecordingId);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheMatchedTrackHasNoRecording_ShouldFallThroughToTheSearch()
|
||||
{
|
||||
// Arrange
|
||||
const string RELEASE_JSON = """
|
||||
{
|
||||
"id": "11111111-1111-1111-1111-111111111111",
|
||||
"title": "The Release",
|
||||
"media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "Track Without Recording" } ] } ]
|
||||
}
|
||||
""";
|
||||
const string SEARCH_JSON = """{"count":1,"recordings":[{"id":"22222222-2222-2222-2222-222222222222","title":"Searched Track"}]}""";
|
||||
string recordingJson = RecordingJson(s_recordingId, "Searched Track");
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) =>
|
||||
request.RequestUri!.Query.Contains("query=")
|
||||
? Json(SEARCH_JSON)
|
||||
: request.RequestUri.AbsolutePath.Contains("/recording/")
|
||||
? Json(recordingJson)
|
||||
: Json(RELEASE_JSON));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, title: "Searched Track", trackNumber: 1, discNumber: 1);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Searched Track", result.Title);
|
||||
Assert.Equal(s_recordingId, result.MusicBrainzRecordingId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseTrackCarriesAnInlineWork_ShouldUseItWithoutAFurtherLookup()
|
||||
{
|
||||
// Arrange
|
||||
string releaseJson = $$"""
|
||||
{
|
||||
"id": "{{s_releaseId:D}}",
|
||||
"title": "The Release",
|
||||
"media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "The Track", "recording": { "id": "{{s_recordingId:D}}", "title": "The Track", "relations": [ { "target-type": "work", "work": { "id": "{{s_workId:D}}", "title": "Inline Work", "type": "Song" } } ] } } ] } ]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_recordingId);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.NotNull(result.Work);
|
||||
Assert.Equal(s_workId, result.Work.MusicBrainzWorkId);
|
||||
Assert.Equal("Inline Work", result.Work.Title);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheInlineWorkRelationHasNoWorkPayload_ShouldFallBackToTheWorkIdentifierOfTheTags()
|
||||
{
|
||||
// Arrange
|
||||
string releaseJson = $$"""
|
||||
{
|
||||
"id": "{{s_releaseId:D}}",
|
||||
"title": "The Release",
|
||||
"media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "The Track", "recording": { "id": "{{s_recordingId:D}}", "title": "The Track", "relations": [ { "target-type": "work" } ] } } ] } ]
|
||||
}
|
||||
""";
|
||||
string workJson = $$"""{"id":"{{s_workId:D}}","title":"Tagged Work"}""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(
|
||||
request.RequestUri!.AbsolutePath.Contains("/release/") ? releaseJson : workJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_recordingId, musicBrainzWorkId: s_workId);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.NotNull(result.Work);
|
||||
Assert.Equal(s_workId, result.Work.MusicBrainzWorkId);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseTrackCarriesAWorkWithoutAWorkTitleInTheTags_ShouldNotQueryTheWorkAgain()
|
||||
{
|
||||
// Arrange
|
||||
string releaseJson = $$"""
|
||||
{
|
||||
"id": "{{s_releaseId:D}}",
|
||||
"title": "The Release",
|
||||
"media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "The Track", "recording": { "id": "{{s_recordingId:D}}", "title": "The Track", "relations": [ { "target-type": "work", "work": { "id": "{{s_workId:D}}", "title": "Inline Work" } } ] } } ] } ]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_recordingId, musicBrainzWorkId: Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Inline Work", result.Work!.Title);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenOnlyTheRecordingIdentifierIsPresent_ShouldResolveTheRecordingItsWorkAndItsRelease()
|
||||
{
|
||||
// Arrange
|
||||
string recordingJson = $$"""
|
||||
{
|
||||
"id": "{{s_recordingId:D}}",
|
||||
"title": "The Track",
|
||||
"relations": [ { "target-type": "work", "work": { "id": "{{s_workId:D}}", "title": "The Work" } } ],
|
||||
"releases": [ { "id": "{{s_releaseId:D}}", "title": "The Release", "text-representation": { "language": "eng", "script": "Latn" } } ]
|
||||
}
|
||||
""";
|
||||
string workJson = $$"""{"id":"{{s_workId:D}}","title":"The Work","type":"Song"}""";
|
||||
string releaseJson = $$"""{"id":"{{s_releaseId:D}}","title":"The Release","text-representation":{"language":"eng","script":"Latn"} }""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) =>
|
||||
request.RequestUri!.AbsolutePath.Contains("/work/") ? Json(workJson)
|
||||
: request.RequestUri.AbsolutePath.Contains("/release/") ? Json(releaseJson)
|
||||
: Json(recordingJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(s_recordingId, result.MusicBrainzRecordingId);
|
||||
Assert.Equal(s_workId, result.Work!.MusicBrainzWorkId);
|
||||
Assert.Equal("The Work", result.Work.Title);
|
||||
Assert.NotNull(result.Language);
|
||||
Assert.Equal("en", result.Language.LanguageCode);
|
||||
Assert.Equal(3, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheRecordingRelationsCarryAnUnparsableWorkIdentifier_ShouldUseTheEmbeddedWork()
|
||||
{
|
||||
// Arrange
|
||||
string recordingJson = $$"""
|
||||
{
|
||||
"id": "{{s_recordingId:D}}",
|
||||
"title": "The Track",
|
||||
"relations": [ { "target-type": "work", "work": { "id": "not-a-guid", "title": "Embedded Work" } } ]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Embedded Work", result.Work!.Title);
|
||||
Assert.Null(result.Work.MusicBrainzWorkId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheRecordingHasNoWorkRelation_ShouldReturnATrackWithoutWork()
|
||||
{
|
||||
// Arrange
|
||||
string recordingJson = RecordingJson(s_recordingId, "The Track");
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.Work);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheRecordingReferencesAnUnparsableRelease_ShouldReturnATrackWithoutRelease()
|
||||
{
|
||||
// Arrange
|
||||
string recordingJson = $$"""
|
||||
{
|
||||
"id": "{{s_recordingId:D}}",
|
||||
"title": "The Track",
|
||||
"releases": [ { "id": "not-a-guid", "title": "The Release" } ]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.Language);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheRecordingHasNoReleases_ShouldReturnATrackWithoutRelease()
|
||||
{
|
||||
// Arrange
|
||||
string recordingJson = RecordingJson(s_recordingId, "The Track");
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.Script);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheIsrcMatchesARecordingWithAParsableIdentifier_ShouldResolveItInFull()
|
||||
{
|
||||
// Arrange
|
||||
const string ISRC_JSON = """{"recordings":[{"id":"22222222-2222-2222-2222-222222222222","title":"Isrc Track"}]}""";
|
||||
string recordingJson = RecordingJson(s_recordingId, "Resolved Isrc Track");
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) =>
|
||||
request.RequestUri!.AbsolutePath.Contains("/isrc/") ? Json(ISRC_JSON) : Json(recordingJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", isrc: "US1A2B3C4D5E");
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Resolved Isrc Track", result.Title);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheIsrcMatchesARecordingWithAnUnparsableIdentifier_ShouldReturnItAsIs()
|
||||
{
|
||||
// Arrange
|
||||
const string ISRC_JSON = """{"recordings":[{"id":"not-a-guid","title":"Raw Isrc Track"}]}""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(ISRC_JSON));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", isrc: "US1A2B3C4D5E");
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Raw Isrc Track", result.Title);
|
||||
Assert.Null(result.MusicBrainzRecordingId);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheIsrcMatchesNothing_ShouldReturnNullWithoutATitle()
|
||||
{
|
||||
// Arrange
|
||||
const string ISRC_JSON = """{"recordings":[]}""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(ISRC_JSON));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", isrc: "US1A2B3C4D5E");
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenOnlyTheTitleIsPresent_ShouldSearchAndResolveTheRecordingInFull()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":1,"recordings":[{"id":"22222222-2222-2222-2222-222222222222","title":"Searched Track"}]}""";
|
||||
string recordingJson = RecordingJson(s_recordingId, "Resolved Searched Track");
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) =>
|
||||
request.RequestUri!.Query.Contains("query=") ? Json(SEARCH_JSON) : Json(recordingJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", title: "Searched Track");
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Resolved Searched Track", result.Title);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheSearchReturnsNothing_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
const string SEARCH_JSON = """{"count":0,"recordings":[]}""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", title: "Searched Track");
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenNoLookupInformationIsPresent_ShouldReturnNullWithoutAnyRequest()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}"));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path");
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
Assert.Equal(0, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheLocalDiscNumberDoesNotMatchAnyMedium_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
string releaseJson = TwoTrackReleaseJson();
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, discNumber: 9);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenOnlyTheTrackNumberIsPresent_ShouldSelectTheTrackOnAnyDisc()
|
||||
{
|
||||
// Arrange
|
||||
string releaseJson = TwoTrackReleaseJson();
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, trackNumber: 2);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(s_secondRecordingId, result.MusicBrainzRecordingId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheTitleSinglesOutATrack_ShouldSelectIt()
|
||||
{
|
||||
// Arrange
|
||||
string releaseJson = TwoTrackReleaseJson();
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, title: "Second Track");
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(s_secondRecordingId, result.MusicBrainzRecordingId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenSeveralTracksShareTheTitle_ShouldUseTheDurationAsATieBreaker()
|
||||
{
|
||||
// Arrange
|
||||
const string RELEASE_JSON = """
|
||||
{
|
||||
"id": "11111111-1111-1111-1111-111111111111",
|
||||
"title": "The Release",
|
||||
"media": [ { "position": 1, "track-count": 2, "tracks": [
|
||||
{ "position": 1, "title": "Same Title", "length": 100000, "recording": { "id": "22222222-2222-2222-2222-222222222222", "title": "Same Title" } },
|
||||
{ "position": 2, "title": "Same Title", "length": 200000, "recording": { "id": "33333333-3333-3333-3333-333333333333", "title": "Same Title" } }
|
||||
] } ]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(RELEASE_JSON));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, title: "Same Title", durationInSeconds: 190);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(s_secondRecordingId, result.MusicBrainzRecordingId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenSeveralTracksShareTheTitleAndNoDurationIsKnown_ShouldSelectTheFirstOne()
|
||||
{
|
||||
// Arrange
|
||||
const string RELEASE_JSON = """
|
||||
{
|
||||
"id": "11111111-1111-1111-1111-111111111111",
|
||||
"title": "The Release",
|
||||
"media": [ { "position": 1, "track-count": 2, "tracks": [
|
||||
{ "position": 1, "title": "Same Title", "length": 100000, "recording": { "id": "22222222-2222-2222-2222-222222222222", "title": "Same Title" } },
|
||||
{ "position": 2, "title": "Same Title", "length": 200000, "recording": { "id": "33333333-3333-3333-3333-333333333333", "title": "Same Title" } }
|
||||
] } ]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(RELEASE_JSON));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, title: "Different Title");
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(s_recordingId, result.MusicBrainzRecordingId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheTagsCarryAWorkIdButMusicBrainzAlreadyLinkedAWork_ShouldResolveTheMusicBrainzWorkInFull()
|
||||
{
|
||||
// Arrange
|
||||
string recordingJson = $$"""
|
||||
{
|
||||
"id": "{{s_recordingId:D}}",
|
||||
"title": "The Track",
|
||||
"relations": [ { "target-type": "work", "work": { "id": "{{s_workId:D}}", "title": "MusicBrainz Work" } } ]
|
||||
}
|
||||
""";
|
||||
string workJson = $$"""{"id":"{{s_workId:D}}","title":"Tagged Work"}""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(
|
||||
request.RequestUri!.AbsolutePath.Contains("/work/") ? workJson : recordingJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId, musicBrainzWorkId: Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
// The work identifier linked by MusicBrainz is resolved in full, taking precedence over the work identifier of the tags.
|
||||
Assert.Equal(s_workId, result.Work!.MusicBrainzWorkId);
|
||||
Assert.Equal("Tagged Work", result.Work.Title);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenTheReleaseTracksHaveMissingOrUnparsableRecordingIdentifiers_ShouldFallBackToTheRecordingLookup()
|
||||
{
|
||||
// Arrange
|
||||
Guid fallbackRecordingId = Guid.NewGuid();
|
||||
const string RELEASE_JSON = """
|
||||
{
|
||||
"id": "11111111-1111-1111-1111-111111111111",
|
||||
"title": "The Release",
|
||||
"media": [ { "position": 1, "track-count": 2, "tracks": [
|
||||
{ "position": 1, "title": "Track Without Recording" },
|
||||
{ "position": 2, "title": "Track With Bad Recording", "recording": { "id": "not-a-guid", "title": "Track With Bad Recording" } }
|
||||
] } ]
|
||||
}
|
||||
""";
|
||||
string recordingJson = RecordingJson(fallbackRecordingId, "Fallback Track");
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(
|
||||
request.RequestUri!.AbsolutePath.Contains("/release/") ? RELEASE_JSON : recordingJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: fallbackRecordingId);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(fallbackRecordingId, result.MusicBrainzRecordingId);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenAWorkRelationHasNoWork_ShouldReturnATrackWithoutWork()
|
||||
{
|
||||
// Arrange
|
||||
string recordingJson = $$"""
|
||||
{
|
||||
"id": "{{s_recordingId:D}}",
|
||||
"title": "The Track",
|
||||
"relations": [ { "target-type": "work" } ]
|
||||
}
|
||||
""";
|
||||
(MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson));
|
||||
TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.Work);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MusicBrainzTrackMetadataProvider"/> whose requests are answered by the provided stub handler.
|
||||
/// </summary>
|
||||
/// <param name="responseFactory">The factory that produces the response of a request.</param>
|
||||
/// <returns>The created provider and its stub handler.</returns>
|
||||
private (MusicBrainzTrackMetadataProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func<HttpRequestMessage, int, HttpResponseMessage> responseFactory)
|
||||
{
|
||||
StubHttpMessageHandler handler = new(responseFactory);
|
||||
MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create(
|
||||
baseUrl: "http://localhost/",
|
||||
searchResultLimit: 10,
|
||||
releaseLookupLimit: 25,
|
||||
minimumRequestInterval: TimeSpan.Zero));
|
||||
MusicBrainzHttpClient httpClient = new(new HttpClient(handler), settingsProvider, new MusicBrainzRequestThrottle(), new MusicBrainzResponseCache());
|
||||
return (new MusicBrainzTrackMetadataProvider(httpClient, settingsProvider), handler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the JSON of a release with two tracks, each with its own recording.
|
||||
/// </summary>
|
||||
/// <returns>The JSON of the release.</returns>
|
||||
private static string TwoTrackReleaseJson()
|
||||
{
|
||||
return $$"""
|
||||
{
|
||||
"id": "{{s_releaseId:D}}",
|
||||
"title": "The Release",
|
||||
"media": [ { "position": 1, "track-count": 2, "tracks": [
|
||||
{ "position": 1, "title": "First Track", "recording": { "id": "{{s_recordingId:D}}", "title": "First Track" } },
|
||||
{ "position": 2, "title": "Second Track", "recording": { "id": "{{s_secondRecordingId:D}}", "title": "Second Track" } }
|
||||
] } ]
|
||||
}
|
||||
""";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the JSON of a recording response.
|
||||
/// </summary>
|
||||
/// <param name="id">The MusicBrainz identifier of the recording.</param>
|
||||
/// <param name="title">The title of the recording.</param>
|
||||
/// <returns>The JSON of the recording response.</returns>
|
||||
private static string RecordingJson(Guid id, string title)
|
||||
{
|
||||
return $$"""{"id":"{{id:D}}","title":"{{title}}"}""";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an OK response with the provided JSON body.
|
||||
/// </summary>
|
||||
/// <param name="json">The JSON body of the response.</param>
|
||||
/// <returns>The created response.</returns>
|
||||
private static HttpResponseMessage Json(string json)
|
||||
{
|
||||
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||
}
|
||||
}
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Settings;
|
||||
using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzSettingsProvider"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzSettingsProviderTests
|
||||
{
|
||||
private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenNoStoreIsAvailable_ShouldReturnTheDefaults()
|
||||
{
|
||||
// Arrange
|
||||
MusicBrainzSettingsDto defaults = CreateDefaults();
|
||||
MusicBrainzSettingsProvider sut = new(null, Guid.NewGuid(), defaults);
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotSame(defaults, result);
|
||||
Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl);
|
||||
Assert.False(result.DoesAllowPrivateBaseUrl);
|
||||
Assert.Equal("Lumina-MusicBrainz/1.0", result.UserAgent);
|
||||
Assert.Equal("default@example.com", result.ContactEmail);
|
||||
Assert.Equal(10, result.SearchResultLimit);
|
||||
Assert.Equal(25, result.ReleaseLookupLimit);
|
||||
Assert.Equal(TimeSpan.FromSeconds(1), result.MinimumRequestInterval);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenTheStoreReturnsNoSettings_ShouldReturnTheDefaults()
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns((IReadOnlyDictionary<string, string>?)null);
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl);
|
||||
Assert.Equal(10, result.SearchResultLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenEverySettingIsPersisted_ShouldOverlayThemOverTheDefaults()
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
[MusicBrainzSettingsKeys.BASE_URL] = "https://mirror.example/ws/2/",
|
||||
[MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL] = "true",
|
||||
[MusicBrainzSettingsKeys.CONTACT_EMAIL] = " contact@example.com ",
|
||||
[MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT] = "42",
|
||||
[MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT] = "30",
|
||||
[MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = "2.5"
|
||||
});
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("https://mirror.example/ws/2/", result.BaseUrl);
|
||||
Assert.True(result.DoesAllowPrivateBaseUrl);
|
||||
Assert.Equal("contact@example.com", result.ContactEmail);
|
||||
Assert.Equal(42, result.SearchResultLimit);
|
||||
Assert.Equal(30, result.ReleaseLookupLimit);
|
||||
Assert.Equal(TimeSpan.FromSeconds(2.5), result.MinimumRequestInterval);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not-a-url")] // a value that is not an URI at all
|
||||
[InlineData("ftp://mirror.example/")] // an absolute URI with an unsupported scheme
|
||||
[InlineData("relative/path")] // a relative URI
|
||||
[InlineData(" ")] // only white space
|
||||
public async Task GetAsync_WhenThePersistedBaseUrlIsInvalid_ShouldKeepTheDefaultBaseUrl(string baseUrl)
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
|
||||
new Dictionary<string, string> { [MusicBrainzSettingsKeys.BASE_URL] = baseUrl });
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("http://127.0.0.1/ws/2/")] // IPv4 loopback
|
||||
[InlineData("http://localhost/ws/2/")] // loopback host name
|
||||
[InlineData("http://[::1]/ws/2/")] // IPv6 loopback
|
||||
[InlineData("http://169.254.169.254/latest/meta-data/")] // link local cloud metadata endpoint
|
||||
[InlineData("http://10.0.0.5/ws/2/")] // private class A range
|
||||
[InlineData("http://172.16.0.1/ws/2/")] // private class B range
|
||||
[InlineData("http://192.168.1.10/ws/2/")] // private class C range
|
||||
[InlineData("http://0.0.0.0/ws/2/")] // unspecified address
|
||||
[InlineData("http://[fc00::1]/ws/2/")] // IPv6 unique local range
|
||||
public async Task GetAsync_WhenThePersistedBaseUrlPointsAtALocalOrPrivateHost_ShouldKeepTheDefaultBaseUrl(string baseUrl)
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
|
||||
new Dictionary<string, string> { [MusicBrainzSettingsKeys.BASE_URL] = baseUrl });
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("http://192.168.1.10/ws/2/")] // private class C range, a typical self hosted mirror
|
||||
[InlineData("http://localhost/ws/2/")] // loopback host name
|
||||
[InlineData("http://[fc00::1]/ws/2/")] // IPv6 unique local range
|
||||
public async Task GetAsync_WhenPrivateBaseUrlsAreExplicitlyAllowed_ShouldApplyThem(string baseUrl)
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
[MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL] = "true",
|
||||
[MusicBrainzSettingsKeys.BASE_URL] = baseUrl
|
||||
});
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(baseUrl, result.BaseUrl);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("user\r\n@example.com")] // carriage return and line feed injection
|
||||
[InlineData("user@example.com\r\nX-Injected: value")] // header injection attempt
|
||||
[InlineData("user(comment)@example.com")] // parentheses break the user agent comment
|
||||
[InlineData("user\"quoted\"@example.com")] // quotes break the header value
|
||||
[InlineData("user example@example.com")] // an inner space is not a valid token character
|
||||
public async Task GetAsync_WhenThePersistedContactEmailContainsUnsafeCharacters_ShouldDropIt(string storedEmail)
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
|
||||
new Dictionary<string, string> { [MusicBrainzSettingsKeys.CONTACT_EMAIL] = storedEmail });
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.ContactEmail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenThePersistedBaseUrlIsAnAbsoluteHttpUrl_ShouldApplyIt()
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
|
||||
new Dictionary<string, string> { [MusicBrainzSettingsKeys.BASE_URL] = "http://mirror.example/ws/2/" });
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("http://mirror.example/ws/2/", result.BaseUrl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenThePersistedBaseUrlIsNull_ShouldKeepTheDefaultBaseUrl()
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
|
||||
new Dictionary<string, string> { [MusicBrainzSettingsKeys.BASE_URL] = null! });
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("", null)] // an empty value clears the email
|
||||
[InlineData(" ", null)] // a white space value clears the email
|
||||
[InlineData(" user@example.com ", "user@example.com")] // a value with surrounding white space is trimmed
|
||||
public async Task GetAsync_WhenThePersistedContactEmailIsPresent_ShouldSetOrClearIt(string storedEmail, string? expectedEmail)
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
|
||||
new Dictionary<string, string> { [MusicBrainzSettingsKeys.CONTACT_EMAIL] = storedEmail });
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedEmail, result.ContactEmail);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("42", 42)]
|
||||
[InlineData("0", 1)] // a limit of zero is clamped to one
|
||||
[InlineData("-5", 1)] // a negative limit is clamped to one
|
||||
[InlineData("not-a-number", 10)] // an unparsable value keeps the default
|
||||
public async Task GetAsync_WhenThePersistedSearchResultLimitIsPresent_ShouldParseAndClampIt(string storedLimit, int expectedLimit)
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
|
||||
new Dictionary<string, string> { [MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT] = storedLimit });
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedLimit, result.SearchResultLimit);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("30", 30)]
|
||||
[InlineData("0", 1)] // a limit of zero is clamped to one
|
||||
[InlineData("-5", 1)] // a negative limit is clamped to one
|
||||
[InlineData("not-a-number", 25)] // an unparsable value keeps the default
|
||||
public async Task GetAsync_WhenThePersistedReleaseLookupLimitIsPresent_ShouldParseAndClampIt(string storedLimit, int expectedLimit)
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
|
||||
new Dictionary<string, string> { [MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT] = storedLimit });
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedLimit, result.ReleaseLookupLimit);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("2.5", 2.5)]
|
||||
[InlineData("0", 0)] // an interval of zero is allowed
|
||||
[InlineData("-3", 0)] // a negative interval is clamped to zero
|
||||
[InlineData("not-a-number", 1)] // an unparsable value keeps the default
|
||||
public async Task GetAsync_WhenThePersistedMinimumRequestIntervalIsPresent_ShouldParseAndClampIt(string storedInterval, double expectedSeconds)
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
|
||||
new Dictionary<string, string> { [MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = storedInterval });
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromSeconds(expectedSeconds), result.MinimumRequestInterval);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenCalledTwice_ShouldReadTheStoreOnlyOnce()
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(new Dictionary<string, string>());
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto first = await sut.GetAsync(CancellationToken.None);
|
||||
MusicBrainzSettingsDto second = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Same(first, second);
|
||||
await mockStore.Received(1).GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenCalledConcurrently_ShouldReadTheStoreOnlyOnce()
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(new Dictionary<string, string>());
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto[] results = await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => sut.GetAsync(CancellationToken.None)));
|
||||
|
||||
// Assert
|
||||
Assert.All(results, result => Assert.Same(results[0], result));
|
||||
await mockStore.Received(1).GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldThrowOperationCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using (CancellationTokenSource cancellationTokenSource = new())
|
||||
{
|
||||
cancellationTokenSource.Cancel();
|
||||
MusicBrainzSettingsProvider sut = new(null, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return sut.GetAsync(cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the default settings used by the tests of the provider.
|
||||
/// </summary>
|
||||
/// <returns>The default settings.</returns>
|
||||
private MusicBrainzSettingsDto CreateDefaults()
|
||||
{
|
||||
return _musicBrainzSettingsDtoFixture.Create(
|
||||
baseUrl: "https://musicbrainz.org/ws/2/",
|
||||
doesAllowPrivateBaseUrl: false,
|
||||
userAgent: "Lumina-MusicBrainz/1.0",
|
||||
contactEmail: "default@example.com",
|
||||
searchResultLimit: 10,
|
||||
releaseLookupLimit: 25,
|
||||
minimumRequestInterval: TimeSpan.FromSeconds(1));
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
|
||||
<_Parameter1>DisableTestParallelization = true</_Parameter1>
|
||||
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" />
|
||||
<PackageReference Include="Bogus" />
|
||||
<PackageReference Include="coverlet.collector">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="NSubstitute" />
|
||||
<PackageReference Include="xunit" />
|
||||
<PackageReference Include="xunit.runner.visualstudio">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.MusicBrainz\Lumina.Plugins.MusicBrainz.csproj" />
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Plugins.MusicBrainz.Fixtures\Lumina.Plugins.MusicBrainz.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in new issue
Block a user