mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 17:11:10 +00:00
Adds the Cover Art Archive music artwork plugin, its fixtures, and its unit and security test suites
This commit is contained in:
1 parent
c8a8d8750b
commit
fb05561619
36 files changed
+4029
No files matched your search
+205
@@ -0,0 +1,205 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Lumina.Plugins.CoverArtArchive.Common.DependencyInjection;
|
||||
using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.CoverArtArchive.Core.Api;
|
||||
using Lumina.Plugins.CoverArtArchive.Core.Settings;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.UnitTests.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CoverArtArchiveServices"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CoverArtArchiveServicesTests
|
||||
{
|
||||
[Fact]
|
||||
public void AddCoverArtArchiveArtworkProvider_WhenServicesIsNull_ShouldThrowArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
IServiceCollection services = null!;
|
||||
|
||||
// Act
|
||||
Action act = () => services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.Throws<ArgumentNullException>(act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldReturnTheSameServiceCollection()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
IServiceCollection result = services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.Same(services, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldRegisterTheArtworkProviderForKeyedResolution()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
services.AddCoverArtArchiveArtworkProvider(pluginId: pluginId);
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
// Assert
|
||||
Assert.Single(serviceProvider.GetKeyedServices<IArtworkProvider>(pluginId));
|
||||
Assert.Empty(serviceProvider.GetKeyedServices<IArtworkProvider>(Guid.NewGuid()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldRegisterTheSettingsProviderAsScoped()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
ServiceDescriptor settingsProviderDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveSettingsProvider));
|
||||
Assert.Equal(ServiceLifetime.Scoped, settingsProviderDescriptor.Lifetime);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldRegisterTheThrottleAndTheResponseCacheAsSingletons()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
ServiceDescriptor throttleDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveRequestThrottle));
|
||||
ServiceDescriptor responseCacheDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveResponseCache));
|
||||
Assert.Equal(ServiceLifetime.Singleton, throttleDescriptor.Lifetime);
|
||||
Assert.Equal(ServiceLifetime.Singleton, responseCacheDescriptor.Lifetime);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldRegisterTheHttpClient()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid());
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(serviceProvider.GetService<CoverArtArchiveHttpClient>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddCoverArtArchiveArtworkProvider_WhenASettingsCallbackIsProvided_ShouldApplyItToTheDefaults()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
services.AddCoverArtArchiveArtworkProvider(pluginId: pluginId, settings => settings.ContactEmail = "custom@example.com");
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
using (IServiceScope scope = serviceProvider.CreateScope())
|
||||
{
|
||||
CoverArtArchiveSettingsProvider settingsProvider = scope.ServiceProvider.GetRequiredService<CoverArtArchiveSettingsProvider>();
|
||||
CoverArtArchiveSettingsDto settings = await settingsProvider.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("custom@example.com", settings.ContactEmail);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddCoverArtArchiveArtworkProvider_WhenTheClientIsResolved_ShouldDisableAutomaticRedirectsOnItsPrimaryHandler()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid());
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
using (IServiceScope scope = serviceProvider.CreateScope())
|
||||
{
|
||||
// Act
|
||||
CoverArtArchiveHttpClient client = scope.ServiceProvider.GetRequiredService<CoverArtArchiveHttpClient>();
|
||||
HttpClientHandler primaryHandler = GetPrimaryHandler(client);
|
||||
|
||||
// Assert
|
||||
// Automatic redirects must stay disabled on the primary handler, otherwise it would follow a server controlled redirect on its own,
|
||||
// before the client can check the target host against the Cover Art Archive and the Internet Archive, bypassing that control.
|
||||
Assert.False(primaryHandler.AllowAutoRedirect);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddCoverArtArchiveArtworkProvider_WhenCalledTwice_ShouldNotDuplicateTheTryAddServices()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
services.AddCoverArtArchiveArtworkProvider(pluginId: pluginId);
|
||||
services.AddCoverArtArchiveArtworkProvider(pluginId: pluginId);
|
||||
|
||||
// Assert
|
||||
// The settings provider, the throttle and the response cache are registered with TryAdd, so a second call must not add them again.
|
||||
Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveRequestThrottle));
|
||||
Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveResponseCache));
|
||||
Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveSettingsProvider));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the primary HTTP message handler of the provided client, unwrapping the delegating handlers built by the HTTP client factory around it.
|
||||
/// </summary>
|
||||
/// <param name="client">The client whose primary handler is retrieved.</param>
|
||||
/// <returns>The primary HTTP client handler of the client.</returns>
|
||||
private static HttpClientHandler GetPrimaryHandler(CoverArtArchiveHttpClient client)
|
||||
{
|
||||
HttpClient httpClient = (HttpClient)GetFieldOfType(client, typeof(HttpClient))!;
|
||||
HttpMessageHandler? handler = (HttpMessageHandler?)GetFieldOfType(httpClient, typeof(HttpMessageHandler));
|
||||
while (handler is DelegatingHandler delegatingHandler)
|
||||
handler = delegatingHandler.InnerHandler;
|
||||
return Assert.IsType<HttpClientHandler>(handler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the first field, declared on the provided <paramref name="instance"/> or any of its base types, whose type is assignable to
|
||||
/// <paramref name="fieldType"/>, without relying on the field name, so the test keeps working across runtime versions.
|
||||
/// </summary>
|
||||
/// <param name="instance">The instance whose field is read.</param>
|
||||
/// <param name="fieldType">The type the field must be assignable to.</param>
|
||||
/// <returns>The value of the found field.</returns>
|
||||
/// <exception cref="InvalidOperationException">Thrown when no field assignable to <paramref name="fieldType"/> is found.</exception>
|
||||
private static object GetFieldOfType(object instance, Type fieldType)
|
||||
{
|
||||
Type? type = instance.GetType();
|
||||
while (type is not null)
|
||||
{
|
||||
FieldInfo? field = type
|
||||
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly)
|
||||
.FirstOrDefault(candidate => fieldType.IsAssignableFrom(candidate.FieldType));
|
||||
if (field is not null)
|
||||
return field.GetValue(instance)!;
|
||||
type = type.BaseType;
|
||||
}
|
||||
throw new InvalidOperationException($"No field assignable to {fieldType} was found on {instance.GetType()} or its base types.");
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CoverArtArchiveArtworkResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CoverArtArchiveArtworkResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void Deserialize_WhenTheApiReturnsImages_ShouldDeserializeEveryImage()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"images": [
|
||||
{ "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg", "front": true, "types": [ "Front" ] },
|
||||
{ "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/2.jpg", "back": true, "types": [ "Back" ] }
|
||||
]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize<CoverArtArchiveArtworkResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.NotNull(response.Images);
|
||||
Assert.Equal(2, response.Images.Count);
|
||||
Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg", response.Images[0]!.Image);
|
||||
Assert.Equal(["Front"], response.Images[0]!.Types);
|
||||
Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/2.jpg", response.Images[1]!.Image);
|
||||
Assert.Equal(["Back"], response.Images[1]!.Types);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenTheApiReturnsANullImagesCollection_ShouldDeserializeAsNull()
|
||||
{
|
||||
// Arrange
|
||||
// The API can answer with a null images collection, which must not be turned into anything else by the deserializer.
|
||||
const string JSON = """{"images":null}""";
|
||||
|
||||
// Act
|
||||
CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize<CoverArtArchiveArtworkResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Null(response.Images);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenTheImagesCollectionContainsNullElements_ShouldKeepThem()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"images":[null,{"image":"https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg"}]}""";
|
||||
|
||||
// Act
|
||||
CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize<CoverArtArchiveArtworkResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.NotNull(response.Images);
|
||||
Assert.Equal(2, response.Images.Count);
|
||||
Assert.Null(response.Images[0]);
|
||||
Assert.NotNull(response.Images[1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenTheImagesCollectionIsEmpty_ShouldDeserializeAsEmpty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"images":[]}""";
|
||||
|
||||
// Act
|
||||
CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize<CoverArtArchiveArtworkResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.NotNull(response.Images);
|
||||
Assert.Empty(response.Images);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenThePropertyIsMissing_ShouldDefaultToNull()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = "{}";
|
||||
|
||||
// Act
|
||||
CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize<CoverArtArchiveArtworkResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Null(response.Images);
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.UnitTests.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CoverArtArchiveImageResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CoverArtArchiveImageResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """
|
||||
{
|
||||
"approved": true,
|
||||
"back": true,
|
||||
"comment": "A comment",
|
||||
"front": false,
|
||||
"id": 12345,
|
||||
"image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/12345.jpg",
|
||||
"thumbnail": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/12345-250.jpg",
|
||||
"types": [ "Back", "Booklet" ]
|
||||
}
|
||||
""";
|
||||
|
||||
// Act
|
||||
CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize<CoverArtArchiveImageResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/12345.jpg", response.Image);
|
||||
Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/12345-250.jpg", response.Thumbnail);
|
||||
Assert.Equal(["Back", "Booklet"], response.Types);
|
||||
Assert.False(response.IsFront);
|
||||
Assert.True(response.IsBack);
|
||||
Assert.Equal("A comment", response.Comment);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenTheApiReturnsANullTypes_ShouldDeserializeAsNull()
|
||||
{
|
||||
// Arrange
|
||||
// The API can answer with a null types collection, which must not be turned into anything else by the deserializer.
|
||||
const string JSON = """{"image":"https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg","types":null}""";
|
||||
|
||||
// Act
|
||||
CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize<CoverArtArchiveImageResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Null(response.Types);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenTheTypesCollectionContainsNullElements_ShouldKeepThem()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"types":["Front",null,"Booklet"]}""";
|
||||
|
||||
// Act
|
||||
CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize<CoverArtArchiveImageResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.NotNull(response.Types);
|
||||
Assert.Equal(["Front", null, "Booklet"], response.Types);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenTheApiReturnsANullImage_ShouldDeserializeAsNull()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = """{"image":null,"types":["Front"]}""";
|
||||
|
||||
// Act
|
||||
CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize<CoverArtArchiveImageResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Null(response.Image);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WhenThePropertiesAreMissing_ShouldDefaultToNullAndFalse()
|
||||
{
|
||||
// Arrange
|
||||
const string JSON = "{}";
|
||||
|
||||
// Act
|
||||
CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize<CoverArtArchiveImageResponse>(JSON);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
Assert.Null(response.Image);
|
||||
Assert.Null(response.Thumbnail);
|
||||
Assert.Null(response.Types);
|
||||
Assert.False(response.IsFront);
|
||||
Assert.False(response.IsBack);
|
||||
Assert.Null(response.Comment);
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.UnitTests.Common.TestHelpers;
|
||||
|
||||
/// <summary>
|
||||
/// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class StubHttpMessageHandler : HttpMessageHandler
|
||||
{
|
||||
private readonly Func<HttpRequestMessage, int, HttpResponseMessage> _responseFactory;
|
||||
private int _callCount;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the requests that were sent through the handler.
|
||||
/// </summary>
|
||||
public List<HttpRequestMessage> Requests { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of requests that were sent through the handler.
|
||||
/// </summary>
|
||||
public int CallCount => _callCount;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StubHttpMessageHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="responseFactory">The factory that produces the response of a request, given the request and its one based call index.</param>
|
||||
public StubHttpMessageHandler(Func<HttpRequestMessage, int, HttpResponseMessage> responseFactory)
|
||||
{
|
||||
_responseFactory = responseFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends the provided request, producing its response through the configured factory.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to send.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The response produced for the request.</returns>
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
int callIndex = Interlocked.Increment(ref _callCount);
|
||||
Requests.Add(request);
|
||||
try
|
||||
{
|
||||
return Task.FromResult(_responseFactory(request, callIndex));
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// A response factory may throw to simulate a transport failure, which is surfaced as a faulted task.
|
||||
return Task.FromException<HttpResponseMessage>(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user