mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 18:13:42 +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
+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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user