Adds artwork provider system and Calibre plugin

This commit is contained in:
BinaryAlley committed 2026-08-24 14:18:14 -07:00
1 parent c82fadc7a2
commit 6693ff3f60
124 files changed
+9715 -74

No files matched your search

@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
/// <summary>
/// Fixture class for the <see cref="LibraryArtworkProviderConfigurationEntity"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryArtworkProviderConfigurationEntityFixture
{
/// <summary>
/// Creates a random valid <see cref="LibraryArtworkProviderConfigurationEntity"/> for the provided media library, plugin and rank.
/// </summary>
/// <param name="libraryId">The Id of the media library the configuration belongs to.</param>
/// <param name="pluginId">The Id of the plugin providing the artwork.</param>
/// <param name="rank">The rank of the artwork provider, determining the order in which providers are tried.</param>
/// <param name="isEnabled">Whether the artwork provider is enabled or not.</param>
/// <returns>The created <see cref="LibraryArtworkProviderConfigurationEntity"/>.</returns>
public LibraryArtworkProviderConfigurationEntity Create(
Guid libraryId,
Guid pluginId,
int rank,
bool isEnabled = true)
{
return new Faker<LibraryArtworkProviderConfigurationEntity>()
.RuleFor(configuration => configuration.Id, faker => faker.Random.Guid())
.RuleFor(configuration => configuration.LibraryId, libraryId)
.RuleFor(configuration => configuration.PluginId, pluginId)
.RuleFor(configuration => configuration.IsEnabled, isEnabled)
.RuleFor(configuration => configuration.Rank, rank)
.RuleFor(configuration => configuration.CreatedOnUtc, faker => faker.Date.Past())
.RuleFor(configuration => configuration.CreatedBy, faker => faker.Random.Guid())
.RuleFor(configuration => configuration.UpdatedOnUtc, faker => faker.Date.Recent())
.RuleFor(configuration => configuration.UpdatedBy, faker => faker.Random.Guid())
.Generate();
}
/// <summary>
/// Creates a list of <see cref="LibraryArtworkProviderConfigurationEntity"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <param name="libraryId">The Id of the media library the configurations belong to.</param>
/// <param name="pluginId">The Id of the plugin providing the artwork.</param>
/// <param name="rank">The rank of the artwork providers.</param>
/// <returns>List of configured <see cref="LibraryArtworkProviderConfigurationEntity"/> instances.</returns>
public List<LibraryArtworkProviderConfigurationEntity> CreateMany(int count, Guid libraryId, Guid pluginId, int rank)
{
return [.. Enumerable.Range(0, count).Select(_ => Create(libraryId, pluginId, rank))];
}
}
@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
/// <summary>
/// Fixture class for the <see cref="ReorderLibraryArtworkProvidersCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersCommandFixture
{
/// <summary>
/// Creates a random valid command to reorder the artwork providers of a media library.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose artwork providers are reordered.</param>
/// <param name="pluginIds">Optional. The plugin Ids in the new order.</param>
/// <returns>The created command.</returns>
public ReorderLibraryArtworkProvidersCommand Create(
Guid? libraryId = null,
IReadOnlyList<Guid>? pluginIds = null)
{
return new Faker<ReorderLibraryArtworkProvidersCommand>()
.CustomInstantiator(f => new ReorderLibraryArtworkProvidersCommand(
default,
default!))
.RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid())
.RuleFor(x => x.PluginIds, f => pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()])
.Generate();
}
/// <summary>
/// Creates a list of <see cref="ReorderLibraryArtworkProvidersCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<ReorderLibraryArtworkProvidersCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
/// <summary>
/// Fixture class for the <see cref="SetLibraryArtworkProviderEnabledCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledCommandFixture
{
/// <summary>
/// Creates a random valid command to enable or disable an artwork provider for a media library.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose artwork provider is enabled or disabled.</param>
/// <param name="pluginId">Optional. The Id of the plugin providing the artwork.</param>
/// <param name="isEnabled">Whether the artwork provider should be enabled for the media library.</param>
/// <returns>The created command.</returns>
public SetLibraryArtworkProviderEnabledCommand Create(
Guid? libraryId = null,
Guid? pluginId = null,
bool isEnabled = true)
{
return new Faker<SetLibraryArtworkProviderEnabledCommand>()
.CustomInstantiator(f => new SetLibraryArtworkProviderEnabledCommand(
default,
default,
true))
.RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid())
.RuleFor(x => x.PluginId, pluginId ?? Guid.NewGuid())
.RuleFor(x => x.IsEnabled, isEnabled)
.Generate();
}
/// <summary>
/// Creates a list of <see cref="SetLibraryArtworkProviderEnabledCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<SetLibraryArtworkProviderEnabledCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryArtworkProviders;
/// <summary>
/// Fixture class for the <see cref="GetLibraryArtworkProvidersQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryArtworkProvidersQueryFixture
{
/// <summary>
/// Creates a random valid query to get the artwork providers of a media library.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose artwork providers are retrieved.</param>
/// <returns>The created query.</returns>
public GetLibraryArtworkProvidersQuery Create(
Guid? libraryId = null)
{
return new Faker<GetLibraryArtworkProvidersQuery>()
.CustomInstantiator(f => new GetLibraryArtworkProvidersQuery(
libraryId ?? Guid.NewGuid()))
.Generate();
}
/// <summary>
/// Creates a list of <see cref="GetLibraryArtworkProvidersQuery"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryArtworkProvidersQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.DTO.Common;
/// <summary>
/// Fixture class for the <see cref="ArtworkDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtworkDtoFixture
{
/// <summary>
/// Creates an <see cref="ArtworkDto"/>.
/// </summary>
/// <param name="localPath">Optional. The local file system path of the artwork.</param>
/// <param name="remoteUrl">Optional. The remote URL of the artwork.</param>
/// <returns>The created <see cref="ArtworkDto"/>.</returns>
public ArtworkDto Create(
string? localPath = null,
string? remoteUrl = null)
{
return new ArtworkDto(localPath, remoteUrl);
}
/// <summary>
/// Creates a list of <see cref="ArtworkDto"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<ArtworkDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
/// <summary>
/// Fixture class for the <see cref="GetLibraryArtworkProvidersRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryArtworkProvidersRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="GetLibraryArtworkProvidersRequest"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose artwork providers are retrieved.</param>
/// <returns>The created <see cref="GetLibraryArtworkProvidersRequest"/>.</returns>
public GetLibraryArtworkProvidersRequest Create(
Guid? libraryId = null)
{
return new GetLibraryArtworkProvidersRequest(
libraryId ?? _faker.Random.Guid()
);
}
/// <summary>
/// Creates a list of <see cref="GetLibraryArtworkProvidersRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryArtworkProvidersRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,45 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
/// <summary>
/// Fixture class for the <see cref="ReorderLibraryArtworkProvidersRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="ReorderLibraryArtworkProvidersRequest"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose artwork providers are reordered.</param>
/// <param name="pluginIds">Optional. The plugin Ids in the new order.</param>
/// <returns>The created <see cref="ReorderLibraryArtworkProvidersRequest"/>.</returns>
public ReorderLibraryArtworkProvidersRequest Create(
Guid? libraryId = null,
IReadOnlyList<Guid>? pluginIds = null)
{
return new ReorderLibraryArtworkProvidersRequest(
libraryId ?? _faker.Random.Guid(),
pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()]
);
}
/// <summary>
/// Creates a list of <see cref="ReorderLibraryArtworkProvidersRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<ReorderLibraryArtworkProvidersRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
/// <summary>
/// Fixture class for the <see cref="SetLibraryArtworkProviderEnabledRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="SetLibraryArtworkProviderEnabledRequest"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose artwork provider is enabled or disabled.</param>
/// <param name="pluginId">Optional. The Id of the plugin providing the artwork.</param>
/// <param name="isEnabled">Optional. Whether the artwork provider should be enabled.</param>
/// <returns>The created <see cref="SetLibraryArtworkProviderEnabledRequest"/>.</returns>
public SetLibraryArtworkProviderEnabledRequest Create(
Guid? libraryId = null,
Guid? pluginId = null,
bool? isEnabled = null)
{
return new SetLibraryArtworkProviderEnabledRequest(
libraryId ?? _faker.Random.Guid(),
pluginId ?? _faker.Random.Guid(),
isEnabled ?? _faker.Random.Bool()
);
}
/// <summary>
/// Creates a list of <see cref="SetLibraryArtworkProviderEnabledRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<SetLibraryArtworkProviderEnabledRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Responses.Plugins;
/// <summary>
/// Fixture class for the <see cref="LibraryArtworkProviderResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryArtworkProviderResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="LibraryArtworkProviderResponse"/>.
/// </summary>
/// <param name="pluginId">Optional. The Id of the plugin providing the artwork.</param>
/// <param name="name">Optional. The display name of the artwork provider.</param>
/// <param name="isEnabled">Optional. Whether the artwork provider is enabled for the media library.</param>
/// <param name="rank">Optional. The rank of the artwork provider.</param>
/// <returns>The created <see cref="LibraryArtworkProviderResponse"/>.</returns>
public LibraryArtworkProviderResponse Create(
Guid? pluginId = null,
string? name = null,
bool? isEnabled = null,
int? rank = null)
{
return new LibraryArtworkProviderResponse(
pluginId ?? Guid.NewGuid(),
name ?? _faker.Company.CompanyName(),
isEnabled ?? _faker.Random.Bool(),
rank ?? _faker.Random.Int(1, 100));
}
/// <summary>
/// Creates a list of <see cref="LibraryArtworkProviderResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<LibraryArtworkProviderResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Setup;
/// <summary>
/// <see cref="HttpMessageHandler"/> test double that returns the configured response for every request, without performing any network I/O.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class StubHttpMessageHandler : HttpMessageHandler
{
private HttpStatusCode _statusCode;
private byte[] _responseBody;
/// <summary>
/// Initializes a new instance of the <see cref="StubHttpMessageHandler"/> class.
/// </summary>
/// <param name="statusCode">The initial status code of the response to return.</param>
/// <param name="responseBody">The initial body of the response to return.</param>
public StubHttpMessageHandler(HttpStatusCode statusCode = HttpStatusCode.OK, byte[]? responseBody = null)
{
_statusCode = statusCode;
_responseBody = responseBody ?? [];
}
/// <summary>
/// Configures the response to return for every subsequent request.
/// </summary>
/// <param name="statusCode">The status code of the response to return.</param>
/// <param name="responseBody">The body of the response to return.</param>
public void SetResponse(HttpStatusCode statusCode, byte[] responseBody)
{
_statusCode = statusCode;
_responseBody = responseBody;
}
/// <summary>
/// Returns a response with the configured status code and body.
/// </summary>
/// <param name="request">The request, which is ignored.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the operation.</param>
/// <returns>The configured response.</returns>
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromResult(new HttpResponseMessage(_statusCode)
{
Content = new ByteArrayContent(_responseBody)
});
}
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf;
/// <summary>
/// Fixture class for the <see cref="OpfContributorDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class OpfContributorDtoFixture
{
/// <summary>
/// Creates an <see cref="OpfContributorDto"/>.
/// </summary>
/// <param name="name">The name of the contributor.</param>
/// <param name="role">The role code of the contributor, for example <c>bkp</c> for the book producer.</param>
/// <returns>The created <see cref="OpfContributorDto"/>.</returns>
public OpfContributorDto Create(
string name = "Test Contributor",
string? role = null)
{
return new OpfContributorDto(name, role);
}
/// <summary>
/// Creates a list of <see cref="OpfContributorDto"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<OpfContributorDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf;
/// <summary>
/// Fixture class for the <see cref="OpfCreatorDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class OpfCreatorDtoFixture
{
/// <summary>
/// Creates an <see cref="OpfCreatorDto"/>.
/// </summary>
/// <param name="name">The name of the creator.</param>
/// <param name="role">The role code of the creator, for example <c>aut</c> for author.</param>
/// <returns>The created <see cref="OpfCreatorDto"/>.</returns>
public OpfCreatorDto Create(
string name = "Test Creator",
string? role = null)
{
return new OpfCreatorDto(name, role);
}
/// <summary>
/// Creates a list of <see cref="OpfCreatorDto"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<OpfCreatorDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,81 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf;
/// <summary>
/// Fixture class for the <see cref="OpfDocumentDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class OpfDocumentDtoFixture
{
/// <summary>
/// Creates an <see cref="OpfDocumentDto"/>.
/// </summary>
/// <param name="title">Optional. The title of the book.</param>
/// <param name="description">Optional. The description of the book, in HTML format.</param>
/// <param name="publisher">Optional. The publisher of the book.</param>
/// <param name="publishDate">Optional. The publication date of the book.</param>
/// <param name="languageCode">Optional. The language code of the book.</param>
/// <param name="series">Optional. The name of the series the book belongs to.</param>
/// <param name="seriesIndex">Optional. The index of the book within its series.</param>
/// <param name="rating">Optional. The personal rating of the book, on a scale of 0 to 10.</param>
/// <param name="coverHref">Optional. The href of the cover image, relative to the directory of the book.</param>
/// <param name="subjects">Optional. The subjects of the book, used as tags.</param>
/// <param name="creators">Optional. The creators of the book.</param>
/// <param name="contributors">Optional. The contributors of the book.</param>
/// <param name="identifiers">Optional. The identifiers of the book, with their schemes.</param>
/// <returns>The created <see cref="OpfDocumentDto"/>.</returns>
public OpfDocumentDto Create(
string? title = null,
string? description = null,
string? publisher = null,
DateTimeOffset? publishDate = null,
string? languageCode = null,
string? series = null,
double? seriesIndex = null,
int? rating = null,
string? coverHref = null,
IEnumerable<string>? subjects = null,
IEnumerable<OpfCreatorDto>? creators = null,
IEnumerable<OpfContributorDto>? contributors = null,
IEnumerable<OpfIdentifierDto>? identifiers = null)
{
OpfDocumentDto document = new()
{
Title = title,
Description = description,
Publisher = publisher,
PublishDate = publishDate,
LanguageCode = languageCode,
Series = series,
SeriesIndex = seriesIndex,
Rating = rating,
CoverHref = coverHref
};
if (subjects is not null)
document.Subjects.AddRange(subjects);
if (creators is not null)
document.Creators.AddRange(creators);
if (contributors is not null)
document.Contributors.AddRange(contributors);
if (identifiers is not null)
document.Identifiers.AddRange(identifiers);
return document;
}
/// <summary>
/// Creates a list of <see cref="OpfDocumentDto"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<OpfDocumentDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf;
/// <summary>
/// Fixture class for the <see cref="OpfIdentifierDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class OpfIdentifierDtoFixture
{
/// <summary>
/// Creates an <see cref="OpfIdentifierDto"/>.
/// </summary>
/// <param name="scheme">The scheme of the identifier, for example <c>ISBN</c> or <c>GOODREADS</c>.</param>
/// <param name="value">The value of the identifier.</param>
/// <returns>The created <see cref="OpfIdentifierDto"/>.</returns>
public OpfIdentifierDto Create(
string scheme = "ISBN",
string value = "9780306406157")
{
return new OpfIdentifierDto(scheme, value);
}
/// <summary>
/// Creates a list of <see cref="OpfIdentifierDto"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<OpfIdentifierDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Plugins.Calibre.Fixtures.Core.Metadata;
/// <summary>
/// Concrete <see cref="MetadataLookupDto"/> used to represent a lookup that is not a book lookup.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed record TestMetadataLookup(Guid LibraryId, string Path) : MetadataLookupDto;
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Plugins.Calibre.Fixtures.Core.Metadata;
/// <summary>
/// Fixture class for the <see cref="TestMetadataLookup"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class TestMetadataLookupFixture
{
/// <summary>
/// Creates a <see cref="TestMetadataLookup"/> that is not a book lookup.
/// </summary>
/// <param name="libraryId">The Id of the media library, or <see langword="null"/> to generate a random one.</param>
/// <param name="path">The file system path of the media item.</param>
/// <returns>The created <see cref="TestMetadataLookup"/>.</returns>
public TestMetadataLookup Create(
Guid? libraryId = null,
string? path = null)
{
return new TestMetadataLookup(libraryId ?? Guid.NewGuid(), path ?? "/some/path");
}
/// <summary>
/// Creates a list of <see cref="TestMetadataLookup"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<TestMetadataLookup> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
<IsPackable>false</IsPackable>
<IsTestProject>false</IsTestProject>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoFixture" />
<PackageReference Include="AutoFixture.AutoNSubstitute" />
<PackageReference Include="AutoFixture.Xunit2" />
<PackageReference Include="Bogus" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.Calibre\Lumina.Plugins.Calibre.csproj" />
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,20 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lumina.Plugins.Calibre.Fixtures")]
[assembly: AssemblyProduct("Lumina.Plugins.Calibre.Fixtures")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31")]
[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
@@ -0,0 +1,153 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Responses.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryArtworkProviders;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryArtworkProviders;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryArtworkProvidersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task GetLibraryArtworkProviders_WhenProvidersAreConfigured_ShouldReturnThemOrderedByRank()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginIdA = Guid.NewGuid();
Guid pluginIdB = Guid.NewGuid();
await SeedConfigurationAsync(libraryId, pluginIdA, pluginIdB);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artwork-providers");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<LibraryArtworkProviderResponse>? providers = await response.Content.ReadFromJsonAsync<List<LibraryArtworkProviderResponse>>(_jsonOptions);
Assert.NotNull(providers);
Assert.Equal(2, providers!.Count);
Assert.Equal(pluginIdA, providers[0].PluginId);
Assert.Equal(1, providers[0].Rank);
Assert.Equal(pluginIdB, providers[1].PluginId);
Assert.Equal(2, providers[1].Rank);
}
[Fact]
public async Task GetLibraryArtworkProviders_WhenNoProvidersAreConfigured_ShouldReturnEmptyList()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artwork-providers");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<LibraryArtworkProviderResponse>? providers = await response.Content.ReadFromJsonAsync<List<LibraryArtworkProviderResponse>>(_jsonOptions);
Assert.NotNull(providers);
Assert.Empty(providers!);
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds two <see cref="LibraryArtworkProviderConfigurationEntity"/> instances in the database.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <param name="pluginIdA">The Id of the first plugin.</param>
/// <param name="pluginIdB">The Id of the second plugin.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginIdA, Guid pluginIdB)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdA, rank: 1, isEnabled: true));
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdB, rank: 2, isEnabled: false));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,140 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
/// <summary>
/// Contains integration tests for the <see cref="ReorderLibraryArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ReorderLibraryArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task ReorderLibraryArtworkProviders_WhenCalledWithValidData_ShouldReorderTheProviders()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginIdA = Guid.NewGuid();
Guid pluginIdB = Guid.NewGuid();
await SeedConfigurationAsync(libraryId, pluginIdA, rank: 1);
await SeedConfigurationAsync(libraryId, pluginIdB, rank: 2);
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(
libraryId: libraryId,
pluginIds: [pluginIdB, pluginIdA]
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<LibraryArtworkProviderConfigurationEntity> configurations = await dbContext.LibraryArtworkProviderConfigurations
.Where(config => config.LibraryId == libraryId)
.OrderBy(config => config.Rank)
.ToListAsync();
Assert.Equal(2, configurations.Count);
Assert.Equal(pluginIdB, configurations[0].PluginId);
Assert.Equal(1, configurations[0].Rank);
Assert.Equal(pluginIdA, configurations[1].PluginId);
Assert.Equal(2, configurations[1].Rank);
}
/// <summary>
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> in the database.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <param name="pluginId">The Id of the plugin.</param>
/// <param name="rank">The rank of the provider.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,156 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
/// <summary>
/// Contains integration tests for the <see cref="SetLibraryArtworkProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryArtworkProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task SetLibraryArtworkProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginId = Guid.NewGuid();
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations
.FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
Assert.NotNull(configuration);
Assert.True(configuration!.IsEnabled);
Assert.Equal(1, configuration.Rank);
}
[Fact]
public async Task SetLibraryArtworkProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginId = Guid.NewGuid();
await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false, rank: 1);
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations
.FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
Assert.NotNull(configuration);
Assert.True(configuration!.IsEnabled);
}
/// <summary>
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> in the database.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <param name="pluginId">The Id of the plugin.</param>
/// <param name="isEnabled">Whether the provider is enabled.</param>
/// <param name="rank">The rank of the provider.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,119 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryArtworkProviders;
/// <summary>
/// Contains security tests for the <c>/libraries/{libraryId}/artwork-providers</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryArtworkProvidersEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryArtworkProvidersEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetLibraryArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artwork-providers");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
public async Task GetLibraryArtworkProviders_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId)
{
// Arrange
// authenticate with an admin user and seed a library with an artwork provider configuration, so a valid id would reach the handler
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = await SeedLibraryAsync(userId);
await SeedConfigurationAsync(libraryId);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artwork-providers");
// Assert
// note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler
// note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> for the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1));
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,133 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
/// <summary>
/// Contains security tests for the <c>/libraries/{libraryId}/artwork-providers/reorder</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ReorderLibraryArtworkProvidersEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ReorderLibraryArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(
libraryId: Guid.NewGuid(),
pluginIds: [Guid.NewGuid()]
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Plugins--")] // destructive injection
public async Task ReorderLibraryArtworkProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId)
{
// Arrange
// authenticate with an admin user and seed a library with artwork provider configurations, so valid ids would reach the handler
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = await SeedLibraryAsync(userId);
await SeedConfigurationAsync(libraryId, rank: 1);
await SeedConfigurationAsync(libraryId, rank: 2);
// Act
// the malicious value cannot bind to the Guid-typed PluginIds request property, so the body fails JSON deserialization
// before it ever reaches the endpoint handler
HttpResponseMessage response = await client.PutAsJsonAsync(
$"/api/v1/libraries/{libraryId}/artwork-providers/reorder",
new { libraryId, pluginIds = new[] { maliciousPluginId } });
// Assert
// note: observed status is 500 because the JSON body cannot be deserialized into the Guid-typed PluginIds property, and
// FastEndpoints, combined with DontCatchExceptions(), turns the resulting JsonException into a 500 response instead of 400
// (pre-existing production bug, not fixed here)
// note: that 500 body leaks the JsonException details, so no DoesNotContain("Exception") is asserted here
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> for the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <param name="rank">The rank of the provider.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId, int rank)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank));
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,126 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
/// <summary>
/// Contains security tests for the <c>/libraries/{libraryId}/artwork-providers/{pluginId}/enabled</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryArtworkProviderEnabledEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task SetLibraryArtworkProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
string pluginId = Guid.NewGuid().ToString();
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create();
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
public async Task SetLibraryArtworkProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId)
{
// Arrange
// authenticate with an admin user and seed a library with an artwork provider configuration, so valid ids would reach the handler
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = await SeedLibraryAsync(userId);
await SeedConfigurationAsync(libraryId);
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), isEnabled: true);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/artwork-providers/{Guid.NewGuid()}/enabled", request);
// Assert
// note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler
// note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> for the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false));
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,236 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Infrastructure.Common.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.MediaLibrary.Artwork;
/// <summary>
/// Contains security tests for the <see cref="IBookArtworkService"/> contract, exercised through the real <see cref="BookArtworkService"/> implementation resolved from the dependency injection container.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookArtworkServiceSecurityTests
{
private readonly IFileTypeService _mockFileTypeService;
private readonly IFileProviderService _mockFileProviderService;
private readonly IDirectoryProviderService _mockDirectoryProviderService;
private readonly IBookArtworkService _sut;
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookArtworkServiceSecurityTests"/> class.
/// </summary>
public BookArtworkServiceSecurityTests()
{
IEnvironmentContext mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
_mockFileTypeService = Substitute.For<IFileTypeService>();
_mockFileProviderService = Substitute.For<IFileProviderService>();
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService);
mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService);
mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books");
IConfiguration mockConfiguration = Substitute.For<IConfiguration>();
mockConfiguration.GetSection(Arg.Any<string>()).Returns(Substitute.For<IConfigurationSection>());
ServiceCollection services = new();
services.AddInfrastructureLayerServices(mockConfiguration);
services.AddScoped(_ => mockEnvironmentContext);
// the real path service is used, so that the sanitization of hostile segment names is exercised
services.AddScoped(_ => CreateRealPathService());
services.AddSingleton(Options.Create(mediaSettings));
ServiceProvider serviceProvider = services.BuildServiceProvider();
using IServiceScope scope = serviceProvider.CreateScope();
_sut = scope.ServiceProvider.GetRequiredService<IBookArtworkService>();
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkIsAReparsePoint_ShouldRejectIt()
{
// Arrange
string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-security-junction-target-{Guid.NewGuid():N}");
Directory.CreateDirectory(targetDirectory);
string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-security-junction-link-{Guid.NewGuid():N}");
if (!TryCreateJunction(linkPath, targetDirectory))
{
Directory.Delete(targetDirectory, true);
return; // the environment does not support creating reparse points
}
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
// Windows removes a junction with Directory.Delete, while Unix-like platforms unlink the symbolic link with File.Delete
if (OperatingSystem.IsWindows())
Directory.Delete(linkPath, true);
else
File.Delete(linkPath);
Directory.Delete(targetDirectory, true);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenNameSegmentsContainPathTraversal_ShouldSanitizeThemIntoLiteralSegments()
{
// Arrange
string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-security-source-{Guid.NewGuid():N}.jpg");
File.WriteAllBytes(sourcePath, new byte[1024]);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
.Returns(Result.From(true));
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([]));
string capturedDestinationPath = string.Empty;
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Do<FileSystemPathId>(destination => capturedDestinationPath = destination.Path), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpg"))));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpeg"))));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(
Guid.NewGuid(),
Guid.NewGuid(),
libraryName: "..\\..\\Library",
authorName: "..\\evil",
bookTitle: "..\\..\\cover",
_artworkDtoFixture.Create(localPath: sourcePath),
CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.False(string.IsNullOrEmpty(capturedDestinationPath));
string[] segments = capturedDestinationPath.Split(['\\', '/'], StringSplitOptions.RemoveEmptyEntries);
Assert.DoesNotContain(segments, segment => segment == "..");
Assert.DoesNotContain(segments, segment => segment == ".");
Assert.DoesNotContain(result.Value.Split(['\\', '/'], StringSplitOptions.RemoveEmptyEntries), segment => segment == "..");
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLibraryNameIsADotDotSegment_ShouldReturnInvalidPath()
{
// Arrange
string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-security-source-{Guid.NewGuid():N}.jpg");
File.WriteAllBytes(sourcePath, new byte[1024]);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), libraryName: "..", authorName: "Author", bookTitle: "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
File.Delete(sourcePath);
}
}
/// <summary>
/// Creates a real <see cref="PathService"/> backed by a stubbed path strategy, so that the sanitization of hostile segment names is exercised.
/// </summary>
/// <returns>The created real path service.</returns>
private static IPathService CreateRealPathService()
{
IPathStrategy mockPathStrategy = Substitute.For<IPathStrategy>();
mockPathStrategy.PathSeparator.Returns(Path.DirectorySeparatorChar);
mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(Path.GetInvalidFileNameChars());
mockPathStrategy.CombinePath(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
.Returns(callInfo => Result.From(FileSystemPathId.Create(Path.Combine(callInfo.Arg<FileSystemPathId>().Path, callInfo.Arg<string>())).Value));
mockPathStrategy.IsValidPath(Arg.Any<FileSystemPathId>()).Returns(true);
IPlatformContext mockPlatformContext = Substitute.For<IPlatformContext>();
mockPlatformContext.PathStrategy.Returns(mockPathStrategy);
IPlatformContextManager mockPlatformContextManager = Substitute.For<IPlatformContextManager>();
mockPlatformContextManager.GetCurrentContext().Returns(mockPlatformContext);
return new PathService(mockPlatformContextManager);
}
/// <summary>
/// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms.
/// </summary>
/// <param name="linkPath">The file system path of the link to create.</param>
/// <param name="targetDirectory">The file system path of the directory the link points to.</param>
/// <returns><see langword="true"/> when the link was created, <see langword="false"/> otherwise.</returns>
private static bool TryCreateJunction(string linkPath, string targetDirectory)
{
try
{
System.Diagnostics.ProcessStartInfo startInfo = OperatingSystem.IsWindows()
? new()
{
FileName = "cmd.exe",
Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"",
CreateNoWindow = true,
UseShellExecute = false
}
: new()
{
FileName = "ln",
CreateNoWindow = true,
UseShellExecute = false
};
if (!OperatingSystem.IsWindows())
{
startInfo.ArgumentList.Add("-s");
startInfo.ArgumentList.Add(targetDirectory);
startInfo.ArgumentList.Add(linkPath);
}
System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo)!;
process.WaitForExit(5000);
return process.ExitCode == 0;
}
catch (Exception)
{
return false;
}
}
}
@@ -0,0 +1,110 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Plugins.Calibre.Core;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Plugins.Calibre;
/// <summary>
/// Contains security tests for the <see cref="CalibreArtworkProvider"/> class, exercised through the public artwork provider surface.
/// </summary>
[ExcludeFromCodeCoverage]
public class CalibreArtworkProviderSecurityTests
{
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
[Fact]
public async Task GetArtworkAsync_WhenCoverHrefIsABareFileName_ShouldReturnTheCoverInsideTheBookDirectory()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = WriteBookWithCoverReference(bookDirectory, "cover.jpg");
File.WriteAllText(Path.Combine(bookDirectory, "cover.jpg"), "image-bytes");
IArtworkProvider provider = CreateArtworkProvider();
// Act
ArtworkDto? result = await provider.GetArtworkAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Theory]
[InlineData("../cover.jpg")] // parent directory escape
[InlineData("../../cover.jpg")] // multiple parent directory escape
[InlineData("sub/cover.jpg")] // forward slash path traversal
[InlineData("sub\\cover.jpg")] // backslash path traversal
[InlineData(@"C:\Windows\System32\drivers\etc\hosts")] // absolute Windows path
[InlineData("/etc/passwd")] // absolute Unix path
[InlineData("http://evil.example/cover.jpg")] // remote URL
[InlineData("file:///etc/passwd")] // file URI
public async Task GetArtworkAsync_WhenCoverHrefEscapesTheBookDirectory_ShouldReturnNull(string coverHref)
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = WriteBookWithCoverReference(bookDirectory, coverHref);
IArtworkProvider provider = CreateArtworkProvider();
// Act
ArtworkDto? result = await provider.GetArtworkAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
/// <summary>
/// Creates the Calibre artwork provider by registering the plugin services and resolving the keyed artwork provider.
/// </summary>
/// <returns>The created Calibre artwork provider.</returns>
private static IArtworkProvider CreateArtworkProvider()
{
ServiceCollection services = new();
new CalibrePlugin().RegisterServices(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
return serviceProvider.GetKeyedService<IArtworkProvider>(CalibrePlugin.s_pluginId)!;
}
/// <summary>
/// Writes an OPF file that references the given cover into the book directory, and returns the path of the book.
/// </summary>
/// <param name="bookDirectory">The file system path of the directory the OPF file is written into.</param>
/// <param name="coverHref">The href of the cover the OPF file references.</param>
/// <returns>The file system path of the book.</returns>
private static string WriteBookWithCoverReference(string bookDirectory, string coverHref)
{
string opf = $$"""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>Test</dc:title></metadata><guide><reference type="cover" href="{{coverHref}}"/></guide></package>""";
string bookPath = Path.Combine(bookDirectory, "book.epub");
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opf);
return bookPath;
}
/// <summary>
/// Creates a unique temporary directory for the book.
/// </summary>
/// <returns>The file system path of the created temporary directory.</returns>
private static string CreateTempDirectory()
{
string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-security-artwork-{Guid.NewGuid():N}");
Directory.CreateDirectory(directoryPath);
return directoryPath;
}
}
@@ -0,0 +1,155 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Plugins.Calibre.Core;
using Lumina.Plugins.Calibre.Core.Opf;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Plugins.Calibre.Opf;
/// <summary>
/// Contains security tests for the <see cref="OpfReader"/> class, exercised through the public metadata provider surface.
/// </summary>
[ExcludeFromCodeCoverage]
public class OpfReaderSecurityTests
{
private const int MAX_OPF_FILE_SIZE_BYTES = 5 * 1024 * 1024;
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
[Fact]
public async Task GetMetadataAsync_WhenOpfContainsADoctypeWithAnExternalEntity_ShouldNotExpandTheEntity()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
// the OPF is untrusted XML, so a DTD with an external entity must be rejected instead of being read and expanded
string opfContent = """<?xml version="1.0" encoding="utf-8"?><!DOCTYPE package [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>&xxe;</dc:title></metadata></package>""";
string bookPath = WriteBookWithOpf(bookDirectory, opfContent);
IMetadataProvider provider = CreateMetadataProvider();
// Act
MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Null(((BookMetadataDto)result!).Title);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetMetadataAsync_WhenOpfContainsBillionLaughsStyleEntityExpansion_ShouldNotExpandTheEntities()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string opfContent = """<?xml version="1.0" encoding="utf-8"?><!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"><!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">]><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>&lol3;</dc:title></metadata></package>""";
string bookPath = WriteBookWithOpf(bookDirectory, opfContent);
IMetadataProvider provider = CreateMetadataProvider();
// Act
MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Null(((BookMetadataDto)result!).Title);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetMetadataAsync_WhenOpfIsOversized_ShouldNotParseIt()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string oversizedContent = $"""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>{new string('a', MAX_OPF_FILE_SIZE_BYTES + 100)}</dc:title></metadata></package>""";
string bookPath = WriteBookWithOpf(bookDirectory, oversizedContent);
IMetadataProvider provider = CreateMetadataProvider();
// Act
MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Null(((BookMetadataDto)result!).Title);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetMetadataAsync_WhenOpfIsMalformedXml_ShouldNotExposeAnException()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = WriteBookWithOpf(bookDirectory, """<package xmlns="http://www.idpf.org/2007/opf"><metadata><dc:title>Unclosed""");
IMetadataProvider provider = CreateMetadataProvider();
// Act
MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None);
// Assert
// a malformed OPF must be swallowed and must not leak an exception to the caller
Assert.NotNull(result);
Assert.Null(((BookMetadataDto)result!).Title);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
/// <summary>
/// Creates the Calibre metadata provider by registering the plugin services and resolving the keyed metadata provider.
/// </summary>
/// <returns>The created Calibre metadata provider.</returns>
private static IMetadataProvider CreateMetadataProvider()
{
ServiceCollection services = new();
new CalibrePlugin().RegisterServices(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
return serviceProvider.GetKeyedService<IMetadataProvider>(CalibrePlugin.s_pluginId)!;
}
/// <summary>
/// Writes an OPF file with the given content into the book directory, and returns the path of the book.
/// </summary>
/// <param name="bookDirectory">The file system path of the directory the OPF file is written into.</param>
/// <param name="opfContent">The content of the OPF file to write.</param>
/// <returns>The file system path of the book.</returns>
private static string WriteBookWithOpf(string bookDirectory, string opfContent)
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opfContent);
return bookPath;
}
/// <summary>
/// Creates a unique temporary directory for the book.
/// </summary>
/// <returns>The file system path of the created temporary directory.</returns>
private static string CreateTempDirectory()
{
string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-security-opf-{Guid.NewGuid():N}");
Directory.CreateDirectory(directoryPath);
return directoryPath;
}
}
@@ -0,0 +1,183 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryArtworkProvidersCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtworkProviderConfigurationRepository _mockConfigurationRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<ReorderLibraryArtworkProvidersCommand> _mockValidator;
private readonly ReorderLibraryArtworkProvidersCommandHandler _sut;
private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationEntityFixture = new();
private readonly ReorderLibraryArtworkProvidersCommandFixture _reorderLibraryArtworkProvidersCommandFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersCommandHandlerTests"/> class.
/// </summary>
public ReorderLibraryArtworkProvidersCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<ReorderLibraryArtworkProvidersCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated and the library ownership policy allows access
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<ReorderLibraryArtworkProvidersCommand>())
.Returns([]);
_sut = new ReorderLibraryArtworkProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldAssignRanksInTheProvidedOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryArtworkProviderConfigurationEntity firstProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2);
LibraryArtworkProviderConfigurationEntity secondProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1);
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryArtworkProviderConfigurationEntity> { firstProvider, secondProvider });
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => configuration.PluginId == secondProvider.PluginId && configuration.Rank == 1),
Arg.Any<CancellationToken>());
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => configuration.PluginId == firstProvider.PluginId && configuration.Rank == 2),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAProvidedPluginIsNotConfigured_ShouldSkipIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryArtworkProviderConfigurationEntity configuration = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1);
Guid unknownPluginId = Guid.NewGuid();
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryArtworkProviderConfigurationEntity> { configuration });
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [unknownPluginId, configuration.PluginId]), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(candidate => candidate.PluginId == configuration.PluginId && candidate.Rank == 2),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockValidator.Validate(Arg.Any<ReorderLibraryArtworkProvidersCommand>()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginIdsListCannotBeEmpty, result.FirstError);
await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetConfigurationsFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to get configurations"));
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,104 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryArtworkProvidersCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersCommandValidatorTests
{
private readonly ReorderLibraryArtworkProvidersCommandValidator _validator = new();
private readonly ReorderLibraryArtworkProvidersCommandFixture _reorderLibraryArtworkProvidersCommandFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create();
command = command with { LibraryId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdsIsNull_ShouldHaveValidationError()
{
// Arrange
ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create();
command = command with { PluginIds = null! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull);
}
[Fact]
public void Validate_WhenPluginIdsIsEmpty_ShouldHaveValidationError()
{
// Arrange
ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create();
command = command with { PluginIds = [] };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdsAreValid_ShouldNotHaveValidationError()
{
// Arrange
ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,242 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryArtworkProviderEnabledCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtworkProviderConfigurationRepository _mockConfigurationRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<SetLibraryArtworkProviderEnabledCommand> _mockValidator;
private readonly SetLibraryArtworkProviderEnabledCommandHandler _sut;
private readonly SetLibraryArtworkProviderEnabledCommandFixture _setLibraryArtworkProviderEnabledCommandFixture = new();
private readonly Guid _userId;
/// <summary>
/// Fixture for generating <see cref="LibraryArtworkProviderConfigurationEntity"/> test data.
/// </summary>
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledCommandHandlerTests"/> class.
/// </summary>
public SetLibraryArtworkProviderEnabledCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<SetLibraryArtworkProviderEnabledCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated and the library ownership policy allows access
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<SetLibraryArtworkProviderEnabledCommand>())
.Returns([]);
_sut = new SetLibraryArtworkProviderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldCreateEnabledConfigurationWithNextRank()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any<CancellationToken>())
.Returns((LibraryArtworkProviderConfigurationEntity?)null);
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryArtworkProviderConfigurationEntity>());
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => configuration.IsEnabled && configuration.Rank == 1),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenConfigurationDoesNotExistAndOthersExist_ShouldAppendAfterTheHighestRank()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any<CancellationToken>())
.Returns((LibraryArtworkProviderConfigurationEntity?)null);
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryArtworkProviderConfigurationEntity>
{
_libraryArtworkProviderConfigurationEntityFixture.Create(
libraryId: libraryId,
pluginId: Guid.NewGuid(),
rank: 3,
isEnabled: true)
});
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: false), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => !configuration.IsEnabled && configuration.Rank == 4),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState()
{
// Arrange
LibraryArtworkProviderConfigurationEntity existingConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(
libraryId: Guid.NewGuid(),
pluginId: Guid.NewGuid(),
rank: 2,
isEnabled: false);
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(existingConfiguration.LibraryId, existingConfiguration.PluginId, Arg.Any<CancellationToken>())
.Returns(existingConfiguration);
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => configuration.IsEnabled && configuration.Rank == 2),
Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockValidator.Validate(Arg.Any<SetLibraryArtworkProviderEnabledCommand>()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError);
await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByLibraryAndPluginIdFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to get configuration"));
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpsertFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any<CancellationToken>())
.Returns((LibraryArtworkProviderConfigurationEntity?)null);
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryArtworkProviderConfigurationEntity>());
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to upsert configuration"));
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,89 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryArtworkProviderEnabledCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledCommandValidatorTests
{
private readonly SetLibraryArtworkProviderEnabledCommandValidator _validator = new();
private readonly SetLibraryArtworkProviderEnabledCommandFixture _setLibraryArtworkProviderEnabledCommandFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create();
command = command with { LibraryId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create();
command = command with { PluginId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,231 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryArtworkProviders;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryArtworkProviders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryArtworkProvidersQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryArtworkProvidersQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository;
private readonly IPluginRepository _mockPluginRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetLibraryArtworkProvidersQuery> _mockValidator;
private readonly GetLibraryArtworkProvidersQueryHandler _sut;
private readonly GetLibraryArtworkProvidersQueryFixture _getLibraryArtworkProvidersQueryFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationEntityFixture = new();
private readonly PluginEntityFixture _pluginEntityFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryArtworkProvidersQueryHandlerTests"/> class.
/// </summary>
public GetLibraryArtworkProvidersQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockArtworkProviderConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository);
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetLibraryArtworkProvidersQuery>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated and the library ownership policy allows access
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetLibraryArtworkProvidersQuery>()).Returns([]);
_sut = new GetLibraryArtworkProvidersQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenLibraryIdIsEmpty_ShouldReturnValidationError()
{
// Arrange
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetLibraryArtworkProvidersQuery>()).Returns([Errors.Plugins.LibraryIdCannotBeEmpty]);
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.LibraryIdCannotBeEmpty, result.FirstError);
await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenConfigurationsExist_ShouldReturnProvidersOrderedByRankWithPluginNames()
{
// Arrange
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
Guid firstPluginId = Guid.NewGuid();
Guid secondPluginId = Guid.NewGuid();
List<LibraryArtworkProviderConfigurationEntity> configurations =
[
_configurationEntityFixture.Create(query.LibraryId, secondPluginId, 2),
_configurationEntityFixture.Create(query.LibraryId, firstPluginId, 1)
];
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>(configurations));
List<PluginEntity> plugins =
[
_pluginEntityFixture.Create(firstPluginId),
_pluginEntityFixture.Create(secondPluginId)
];
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(plugins);
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Equal(firstPluginId, result.Value[0].PluginId);
Assert.Equal(plugins[0].Name, result.Value[0].Name);
Assert.Equal(configurations[1].Rank, result.Value[0].Rank);
Assert.Equal(secondPluginId, result.Value[1].PluginId);
Assert.Equal(plugins[1].Name, result.Value[1].Name);
}
[Fact]
public async Task HandleAsync_WhenPluginIsMissingFromDetectedPlugins_ShouldUseEmptyName()
{
// Arrange
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
Guid unknownPluginId = Guid.NewGuid();
List<LibraryArtworkProviderConfigurationEntity> configurations =
[
_configurationEntityFixture.Create(query.LibraryId, unknownPluginId, 1)
];
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>(configurations));
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<PluginEntity>>([_pluginEntityFixture.Create()]));
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
LibraryArtworkProviderResponse response = Assert.Single(result.Value);
Assert.Equal(unknownPluginId, response.PluginId);
Assert.Equal(string.Empty, response.Name);
}
[Fact]
public async Task HandleAsync_WhenNoConfigurationsExist_ShouldReturnEmptyList()
{
// Arrange
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<PluginEntity>>([]));
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task HandleAsync_WhenGetConfigurationsFails_ShouldReturnError()
{
// Arrange
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
Error error = Error.Failure(description: "Failed to get configurations");
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError()
{
// Arrange
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to get plugins"));
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == query.LibraryId), Arg.Any<CancellationToken>());
await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryArtworkProviders;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryArtworkProviders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryArtworkProvidersQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryArtworkProvidersQueryValidatorTests
{
private readonly GetLibraryArtworkProvidersQueryValidator _validator = new();
private readonly GetLibraryArtworkProvidersQueryFixture _getLibraryArtworkProvidersQueryFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
query = query with { LibraryId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,137 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.DataAccess.Core.Repositories.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="ArtworkProviderConfigurationRepository"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtworkProviderConfigurationRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly ArtworkProviderConfigurationRepository _sut;
private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ArtworkProviderConfigurationRepositoryTests"/> class.
/// </summary>
public ArtworkProviderConfigurationRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new ArtworkProviderConfigurationRepository(_mockContext);
}
[Fact]
public async Task GetByLibraryIdAsync_WhenCalled_ShouldReturnOnlyConfigurationsOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryArtworkProviderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId, Guid.NewGuid(), 1);
LibraryArtworkProviderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
_mockContext.LibraryArtworkProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<System.Collections.Generic.IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
LibraryArtworkProviderConfigurationEntity retrievedConfiguration = Assert.Single(result.Value);
Assert.Equal(configurationOfLibrary.PluginId, retrievedConfiguration.PluginId);
}
[Fact]
public async Task GetByLibraryIdAsync_WhenLibraryHasNoConfigurations_ShouldReturnEmptyList()
{
// Arrange
Guid libraryId = Guid.NewGuid();
// Act
Result<System.Collections.Generic.IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationExists_ShouldReturnIt()
{
// Arrange
LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
_mockContext.LibraryArtworkProviderConfigurations.Add(configuration);
await _mockContext.SaveChangesAsync();
// Act
Result<LibraryArtworkProviderConfigurationEntity?> result = await _sut.GetByLibraryAndPluginIdAsync(configuration.LibraryId, configuration.PluginId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(configuration.Id, result.Value!.Id);
}
[Fact]
public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationDoesNotExist_ShouldReturnNull()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
// Act
Result<LibraryArtworkProviderConfigurationEntity?> result = await _sut.GetByLibraryAndPluginIdAsync(libraryId, pluginId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task UpsertAsync_WhenConfigurationDoesNotExist_ShouldInsertIt()
{
// Arrange
LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
// Act
Result<Updated> result = await _sut.UpsertAsync(configuration, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Single(_mockContext.LibraryArtworkProviderConfigurations);
}
[Fact]
public async Task UpsertAsync_WhenConfigurationExists_ShouldUpdateIt()
{
// Arrange
LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
_mockContext.LibraryArtworkProviderConfigurations.Add(configuration);
await _mockContext.SaveChangesAsync();
LibraryArtworkProviderConfigurationEntity updatedConfiguration = _configurationFixture.Create(configuration.LibraryId, configuration.PluginId, 5);
updatedConfiguration.IsEnabled = true;
// Act
Result<Updated> result = await _sut.UpsertAsync(updatedConfiguration, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
LibraryArtworkProviderConfigurationEntity retrievedConfiguration = _mockContext.LibraryArtworkProviderConfigurations.Single();
Assert.Equal(5, retrievedConfiguration.Rank);
Assert.True(retrievedConfiguration.IsEnabled);
Assert.Equal(configuration.Id, retrievedConfiguration.Id);
}
}
@@ -0,0 +1,541 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Infrastructure.Fixtures.Common.Setup;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
/// <summary>
/// Contains unit tests for the <see cref="BookArtworkService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookArtworkServiceTests
{
private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024;
private readonly IEnvironmentContext _mockEnvironmentContext;
private readonly IFileTypeService _mockFileTypeService;
private readonly IFileProviderService _mockFileProviderService;
private readonly IDirectoryProviderService _mockDirectoryProviderService;
private readonly IPathService _mockPathService;
private readonly IHttpClientFactory _mockHttpClientFactory;
private readonly IOptions<MediaSettingsDto> _mockMediaSettingsOptions;
private readonly BookArtworkService _sut;
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
private readonly PathSegmentFixture _pathSegmentFixture = new();
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
private readonly StubHttpMessageHandler _stubHttpMessageHandler = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookArtworkServiceTests"/> class.
/// </summary>
public BookArtworkServiceTests()
{
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
_mockFileTypeService = Substitute.For<IFileTypeService>();
_mockFileProviderService = Substitute.For<IFileProviderService>();
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
_mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService);
_mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService);
_mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
_mockPathService = Substitute.For<IPathService>();
_mockPathService.PathSeparator.Returns('\\');
_mockHttpClientFactory = Substitute.For<IHttpClientFactory>();
_mockHttpClientFactory.CreateClient().Returns(new HttpClient(_stubHttpMessageHandler));
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books");
_mockMediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
_mockMediaSettingsOptions.Value.Returns(mediaSettings);
_sut = new BookArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkExists_ShouldCopyItAndReturnARelativePath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
FileSystemPathId copiedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(copiedFileId));
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpeg");
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath);
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value);
_mockFileProviderService.Received(1).CopyFile(
Arg.Is<FileSystemPathId>(pathId => pathId.Path == sourcePath),
Arg.Any<FileSystemPathId>(),
true);
_mockFileProviderService.Received(1).RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg");
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenAuthorNameIsMissing_ShouldUseUnknownForTheDirectorySegment()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName: "Unknown", bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName: " ", bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockPathService.Received(1).SanitizeSegment("Unknown");
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound()
{
// Arrange
string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg");
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkIsALink_ShouldReturnInvalidPath()
{
// Arrange
string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-junction-target-{Guid.NewGuid():N}");
Directory.CreateDirectory(targetDirectory);
string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-junction-link-{Guid.NewGuid():N}");
if (!TryCreateJunction(linkPath, targetDirectory))
{
Directory.Delete(targetDirectory, true);
return; // the environment does not support creating reparse points
}
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
// Windows removes a junction with Directory.Delete, while Unix-like platforms unlink the symbolic link with File.Delete
if (OperatingSystem.IsWindows())
Directory.Delete(linkPath, true);
else
File.Delete(linkPath);
Directory.Delete(targetDirectory, true);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkExceedsMaxSize_ShouldReturnFileTooLarge()
{
// Arrange
string sourcePath = CreateTempImageFile(smallImageBytes: (int)MAX_ARTWORK_SIZE_BYTES + 1);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkIsNotAnImage_ShouldReturnCoverFileMustBeAnImage()
{
// Arrange
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.None));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.CoverFileMustBeAnImage, result.FirstError);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound()
{
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRemoteUrlIsProvided_ShouldDownloadAndStoreTheArtwork()
{
// Arrange
byte[] imageBytes = new byte[1024];
_stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, imageBytes);
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.Received(1).CopyFile(
Arg.Is<FileSystemPathId>(pathId => pathId.Path.StartsWith(Path.GetTempPath())),
Arg.Any<FileSystemPathId>(),
true);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRemoteDownloadReturnsAnErrorStatus_ShouldReturnFileNotFound()
{
// Arrange
_stubHttpMessageHandler.SetResponse(HttpStatusCode.NotFound, []);
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRemoteDownloadExceedsMaxSize_ShouldReturnFileTooLarge()
{
// Arrange
_stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[MAX_ARTWORK_SIZE_BYTES + 1]);
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenArtworkHasBothLocalPathAndRemoteUrl_ShouldUseTheLocalFileWithoutDeletingIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.True(File.Exists(sourcePath));
_mockFileProviderService.Received(1).CopyFile(
Arg.Is<FileSystemPathId>(pathId => pathId.Path == sourcePath),
Arg.Any<FileSystemPathId>(),
true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRemoteDownloadIsCancelled_ShouldRethrowCancellation()
{
// Arrange
CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
async Task Act()
{
await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), cancellationTokenSource.Token);
}
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
}
[Fact]
public void DeleteBookArtwork_WhenCalled_ShouldDeleteTheCoverFilesInTheBookDirectory()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
FileSystemPathId otherFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "metadata.json"));
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, otherFileId]));
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
// Act
Result<Deleted> result = _sut.DeleteBookArtwork(libraryId, bookId, libraryName, authorName, bookTitle);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.Received(1).DeleteFile(coverFileId);
_mockFileProviderService.DidNotReceive().DeleteFile(otherFileId);
}
[Fact]
public void DeleteBookArtwork_WhenCalledWithInvalidNameSegments_ShouldReturnError()
{
// Arrange
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(Errors.FileSystemManagement.InvalidPath);
// Act
Result<Deleted> result = _sut.DeleteBookArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title");
// Assert
Assert.True(result.IsFailure);
_mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any<FileSystemPathId>(), true);
}
/// <summary>
/// Stubs the path and file system services so that the artwork is stored into the given directory.
/// </summary>
/// <param name="artworkDirectoryPath">The file system path of the directory into which the artwork is stored.</param>
private void MockArtworkDirectoryStubs(string artworkDirectoryPath)
{
string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media");
string booksPath = Path.Combine(mediaRoot, "books");
_mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot));
_mockPathService.CombinePath(mediaRoot, "books").Returns(Result.From(booksPath));
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.Arg<string>();
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
});
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
// every directory except the artwork directory itself already exists, so that only the final directory is created
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
.Returns(callInfo => Result.From(!string.Equals(callInfo.Arg<FileSystemPathId>().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase)));
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
.Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg<FileSystemPathId>().Path, callInfo.Arg<string>()))));
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([]));
}
/// <summary>
/// Builds the file system path of the directory that the artwork of the book is stored into.
/// </summary>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="bookId">The Id of the book.</param>
/// <param name="libraryName">The name of the media library the book belongs to.</param>
/// <param name="authorName">The name of the author of the book.</param>
/// <param name="bookTitle">The title of the book.</param>
/// <returns>The expected file system path of the book artwork directory.</returns>
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle)
{
return Path.Combine(
AppContext.BaseDirectory,
"media",
"books",
$"{libraryName}-{libraryId}",
authorName,
$"{bookTitle}-{bookId}");
}
/// <summary>
/// Creates a temporary image file with the given size and returns its path.
/// </summary>
/// <param name="smallImageBytes">The size of the temporary image file, in bytes.</param>
/// <returns>The file system path of the created temporary image file.</returns>
private static string CreateTempImageFile(int smallImageBytes)
{
string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-source-{Guid.NewGuid():N}.jpg");
File.WriteAllBytes(sourcePath, new byte[smallImageBytes]);
return sourcePath;
}
/// <summary>
/// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms.
/// </summary>
/// <param name="linkPath">The file system path of the link to create.</param>
/// <param name="targetDirectory">The file system path of the directory the link points to.</param>
/// <returns><see langword="true"/> when the link was created, <see langword="false"/> otherwise.</returns>
private static bool TryCreateJunction(string linkPath, string targetDirectory)
{
try
{
System.Diagnostics.ProcessStartInfo startInfo = OperatingSystem.IsWindows()
? new()
{
FileName = "cmd.exe",
Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"",
CreateNoWindow = true,
UseShellExecute = false
}
: new()
{
FileName = "ln",
CreateNoWindow = true,
UseShellExecute = false
};
if (!OperatingSystem.IsWindows())
{
startInfo.ArgumentList.Add("-s");
startInfo.ArgumentList.Add(targetDirectory);
startInfo.ArgumentList.Add(linkPath);
}
System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo)!;
process.WaitForExit(5000);
return process.ExitCode == 0;
}
catch (Exception)
{
return false;
}
}
}
@@ -0,0 +1,252 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Calibre.Core;
using Lumina.Plugins.Calibre.Fixtures.Core.Metadata;
using Lumina.Plugins.Contracts.Core.Metadata;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.Calibre.UnitTests.Core;
/// <summary>
/// Contains unit tests for the <see cref="CalibreArtworkProvider"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CalibreArtworkProviderTests
{
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
private readonly TestMetadataLookupFixture _testMetadataLookupFixture = new();
private readonly CalibreArtworkProvider _sut = new();
[Fact]
public void Name_WhenCalled_ShouldReturnTheProviderDisplayName()
{
// Act
string result = _sut.Name;
// Assert
Assert.Equal("Calibre", result);
}
[Fact]
public void SupportedLibraryTypes_WhenCalled_ShouldReturnBookAndEBook()
{
// Act
IReadOnlyList<LibraryType> result = _sut.SupportedLibraryTypes;
// Assert
Assert.Equal(2, result.Count);
Assert.Equal(LibraryType.Book, result[0]);
Assert.Equal(LibraryType.EBook, result[1]);
}
[Fact]
public void RequiresWebAccess_WhenCalled_ShouldReturnFalse()
{
// Act
bool result = _sut.RequiresWebAccess;
// Assert
Assert.False(result);
}
[Fact]
public async Task GetArtworkAsync_WhenCoverHrefIsABareFileName_ShouldReturnTheLocalCoverPath()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
WriteOpf(bookDirectory, coverHref: "cover.jpg");
File.WriteAllText(Path.Combine(bookDirectory, "cover.jpg"), "image-bytes");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath);
Assert.Null(result.RemoteUrl);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetArtworkAsync_WhenCoverHrefIsAnAbsolutePath_ShouldReturnNull()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
WriteOpf(bookDirectory, coverHref: @"C:\Windows\System32\drivers\etc\hosts");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Theory]
[InlineData("../cover.jpg")] // parent directory escape
[InlineData("sub/cover.jpg")] // path with a separator
[InlineData("sub\\cover.jpg")] // path with a backslash separator
public async Task GetArtworkAsync_WhenCoverHrefContainsPathTraversalOrSeparators_ShouldReturnNull(string coverHref)
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
WriteOpf(bookDirectory, coverHref);
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetArtworkAsync_WhenCoverFileIsMissing_ShouldReturnNull()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
WriteOpf(bookDirectory, coverHref: "cover.jpg");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetArtworkAsync_WhenOpfFileDoesNotExist_ShouldReturnNull()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetArtworkAsync_WhenOpfHasNoCoverReference_ShouldReturnNull()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), """<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>Test</dc:title></metadata></package>""");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetArtworkAsync_WhenLookupIsNotABookLookup_ShouldReturnNull()
{
// Arrange
MetadataLookupDto lookup = _testMetadataLookupFixture.Create();
IArtworkProvider baseProvider = _sut;
// Act
ArtworkDto? result = await baseProvider.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
[Fact]
public async Task GetArtworkAsync_WhenLookupPathIsEmpty_ShouldReturnNull()
{
// Arrange
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: " ");
// Act
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
/// <summary>
/// Writes an OPF file that references the given cover into the book directory.
/// </summary>
/// <param name="bookDirectory">The file system path of the directory the OPF file is written into.</param>
/// <param name="coverHref">The href of the cover the OPF file references.</param>
private static void WriteOpf(string bookDirectory, string coverHref)
{
string opf = $$"""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>Test</dc:title></metadata><guide><reference type="cover" href="{{coverHref}}"/></guide></package>""";
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opf);
}
/// <summary>
/// Creates a unique temporary directory for the book.
/// </summary>
/// <returns>The file system path of the created temporary directory.</returns>
private static string CreateTempDirectory()
{
string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-artwork-{Guid.NewGuid():N}");
Directory.CreateDirectory(directoryPath);
return directoryPath;
}
}
@@ -0,0 +1,174 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Calibre.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.Calibre.UnitTests.Core;
/// <summary>
/// Contains unit tests for the <see cref="CalibreBookMetadataProvider"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CalibreBookMetadataProviderTests
{
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
private readonly CalibreBookMetadataProvider _sut = new();
private const string OPF_DOCUMENT = """<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf" version="2.0"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf"><dc:title>Test Book Title</dc:title><dc:creator opf:role="aut">Test Author</dc:creator></metadata></package>""";
[Fact]
public void Name_WhenCalled_ShouldReturnTheProviderDisplayName()
{
// Act
string result = _sut.Name;
// Assert
Assert.Equal("Calibre", result);
}
[Fact]
public void SupportedLibraryTypes_WhenCalled_ShouldReturnBookAndEBook()
{
// Act
IReadOnlyList<LibraryType> result = _sut.SupportedLibraryTypes;
// Assert
Assert.Equal(2, result.Count);
Assert.Equal(LibraryType.Book, result[0]);
Assert.Equal(LibraryType.EBook, result[1]);
}
[Fact]
public void RequiresWebAccess_WhenCalled_ShouldReturnFalse()
{
// Act
bool result = _sut.RequiresWebAccess;
// Assert
Assert.False(result);
}
[Fact]
public async Task GetMetadataAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnTheMappedMetadata()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT);
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Equal("Test Book Title", result!.Title);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetMetadataAsync_WhenOpfFileDoesNotExist_ShouldReturnNull()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetMetadataAsync_WhenLookupPathIsEmpty_ShouldReturnNull()
{
// Arrange
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: " ");
// Act
BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
[Fact]
public async Task GetSearchResultsAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnASingleMetadataCandidate()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT);
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
IReadOnlyList<BookMetadataDto> result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None);
// Assert
BookMetadataDto metadata = Assert.IsType<BookMetadataDto>(Assert.Single(result));
Assert.Equal("Test Book Title", metadata.Title);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetSearchResultsAsync_WhenOpfFileDoesNotExist_ShouldReturnAnEmptyList()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
IReadOnlyList<BookMetadataDto> result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None);
// Assert
Assert.Empty(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
/// <summary>
/// Creates a unique temporary directory for the book.
/// </summary>
/// <returns>The file system path of the created temporary directory.</returns>
private static string CreateTempDirectory()
{
string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-metadata-{Guid.NewGuid():N}");
Directory.CreateDirectory(directoryPath);
return directoryPath;
}
}
@@ -0,0 +1,98 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Calibre.Core;
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Plugins.Calibre.UnitTests.Core;
/// <summary>
/// Contains unit tests for the <see cref="CalibrePlugin"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CalibrePluginTests
{
private readonly CalibrePlugin _sut = new();
[Fact]
public void Id_WhenCalled_ShouldReturnStablePluginIdentifier()
{
// Act
Guid result = _sut.Id;
// Assert
Assert.Equal(CalibrePlugin.s_pluginId, result);
Assert.Equal(new Guid("a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d"), result);
}
[Fact]
public void Name_WhenCalled_ShouldReturnPluginDisplayName()
{
// Act
string result = _sut.Name;
// Assert
Assert.Equal("Calibre 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("Reads book metadata and covers from the OPF files of a Calibre library.", result);
}
[Fact]
public void GetSettingsSchema_WhenCalled_ShouldReturnEmptySettingsSchema()
{
// Act
IReadOnlyList<PluginSettingDescriptorDto> result = _sut.GetSettingsSchema();
// Assert
Assert.Empty(result);
}
[Fact]
public void RegisterServices_WhenCalled_ShouldRegisterTheKeyedMetadataAndArtworkProviders()
{
// Arrange
ServiceCollection services = new();
// Act
_sut.RegisterServices(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert
Assert.NotNull(serviceProvider.GetKeyedService<IMetadataProvider>(CalibrePlugin.s_pluginId));
Assert.NotNull(serviceProvider.GetKeyedService<IArtworkProvider>(CalibrePlugin.s_pluginId));
Assert.Null(serviceProvider.GetKeyedService<IMetadataProvider>(Guid.NewGuid()));
Assert.Null(serviceProvider.GetKeyedService<IArtworkProvider>(Guid.NewGuid()));
}
}
@@ -0,0 +1,367 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
using Lumina.Plugins.Calibre.Core.Mapping;
using Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Plugins.Calibre.UnitTests.Core.Mapping;
/// <summary>
/// Contains unit tests for the <see cref="CalibreMapper"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CalibreMapperTests
{
private readonly OpfDocumentDtoFixture _opfDocumentDtoFixture = new();
private readonly OpfCreatorDtoFixture _opfCreatorDtoFixture = new();
private readonly OpfContributorDtoFixture _opfContributorDtoFixture = new();
private readonly OpfIdentifierDtoFixture _opfIdentifierDtoFixture = new();
[Fact]
public void Map_WhenDocumentHasAllFields_ShouldMapThemToTheBookMetadataDto()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create(
title: "Test Book Title",
description: "<p>A test description with <b>markup</b>. </p>",
publisher: "Test Publisher",
publishDate: new DateTimeOffset(2015, 6, 15, 0, 0, 0, TimeSpan.Zero),
languageCode: "en",
series: "The Series",
seriesIndex: 2.5,
rating: 8,
subjects: ["Science fiction", "Space opera"],
creators: [_opfCreatorDtoFixture.Create("Test Author", "aut"), _opfCreatorDtoFixture.Create("Co Author", "oth")],
contributors:
[
_opfContributorDtoFixture.Create("calibre (3.48.0) [https://calibre-ebook.com]", "bkp"),
_opfContributorDtoFixture.Create("Test Translator", "trl")
],
identifiers:
[
_opfIdentifierDtoFixture.Create("ISBN", "978-0-306-40615-7"),
_opfIdentifierDtoFixture.Create("goodreads", "123456"),
_opfIdentifierDtoFixture.Create("ASIN", "B00TEST1"),
_opfIdentifierDtoFixture.Create("lccn", "test-lccn"),
_opfIdentifierDtoFixture.Create("oclc", "ocm12345678"),
_opfIdentifierDtoFixture.Create("openlibrary", "OL100M"),
_opfIdentifierDtoFixture.Create("google", "google-id")
]);
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Equal("Test Book Title", result.Title);
Assert.Equal("A test description with markup .", result.Description);
Assert.Equal("Test Publisher", result.Publisher);
Assert.NotNull(result.ReleaseInfo);
Assert.Equal(new DateOnly(2015, 6, 15), result.ReleaseInfo!.OriginalReleaseDate);
Assert.Equal(2015, result.ReleaseInfo.OriginalReleaseYear);
Assert.Equal("The Series", result.Series!.Title);
Assert.Equal(2.5f, result.VolumeNumber);
Assert.Equal("B00TEST1", result.ASIN);
Assert.Equal("123456", result.GoodreadsId);
Assert.Equal("test-lccn", result.LCCN);
Assert.Equal("ocm12345678", result.OCLCNumber);
Assert.Equal("OL100M", result.OpenLibraryId);
Assert.Equal("google-id", result.GoogleBooksId);
Assert.Null(result.Genres);
Assert.Null(result.CoverImagePath);
}
[Fact]
public void Map_WhenDescriptionContainsHtmlEntities_ShouldDecodeAndStripThem()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create(description: "A &amp; B &lt;tag&gt;description&lt;/tag&gt; with multiple spaces");
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Equal("A & B description with multiple spaces", result.Description);
}
[Fact]
public void Map_WhenDescriptionIsEmpty_ShouldReturnNullDescription()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create(description: " ");
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Null(result.Description);
}
[Theory]
[InlineData(0)] // a zero series index is not a meaningful volume number
public void Map_WhenSeriesIndexIsZero_ShouldReturnNullVolumeNumber(double seriesIndex)
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create(seriesIndex: seriesIndex);
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Null(result.VolumeNumber);
}
[Fact]
public void Map_WhenSeriesIndexIsNull_ShouldReturnNullVolumeNumber()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create();
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Null(result.VolumeNumber);
}
[Fact]
public void Map_WhenSeriesIsNull_ShouldReturnNullSeries()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create();
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Null(result.Series);
}
[Fact]
public void Map_WhenRatingIsPresent_ShouldMapItToACalibreRatingWithMaxValueTen()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create(rating: 8);
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
BookRatingDto rating = Assert.Single(result.Ratings!);
Assert.Equal(8m, rating.Value);
Assert.Equal(10m, rating.MaxValue);
Assert.Equal(BookRatingSource.Calibre, rating.Source);
Assert.Null(rating.VoteCount);
}
[Fact]
public void Map_WhenRatingIsMissing_ShouldReturnNullRatings()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create();
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Null(result.Ratings);
}
[Fact]
public void Map_WhenSubjectsArePresent_ShouldMapThemToTagsWithNullGenres()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create(subjects: ["Science fiction", "Space opera"]);
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Null(result.Genres);
Assert.Equal(2, result.Tags!.Count);
Assert.Equal("Science fiction", result.Tags[0].Name);
Assert.Equal("Space opera", result.Tags[1].Name);
}
[Fact]
public void Map_WhenCreatorsAndContributorsArePresent_ShouldMapRolesAndCategories()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create(
creators: [_opfCreatorDtoFixture.Create("Test Author", "aut"), _opfCreatorDtoFixture.Create("Co Author", null)],
contributors:
[
_opfContributorDtoFixture.Create("Test Translator", "trl"),
_opfContributorDtoFixture.Create("Test Illustrator", "ill"),
_opfContributorDtoFixture.Create("calibre (3.48.0) [https://calibre-ebook.com]", "bkp"),
_opfContributorDtoFixture.Create("Misc Contributor", null)
]);
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Equal(6, result.Contributors!.Count);
MediaContributorDto author = result.Contributors[0];
Assert.Equal("Test Author", author.Name!.DisplayName);
Assert.Equal("Author", author.Role!.Name);
Assert.Equal("Writing", author.Role.Category);
MediaContributorDto coAuthor = result.Contributors[1];
Assert.Equal("Co Author", coAuthor.Name!.DisplayName);
Assert.Equal("Author", coAuthor.Role!.Name);
Assert.Equal("Writing", coAuthor.Role.Category);
MediaContributorDto translator = result.Contributors[2];
Assert.Equal("Test Translator", translator.Name!.DisplayName);
Assert.Equal("trl", translator.Role!.Name);
Assert.Equal("Translation", translator.Role.Category);
MediaContributorDto illustrator = result.Contributors[3];
Assert.Equal("Test Illustrator", illustrator.Name!.DisplayName);
Assert.Equal("ill", illustrator.Role!.Name);
Assert.Equal("Art", illustrator.Role.Category);
MediaContributorDto production = result.Contributors[4];
Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", production.Name!.DisplayName);
Assert.Equal("bkp", production.Role!.Name);
Assert.Equal("Production", production.Role.Category);
MediaContributorDto misc = result.Contributors[5];
Assert.Equal("Misc Contributor", misc.Name!.DisplayName);
Assert.Equal("Contributor", misc.Role!.Name);
Assert.Equal("Other", misc.Role.Category);
}
[Fact]
public void Map_WhenCreatorsAreDuplicatedWithTheSameRole_ShouldDeDuplicateThem()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create(creators: [_opfCreatorDtoFixture.Create("Test Author", "aut"), _opfCreatorDtoFixture.Create("Test Author", "aut")]);
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
MediaContributorDto author = Assert.Single(result.Contributors!);
Assert.Equal("Test Author", author.Name!.DisplayName);
}
[Fact]
public void Map_WhenIsbnIdentifiersArePresent_ShouldNormalizeAndMapThem()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create(identifiers:
[
_opfIdentifierDtoFixture.Create("ISBN", "978-0-306-40615-7"),
_opfIdentifierDtoFixture.Create("ISBN", "0306406152"),
_opfIdentifierDtoFixture.Create("ISBN", "978-0-306-40615-7"),
_opfIdentifierDtoFixture.Create("ISBN", "not-an-isbn")
]);
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Equal(2, result.Isbns!.Count);
Assert.Contains(result.Isbns, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13);
Assert.Contains(result.Isbns, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10);
}
[Fact]
public void Map_WhenNoIdentifiersArePresent_ShouldReturnEmptyIsbnList()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create();
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Empty(result.Isbns!);
}
[Fact]
public void Map_WhenAmazonIdentifiersArePresent_ShouldMapAsin()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create(identifiers: [_opfIdentifierDtoFixture.Create("amazon", "B00TEST1")]);
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Equal("B00TEST1", result.ASIN);
}
[Fact]
public void Map_WhenLanguageCodeIsUnknown_ShouldReturnTheRawCode()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create(languageCode: "zz");
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Equal("zz", result.Language!.LanguageCode);
Assert.Equal("zz", result.Language.LanguageName);
}
[Fact]
public void Map_WhenLanguageCodeIsEmpty_ShouldReturnNullLanguage()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create(languageCode: " ");
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Null(result.Language);
}
[Fact]
public void Map_WhenDocumentHasNoMetadata_ShouldReturnEmptyDto()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create();
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
Assert.Null(result.Title);
Assert.Null(result.Description);
Assert.NotNull(result.ReleaseInfo);
Assert.Null(result.Publisher);
Assert.Null(result.Series);
Assert.Null(result.VolumeNumber);
Assert.Null(result.Ratings);
}
[Fact]
public void Map_WhenPublishDateIsMissing_ShouldReturnEmptyReleaseInfo()
{
// Arrange
OpfDocumentDto document = _opfDocumentDtoFixture.Create(publishDate: null);
// Act
BookMetadataDto result = CalibreMapper.Map(document);
// Assert
// a book without a publication date must still be enrichable, so the release info is present with empty fields
Assert.NotNull(result.ReleaseInfo);
Assert.Null(result.ReleaseInfo!.OriginalReleaseDate);
Assert.Null(result.ReleaseInfo.OriginalReleaseYear);
Assert.Null(result.ReleaseInfo.ReReleaseDate);
Assert.Null(result.ReleaseInfo.ReReleaseYear);
Assert.Null(result.ReleaseInfo.ReleaseCountry);
Assert.Null(result.ReleaseInfo.ReleaseVersion);
}
}
@@ -0,0 +1,212 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
using Lumina.Plugins.Calibre.Core.Opf;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
#endregion
namespace Lumina.Plugins.Calibre.UnitTests.Core.Opf;
/// <summary>
/// Contains unit tests for the <see cref="OpfReader"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class OpfReaderTests
{
[Fact]
public void Read_WhenOpfFileContainsAllSupportedFields_ShouldParseThemAll()
{
// Arrange
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="uuid_id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf"><dc:title>Test Book Title</dc:title><dc:creator opf:role="aut">Test Author</dc:creator><dc:creator opf:role="oth">Second Creator</dc:creator><dc:contributor opf:role="bkp">calibre (3.48.0) [https://calibre-ebook.com]</dc:contributor><dc:contributor opf:role="trl">Test Translator</dc:contributor><dc:description>&lt;p&gt;A test description with &lt;b&gt;markup&lt;/b&gt;.&lt;/p&gt;</dc:description><dc:publisher>Test Publisher</dc:publisher><dc:date>2015-06-15</dc:date><dc:language>en</dc:language><dc:identifier opf:scheme="ISBN">978-0-306-40615-7</dc:identifier><dc:identifier opf:scheme="goodreads">123456</dc:identifier><dc:identifier opf:scheme="ASIN">B00TEST1</dc:identifier><dc:identifier opf:scheme="LCCN">test-lccn</dc:identifier><dc:identifier opf:scheme="oclc">ocm12345678</dc:identifier><dc:identifier opf:scheme="openlibrary">OL100M</dc:identifier><dc:identifier opf:scheme="google">google-id</dc:identifier><dc:subject>Science fiction</dc:subject><dc:subject>Space opera</dc:subject><meta name="calibre:series" content="The Series"/><meta name="calibre:series_index" content="2.5"/><meta name="calibre:rating" content="8"/></metadata><guide><reference type="cover" href="cover.jpg"/><reference type="toc" href="toc.xhtml"/></guide></package>""");
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Equal("Test Book Title", result.Title);
Assert.Equal("<p>A test description with <b>markup</b>.</p>", result.Description);
Assert.Equal("Test Publisher", result.Publisher);
Assert.Equal(2015, result.PublishDate!.Value.Year);
Assert.Equal(6, result.PublishDate.Value.Month);
Assert.Equal(15, result.PublishDate.Value.Day);
Assert.Equal("en", result.LanguageCode);
Assert.Equal("The Series", result.Series);
Assert.Equal(2.5, result.SeriesIndex);
Assert.Equal(8, result.Rating);
Assert.Equal("cover.jpg", result.CoverHref);
Assert.Equal(2, result.Creators.Count);
Assert.Equal("Test Author", result.Creators[0].Name);
Assert.Equal("aut", result.Creators[0].Role);
Assert.Equal(2, result.Contributors.Count);
Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", result.Contributors[0].Name);
Assert.Equal("bkp", result.Contributors[0].Role);
Assert.Equal(7, result.Identifiers.Count);
Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "ISBN" && identifier.Value == "978-0-306-40615-7");
Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "goodreads" && identifier.Value == "123456");
Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "ASIN" && identifier.Value == "B00TEST1");
Assert.Equal(2, result.Subjects.Count);
Assert.Equal("Science fiction", result.Subjects[0]);
Assert.Equal("Space opera", result.Subjects[1]);
}
finally
{
File.Delete(opfFilePath);
}
}
[Fact]
public void Read_WhenOpfFileDoesNotExist_ShouldReturnEmptyDocument()
{
// Act
OpfDocumentDto result = OpfReader.Read(Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.opf"));
// Assert
Assert.Null(result.Title);
Assert.Empty(result.Identifiers);
Assert.Empty(result.Creators);
Assert.Empty(result.Subjects);
}
[Fact]
public void Read_WhenMetadataContainsWhitespaceOnlyValues_ShouldSkipThem()
{
// Arrange
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title> </dc:title><dc:creator opf:role="aut"> </dc:creator><dc:subject></dc:subject></metadata></package>""");
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Null(result.Title);
Assert.Empty(result.Creators);
Assert.Empty(result.Subjects);
}
finally
{
File.Delete(opfFilePath);
}
}
[Fact]
public void Read_WhenMetadataElementIsMissing_ShouldReturnEmptyDocument()
{
// Arrange
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"></package>""");
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Null(result.Title);
Assert.Empty(result.Identifiers);
}
finally
{
File.Delete(opfFilePath);
}
}
[Fact]
public void Read_WhenOpfFileDeclaresADoctypeWithEntities_ShouldNotExpandThem()
{
// Arrange
// the DTD is prohibited, so the document must not be parsed and the entity must not be expanded into the title
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><!DOCTYPE package [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>&xxe;</dc:title></metadata></package>""");
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Null(result.Title);
}
finally
{
File.Delete(opfFilePath);
}
}
[Fact]
public void Read_WhenOpfFileContainsBillionLaughsStyleEntityExpansion_ShouldNotExpandThem()
{
// Arrange
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"><!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">]><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>&lol3;</dc:title></metadata></package>""");
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Null(result.Title);
}
finally
{
File.Delete(opfFilePath);
}
}
[Fact]
public void Read_WhenOpfFileIsOversized_ShouldReturnEmptyDocument()
{
// Arrange
string opfFilePath = Path.Combine(Path.GetTempPath(), $"oversized-{Guid.NewGuid():N}.opf");
string oversizedContent = $"""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>{new string('a', (5 * 1024 * 1024) + 100)}</dc:title></metadata></package>""";
File.WriteAllText(opfFilePath, oversizedContent);
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Null(result.Title);
Assert.Empty(result.Identifiers);
}
finally
{
File.Delete(opfFilePath);
}
}
[Fact]
public void Read_WhenOpfFileIsMalformedXml_ShouldReturnEmptyDocument()
{
// Arrange
string opfFilePath = CreateOpfFile("""<package xmlns="http://www.idpf.org/2007/opf"><metadata><dc:title>Unclosed""");
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Null(result.Title);
Assert.Empty(result.Identifiers);
}
finally
{
File.Delete(opfFilePath);
}
}
/// <summary>
/// Creates a temporary OPF file with the given content and returns its path.
/// </summary>
/// <param name="content">The content of the OPF file to create.</param>
/// <returns>The file system path of the created OPF file.</returns>
private static string CreateOpfFile(string content)
{
string opfFilePath = Path.Combine(Path.GetTempPath(), $"opf-{Guid.NewGuid():N}.opf");
File.WriteAllText(opfFilePath, content);
return opfFilePath;
}
}
@@ -0,0 +1,48 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" />
<PackageReference Include="AutoFixture.Xunit2" />
<PackageReference Include="Bogus" />
<PackageReference Include="coverlet.collector">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.Calibre\Lumina.Plugins.Calibre.csproj" />
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Plugins.Calibre.Fixtures\Lumina.Plugins.Calibre.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,105 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.Contracts.UnitTests.Core.Metadata;
/// <summary>
/// Contains unit tests for the <see cref="IArtworkProvider{TLookup}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
public class IArtworkProviderGenericTests
{
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
private readonly OtherMetadataLookupDtoFixture _otherMetadataLookupDtoFixture = new();
[Fact]
public async Task GetArtworkAsync_WhenCalledThroughBaseInterface_ShouldForwardToTypedImplementation()
{
// Arrange
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ArtworkDto expectedArtwork = _artworkDtoFixture.Create();
TestBookArtworkProvider provider = new(expectedArtwork);
IArtworkProvider baseProvider = provider;
// Act
ArtworkDto? result = await baseProvider.GetArtworkAsync(lookup, cancellationToken);
// Assert
Assert.Equal(expectedArtwork, result);
Assert.Same(lookup, provider.ReceivedLookup);
Assert.Equal(cancellationToken, provider.ReceivedCancellationToken);
}
[Fact]
public async Task GetArtworkAsync_WhenLookupIsOfAnotherRuntimeType_ShouldReturnNull()
{
// Arrange
MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create();
TestBookArtworkProvider provider = new(_artworkDtoFixture.Create());
IArtworkProvider baseProvider = provider;
// Act
ArtworkDto? result = await baseProvider.GetArtworkAsync(otherLookup, CancellationToken.None);
// Assert
Assert.Null(result);
Assert.Null(provider.ReceivedLookup);
}
/// <summary>
/// Test double for the typed artwork provider interface that records the forwarded arguments.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed class TestBookArtworkProvider : IArtworkProvider<BookMetadataLookupDto>
{
private readonly ArtworkDto _artwork;
/// <summary>
/// Gets the lookup that was forwarded to the typed implementation.
/// </summary>
public BookMetadataLookupDto? ReceivedLookup { get; private set; }
/// <summary>
/// Gets the cancellation token that was forwarded to the typed implementation.
/// </summary>
public CancellationToken ReceivedCancellationToken { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="TestBookArtworkProvider"/> class.
/// </summary>
/// <param name="artwork">The artwork returned by the typed implementation.</param>
public TestBookArtworkProvider(ArtworkDto artwork)
{
_artwork = artwork;
}
/// <inheritdoc/>
public string Name => "Test Provider";
/// <inheritdoc/>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Book];
/// <inheritdoc/>
public bool RequiresWebAccess => false;
/// <inheritdoc/>
public Task<ArtworkDto?> GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken)
{
ReceivedLookup = lookup;
ReceivedCancellationToken = cancellationToken;
return Task.FromResult<ArtworkDto?>(_artwork);
}
}
}
@@ -0,0 +1,136 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Fixtures.Core.Responses.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryArtworkProviders;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.GetLibraryArtworkProviders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryArtworkProvidersEndpointTests
{
private readonly IQueryHandler<GetLibraryArtworkProvidersQuery, Result<IReadOnlyList<LibraryArtworkProviderResponse>>> _mockHandler;
private readonly GetLibraryArtworkProvidersEndpoint _sut;
private readonly GetLibraryArtworkProvidersRequestFixture _getLibraryArtworkProvidersRequestFixture = new();
private readonly LibraryArtworkProviderResponseFixture _libraryArtworkProviderResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryArtworkProvidersEndpointTests"/> class.
/// </summary>
public GetLibraryArtworkProvidersEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetLibraryArtworkProvidersQuery, Result<IReadOnlyList<LibraryArtworkProviderResponse>>>>();
_sut = Factory.Create<GetLibraryArtworkProvidersEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLibraryArtworkProviderResponses()
{
// Arrange
GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
IReadOnlyList<LibraryArtworkProviderResponse> expectedResponses =
[
_libraryArtworkProviderResponseFixture.Create(name: "Provider A", isEnabled: true, rank: 1),
_libraryArtworkProviderResponseFixture.Create(name: "Provider B", isEnabled: false, rank: 2)
];
_mockHandler.HandleAsync(Arg.Any<GetLibraryArtworkProvidersQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponses));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<IReadOnlyList<LibraryArtworkProviderResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<LibraryArtworkProviderResponse>>>(result);
Assert.Equal(expectedResponses, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Library.NotFound", "The requested library was not found.");
_mockHandler.HandleAsync(Arg.Any<GetLibraryArtworkProvidersQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal("Library.NotFound", problemDetails.ProblemDetails.Title);
Assert.Equal("The requested library was not found.", problemDetails.ProblemDetails.Detail);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type);
Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryArtworkProvidersQueryToSender()
{
// Arrange
GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetLibraryArtworkProvidersQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderResponse>>([]));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetLibraryArtworkProvidersQuery>(query => query.LibraryId == request.LibraryId),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetLibraryArtworkProvidersQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From<IReadOnlyList<LibraryArtworkProviderResponse>>([]);
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersEndpointTests
{
private readonly ICommandHandler<ReorderLibraryArtworkProvidersCommand, Result<Success>> _mockHandler;
private readonly ReorderLibraryArtworkProvidersEndpoint _sut;
private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersEndpointTests"/> class.
/// </summary>
public ReorderLibraryArtworkProvidersEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<ReorderLibraryArtworkProvidersCommand, Result<Success>>>();
_sut = FastEndpoints.Factory.Create<ReorderLibraryArtworkProvidersEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess()
{
// Arrange
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<ReorderLibraryArtworkProvidersCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<Success> okResult = Assert.IsType<Ok<Success>>(result);
Assert.Equal(Result.Success, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("LibraryArtworkProviderConfiguration.NotFound", "The artwork provider configuration was not found.");
_mockHandler.HandleAsync(Arg.Any<ReorderLibraryArtworkProvidersCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal("LibraryArtworkProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title);
Assert.Equal("The artwork provider configuration was not found.", problemDetails.ProblemDetails.Detail);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type);
Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendReorderLibraryArtworkProvidersCommandToSender()
{
// Arrange
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<ReorderLibraryArtworkProvidersCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<ReorderLibraryArtworkProvidersCommand>(command =>
command.LibraryId == request.LibraryId &&
command.PluginIds.SequenceEqual(request.PluginIds)),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<ReorderLibraryArtworkProvidersCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Success);
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryArtworkProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledEndpointTests
{
private readonly ICommandHandler<SetLibraryArtworkProviderEnabledCommand, Result<Success>> _mockHandler;
private readonly SetLibraryArtworkProviderEnabledEndpoint _sut;
private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledEndpointTests"/> class.
/// </summary>
public SetLibraryArtworkProviderEnabledEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<SetLibraryArtworkProviderEnabledCommand, Result<Success>>>();
_sut = FastEndpoints.Factory.Create<SetLibraryArtworkProviderEnabledEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess()
{
// Arrange
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<SetLibraryArtworkProviderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<Success> okResult = Assert.IsType<Ok<Success>>(result);
Assert.Equal(Result.Success, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("LibraryArtworkProviderConfiguration.NotFound", "The artwork provider configuration was not found.");
_mockHandler.HandleAsync(Arg.Any<SetLibraryArtworkProviderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal("LibraryArtworkProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title);
Assert.Equal("The artwork provider configuration was not found.", problemDetails.ProblemDetails.Detail);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type);
Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendSetLibraryArtworkProviderEnabledCommandToSender()
{
// Arrange
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<SetLibraryArtworkProviderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<SetLibraryArtworkProviderEnabledCommand>(command =>
command.LibraryId == request.LibraryId &&
command.PluginId == request.PluginId &&
command.IsEnabled == request.IsEnabled),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<SetLibraryArtworkProviderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Success);
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}