Updates the provider configuration and ownership tests

Covers the provider and reader choices saved with a library, the reconciliation and stale configuration deletion in the provider store, the library type lookups, the ownership and permission checks for update and delete, and the validator behavior for enum names.
This commit is contained in:
BinaryAlley committed 2026-11-03 10:00:00 +02:00
1 parent 48ad8692af
commit 64e5163229
127 files changed
+5541 -5296

No files matched your search

@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management;
/// <summary>
/// Fixture class for the <see cref="LibraryProviderSelectionDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryProviderSelectionDtoFixture
{
/// <summary>
/// Creates a random valid <see cref="LibraryProviderSelectionDto"/>.
/// </summary>
/// <param name="pluginId">Optional. The Id of the plugin providing the provider or reader.</param>
/// <param name="isEnabled">Whether the provider or reader is enabled.</param>
/// <param name="includeIsEnabled">Whether the choice carries an enabled state. When <see langword="false"/>, the enabled state is <see langword="null"/>.</param>
/// <returns>The created <see cref="LibraryProviderSelectionDto"/>.</returns>
public LibraryProviderSelectionDto Create(
Guid? pluginId = null,
bool isEnabled = true,
bool includeIsEnabled = true)
{
return new LibraryProviderSelectionDto(
pluginId ?? Guid.NewGuid(),
includeIsEnabled ? isEnabled : null);
}
/// <summary>
/// Creates a list of <see cref="LibraryProviderSelectionDto"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<LibraryProviderSelectionDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -32,6 +32,9 @@ public class AddLibraryCommandFixture
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items should be tracked, or not.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
/// <param name="pathTemplateParts">Optional. The ordered parts of the path template of the media library.</param>
/// <param name="metadataProviders">Optional. The choices made for the metadata providers of the media library.</param>
/// <param name="artworkProviders">Optional. The choices made for the artwork providers of the media library.</param>
/// <param name="bookReaders">Optional. The choices made for the book readers of the media library.</param>
/// <returns>The created command.</returns>
public AddLibraryCommand Create(
string? title = null,
@@ -46,7 +49,10 @@ public class AddLibraryCommandFixture
bool isContentOnSsd = false,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
LibraryPathTemplatePartDto[]? pathTemplateParts = null)
LibraryPathTemplatePartDto[]? pathTemplateParts = null,
LibraryProviderSelectionDto[]? metadataProviders = null,
LibraryProviderSelectionDto[]? artworkProviders = null,
LibraryProviderSelectionDto[]? bookReaders = null)
{
return new Faker<AddLibraryCommand>()
.CustomInstantiator(f => new AddLibraryCommand(
@@ -62,6 +68,9 @@ public class AddLibraryCommandFixture
false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
null,
null,
null,
null
))
.RuleFor(x => x.Title, f => title ?? f.Lorem.Word())
@@ -75,6 +84,9 @@ public class AddLibraryCommandFixture
.RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan)
.RuleFor(x => x.IsContentOnSsd, isContentOnSsd)
.RuleFor(x => x.PathTemplateParts, pathTemplateParts)
.RuleFor(x => x.MetadataProviders, metadataProviders)
.RuleFor(x => x.ArtworkProviders, artworkProviders)
.RuleFor(x => x.BookReaders, bookReaders)
.Generate();
}
@@ -21,7 +21,6 @@ public class UpdateLibraryCommandFixture
/// Creates a random valid command to update a media library.
/// </summary>
/// <param name="id">Optional. The Id of the media library.</param>
/// <param name="ownerId">Optional. The Id of the user owning the media library.</param>
/// <param name="title">Optional. The title of the media library.</param>
/// <param name="libraryType">Optional. The type of the media library.</param>
/// <param name="contentLocations">Optional. The content locations of the media library.</param>
@@ -35,10 +34,12 @@ public class UpdateLibraryCommandFixture
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items should be tracked, or not.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
/// <param name="pathTemplateParts">Optional. The ordered parts of the path template of the media library.</param>
/// <param name="metadataProviders">Optional. The choices made for the metadata providers of the media library.</param>
/// <param name="artworkProviders">Optional. The choices made for the artwork providers of the media library.</param>
/// <param name="bookReaders">Optional. The choices made for the book readers of the media library.</param>
/// <returns>The created command.</returns>
public UpdateLibraryCommand Create(
Guid? id = null,
Guid? ownerId = null,
string? title = null,
string? libraryType = null,
string[]? contentLocations = null,
@@ -51,11 +52,13 @@ public class UpdateLibraryCommandFixture
bool isContentOnSsd = false,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
LibraryPathTemplatePartDto[]? pathTemplateParts = null)
LibraryPathTemplatePartDto[]? pathTemplateParts = null,
LibraryProviderSelectionDto[]? metadataProviders = null,
LibraryProviderSelectionDto[]? artworkProviders = null,
LibraryProviderSelectionDto[]? bookReaders = null)
{
return new Faker<UpdateLibraryCommand>()
.CustomInstantiator(f => new UpdateLibraryCommand(
default,
default,
default!,
default!,
@@ -69,10 +72,12 @@ public class UpdateLibraryCommandFixture
false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
null,
null,
null,
null
))
.RuleFor(x => x.Id, id ?? Guid.NewGuid())
.RuleFor(x => x.OwnerId, ownerId ?? Guid.NewGuid())
.RuleFor(x => x.Title, f => title ?? f.Lorem.Word())
.RuleFor(x => x.LibraryType, f => libraryType ?? f.Random.Enum<LibraryType>().ToString())
.RuleFor(x => x.ContentLocations, f => contentLocations ?? [f.System.DirectoryPath(), f.System.DirectoryPath(), f.System.DirectoryPath()])
@@ -84,6 +89,9 @@ public class UpdateLibraryCommandFixture
.RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan)
.RuleFor(x => x.IsContentOnSsd, isContentOnSsd)
.RuleFor(x => x.PathTemplateParts, pathTemplateParts)
.RuleFor(x => x.MetadataProviders, metadataProviders)
.RuleFor(x => x.ArtworkProviders, artworkProviders)
.RuleFor(x => x.BookReaders, bookReaders)
.Generate();
}
@@ -1,46 +0,0 @@
#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())];
}
}
@@ -1,44 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
/// <summary>
/// Fixture class for the <see cref="ReorderLibraryMetadataProvidersCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersCommandFixture
{
/// <summary>
/// Creates a random valid command to reorder the metadata providers of a media library.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose metadata providers are reordered.</param>
/// <param name="pluginIds">Optional. The plugin Ids in the new order.</param>
/// <returns>The created command.</returns>
public ReorderLibraryMetadataProvidersCommand Create(Guid? libraryId = null, IReadOnlyList<Guid>? pluginIds = null)
{
return new Faker<ReorderLibraryMetadataProvidersCommand>()
.CustomInstantiator(f => new ReorderLibraryMetadataProvidersCommand(
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="ReorderLibraryMetadataProvidersCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<ReorderLibraryMetadataProvidersCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,50 +0,0 @@
#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())];
}
}
@@ -1,41 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
/// <summary>
/// Fixture class for the <see cref="SetLibraryBookReaderEnabledCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledCommandFixture
{
/// <summary>
/// Creates a random valid command to enable or disable a book reader for a media library.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose book reader is enabled or disabled.</param>
/// <param name="pluginId">Optional. The unique identifier of the plugin providing the book reader.</param>
/// <param name="isEnabled">Optional. Whether the book reader should be enabled for the media library.</param>
/// <returns>The created <see cref="SetLibraryBookReaderEnabledCommand"/>.</returns>
public SetLibraryBookReaderEnabledCommand Create(
Guid? libraryId = null,
Guid? pluginId = null,
bool? isEnabled = null)
{
return new SetLibraryBookReaderEnabledCommand(libraryId ?? Guid.NewGuid(), pluginId ?? Guid.NewGuid(), isEnabled ?? true);
}
/// <summary>
/// Creates a list of <see cref="SetLibraryBookReaderEnabledCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<SetLibraryBookReaderEnabledCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,47 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
/// <summary>
/// Fixture class for the <see cref="SetLibraryMetadataProviderEnabledCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledCommandFixture
{
/// <summary>
/// Creates a random valid command to enable or disable a metadata provider for a media library.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose metadata provider is enabled or disabled.</param>
/// <param name="pluginId">Optional. The Id of the plugin providing the metadata.</param>
/// <param name="isEnabled">Whether the metadata provider should be enabled for the media library.</param>
/// <returns>The created command.</returns>
public SetLibraryMetadataProviderEnabledCommand Create(Guid? libraryId = null, Guid? pluginId = null, bool isEnabled = true)
{
return new Faker<SetLibraryMetadataProviderEnabledCommand>()
.CustomInstantiator(f => new SetLibraryMetadataProviderEnabledCommand(
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="SetLibraryMetadataProviderEnabledCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<SetLibraryMetadataProviderEnabledCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
/// <summary>
/// Fixture class for the <see cref="GetLibraryTypeArtworkProvidersQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersQueryFixture
{
/// <summary>
/// Creates a random valid <see cref="GetLibraryTypeArtworkProvidersQuery"/>.
/// </summary>
/// <param name="libraryType">Optional. The media library type whose available artwork providers are retrieved.</param>
/// <returns>The created <see cref="GetLibraryTypeArtworkProvidersQuery"/>.</returns>
public GetLibraryTypeArtworkProvidersQuery Create(string? libraryType = null)
{
return new GetLibraryTypeArtworkProvidersQuery(libraryType ?? "Book");
}
/// <summary>
/// Creates a list of <see cref="GetLibraryTypeArtworkProvidersQuery"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryTypeArtworkProvidersQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeBookReaders;
/// <summary>
/// Fixture class for the <see cref="GetLibraryTypeBookReadersQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersQueryFixture
{
/// <summary>
/// Creates a random valid <see cref="GetLibraryTypeBookReadersQuery"/>.
/// </summary>
/// <param name="libraryType">Optional. The media library type whose available book readers are retrieved.</param>
/// <returns>The created <see cref="GetLibraryTypeBookReadersQuery"/>.</returns>
public GetLibraryTypeBookReadersQuery Create(string? libraryType = null)
{
return new GetLibraryTypeBookReadersQuery(libraryType ?? "Book");
}
/// <summary>
/// Creates a list of <see cref="GetLibraryTypeBookReadersQuery"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryTypeBookReadersQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
/// <summary>
/// Fixture class for the <see cref="GetLibraryTypeMetadataProvidersQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersQueryFixture
{
/// <summary>
/// Creates a random valid <see cref="GetLibraryTypeMetadataProvidersQuery"/>.
/// </summary>
/// <param name="libraryType">Optional. The media library type whose available metadata providers are retrieved.</param>
/// <returns>The created <see cref="GetLibraryTypeMetadataProvidersQuery"/>.</returns>
public GetLibraryTypeMetadataProvidersQuery Create(string? libraryType = null)
{
return new GetLibraryTypeMetadataProvidersQuery(libraryType ?? "Book");
}
/// <summary>
/// Creates a list of <see cref="GetLibraryTypeMetadataProvidersQuery"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryTypeMetadataProvidersQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -32,6 +32,9 @@ public class AddLibraryRequestFixture
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items should be tracked, or not.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
/// <param name="pathTemplateParts">Optional. The ordered parts of the path template of the media library.</param>
/// <param name="metadataProviders">Optional. The choices made for the metadata providers of the media library.</param>
/// <param name="artworkProviders">Optional. The choices made for the artwork providers of the media library.</param>
/// <param name="bookReaders">Optional. The choices made for the book readers of the media library.</param>
/// <returns>The created <see cref="AddLibraryRequest"/>.</returns>
public AddLibraryRequest Create(
string? title = null,
@@ -46,7 +49,10 @@ public class AddLibraryRequestFixture
bool? isContentOnSsd = null,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
LibraryPathTemplatePartRequest[]? pathTemplateParts = null)
LibraryPathTemplatePartRequest?[]? pathTemplateParts = null,
LibraryProviderSelectionRequest?[]? metadataProviders = null,
LibraryProviderSelectionRequest?[]? artworkProviders = null,
LibraryProviderSelectionRequest?[]? bookReaders = null)
{
return new AddLibraryRequest(
title ?? _faker.Commerce.Department(),
@@ -61,7 +67,10 @@ public class AddLibraryRequestFixture
isContentOnSsd ?? false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
pathTemplateParts
pathTemplateParts,
metadataProviders,
artworkProviders,
bookReaders
);
}
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
/// <summary>
/// Fixture class for the <see cref="LibraryProviderSelectionRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryProviderSelectionRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="LibraryProviderSelectionRequest"/>.
/// </summary>
/// <param name="pluginId">Optional. The Id of the plugin providing the provider or reader.</param>
/// <param name="isEnabled">Whether the provider or reader is enabled.</param>
/// <param name="includeIsEnabled">Whether the choice carries an enabled state. When <see langword="false"/>, the enabled state is <see langword="null"/>.</param>
/// <returns>The created <see cref="LibraryProviderSelectionRequest"/>.</returns>
public LibraryProviderSelectionRequest Create(
Guid? pluginId = null,
bool isEnabled = true,
bool includeIsEnabled = true)
{
return new LibraryProviderSelectionRequest(
pluginId ?? Guid.NewGuid(),
includeIsEnabled ? isEnabled : null);
}
/// <summary>
/// Creates a list of <see cref="LibraryProviderSelectionRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<LibraryProviderSelectionRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -21,7 +21,6 @@ public class UpdateLibraryRequestFixture
/// Creates a random valid <see cref="UpdateLibraryRequest"/>.
/// </summary>
/// <param name="id">Optional. The Id of the media library to update.</param>
/// <param name="userId">Optional. The Id of the user owning the media library.</param>
/// <param name="title">Optional. The title of the media library.</param>
/// <param name="libraryType">Optional. The type of the media library.</param>
/// <param name="contentLocations">Optional. The file system paths of the media library content directories.</param>
@@ -35,10 +34,12 @@ public class UpdateLibraryRequestFixture
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items should be tracked, or not.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
/// <param name="pathTemplateParts">Optional. The ordered parts of the path template of the media library.</param>
/// <param name="metadataProviders">Optional. The choices made for the metadata providers of the media library.</param>
/// <param name="artworkProviders">Optional. The choices made for the artwork providers of the media library.</param>
/// <param name="bookReaders">Optional. The choices made for the book readers of the media library.</param>
/// <returns>The created <see cref="UpdateLibraryRequest"/>.</returns>
public UpdateLibraryRequest Create(
Guid? id = null,
Guid? userId = null,
string? title = null,
string? libraryType = null,
string[]? contentLocations = null,
@@ -51,11 +52,13 @@ public class UpdateLibraryRequestFixture
bool? isContentOnSsd = null,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
LibraryPathTemplatePartRequest[]? pathTemplateParts = null)
LibraryPathTemplatePartRequest?[]? pathTemplateParts = null,
LibraryProviderSelectionRequest?[]? metadataProviders = null,
LibraryProviderSelectionRequest?[]? artworkProviders = null,
LibraryProviderSelectionRequest?[]? bookReaders = null)
{
return new UpdateLibraryRequest(
id ?? _faker.Random.Guid(),
userId ?? _faker.Random.Guid(),
title ?? _faker.Commerce.Department(),
libraryType ?? "EBook",
contentLocations ?? [_faker.System.DirectoryPath()],
@@ -68,7 +71,10 @@ public class UpdateLibraryRequestFixture
isContentOnSsd ?? false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
pathTemplateParts
pathTemplateParts,
metadataProviders,
artworkProviders,
bookReaders
);
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Requests.Plugins;
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="GetLibraryTypeArtworkProvidersRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="GetLibraryTypeArtworkProvidersRequest"/>.
/// </summary>
/// <param name="libraryType">Optional. The media library type whose available artwork providers are retrieved.</param>
/// <returns>The created <see cref="GetLibraryTypeArtworkProvidersRequest"/>.</returns>
public GetLibraryTypeArtworkProvidersRequest Create(string? libraryType = null)
{
return new GetLibraryTypeArtworkProvidersRequest(libraryType ?? "Book");
}
/// <summary>
/// Creates a list of <see cref="GetLibraryTypeArtworkProvidersRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryTypeArtworkProvidersRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Requests.Plugins;
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="GetLibraryTypeBookReadersRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="GetLibraryTypeBookReadersRequest"/>.
/// </summary>
/// <param name="libraryType">Optional. The media library type whose available book readers are retrieved.</param>
/// <returns>The created <see cref="GetLibraryTypeBookReadersRequest"/>.</returns>
public GetLibraryTypeBookReadersRequest Create(string? libraryType = null)
{
return new GetLibraryTypeBookReadersRequest(libraryType ?? "Book");
}
/// <summary>
/// Creates a list of <see cref="GetLibraryTypeBookReadersRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryTypeBookReadersRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Requests.Plugins;
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="GetLibraryTypeMetadataProvidersRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="GetLibraryTypeMetadataProvidersRequest"/>.
/// </summary>
/// <param name="libraryType">Optional. The media library type whose available metadata providers are retrieved.</param>
/// <returns>The created <see cref="GetLibraryTypeMetadataProvidersRequest"/>.</returns>
public GetLibraryTypeMetadataProvidersRequest Create(string? libraryType = null)
{
return new GetLibraryTypeMetadataProvidersRequest(libraryType ?? "Book");
}
/// <summary>
/// Creates a list of <see cref="GetLibraryTypeMetadataProvidersRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryTypeMetadataProvidersRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,45 +0,0 @@
#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())];
}
}
@@ -1,45 +0,0 @@
#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="ReorderLibraryMetadataProvidersRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="ReorderLibraryMetadataProvidersRequest"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose metadata providers are reordered.</param>
/// <param name="pluginIds">Optional. The plugin Ids in the new order.</param>
/// <returns>The created <see cref="ReorderLibraryMetadataProvidersRequest"/>.</returns>
public ReorderLibraryMetadataProvidersRequest Create(
Guid? libraryId = null,
IReadOnlyList<Guid>? pluginIds = null)
{
return new ReorderLibraryMetadataProvidersRequest(
libraryId ?? _faker.Random.Guid(),
pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()]
);
}
/// <summary>
/// Creates a list of <see cref="ReorderLibraryMetadataProvidersRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<ReorderLibraryMetadataProvidersRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,48 +0,0 @@
#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())];
}
}
@@ -1,41 +0,0 @@
#region ========================================================================= USING =====================================================================================
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="SetLibraryBookReaderEnabledRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="SetLibraryBookReaderEnabledRequest"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose book reader is enabled or disabled.</param>
/// <param name="pluginId">Optional. The unique identifier of the plugin providing the book reader.</param>
/// <param name="isEnabled">Optional. Whether the book reader should be enabled for the media library.</param>
/// <returns>The created <see cref="SetLibraryBookReaderEnabledRequest"/>.</returns>
public SetLibraryBookReaderEnabledRequest Create(
Guid? libraryId = null,
Guid? pluginId = null,
bool? isEnabled = null)
{
return new SetLibraryBookReaderEnabledRequest(libraryId ?? Guid.NewGuid(), pluginId ?? Guid.NewGuid(), isEnabled ?? true);
}
/// <summary>
/// Creates a list of <see cref="SetLibraryBookReaderEnabledRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<SetLibraryBookReaderEnabledRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,48 +0,0 @@
#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="SetLibraryMetadataProviderEnabledRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="SetLibraryMetadataProviderEnabledRequest"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose metadata provider is enabled or disabled.</param>
/// <param name="pluginId">Optional. The Id of the plugin providing the metadata.</param>
/// <param name="isEnabled">Optional. Whether the metadata provider should be enabled.</param>
/// <returns>The created <see cref="SetLibraryMetadataProviderEnabledRequest"/>.</returns>
public SetLibraryMetadataProviderEnabledRequest Create(
Guid? libraryId = null,
Guid? pluginId = null,
bool? isEnabled = null)
{
return new SetLibraryMetadataProviderEnabledRequest(
libraryId ?? _faker.Random.Guid(),
pluginId ?? _faker.Random.Guid(),
isEnabled ?? _faker.Random.Bool()
);
}
/// <summary>
/// Creates a list of <see cref="SetLibraryMetadataProviderEnabledRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<SetLibraryMetadataProviderEnabledRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -31,7 +31,6 @@ public class LibraryDtoFixture
return new LibraryDto
{
Id = id ?? Guid.NewGuid(),
UserId = Guid.NewGuid(),
Title = title ?? _faker.Commerce.Department(),
LibraryType = libraryType ?? _faker.PickRandom("Book", "Video", "Photo"),
CoverImage = _faker.Image.PicsumUrl(),
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.Libraries;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
/// <summary>
/// Fixture class for the <see cref="LibraryProviderSelectionDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryProviderSelectionDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="LibraryProviderSelectionDto"/>.
/// </summary>
/// <param name="pluginId">Optional. The Id of the plugin providing the provider or reader.</param>
/// <param name="isEnabled">Optional. Whether the provider or reader is enabled.</param>
/// <param name="includeIsEnabled">Whether the choice carries an enabled state. When <see langword="false"/>, the enabled state is <see langword="null"/>.</param>
/// <returns>The created <see cref="LibraryProviderSelectionDto"/>.</returns>
public LibraryProviderSelectionDto Create(
Guid? pluginId = null,
bool? isEnabled = null,
bool includeIsEnabled = true)
{
return new LibraryProviderSelectionDto
{
PluginId = pluginId ?? Guid.NewGuid(),
IsEnabled = includeIsEnabled ? isEnabled ?? _faker.Random.Bool() : null
};
}
/// <summary>
/// Creates a list of <see cref="LibraryProviderSelectionDto"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<LibraryProviderSelectionDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
/// <summary>
/// Fixture class for the <see cref="GetLibraryTypeArtworkProvidersRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="GetLibraryTypeArtworkProvidersRequest"/>.
/// </summary>
/// <param name="libraryType">Optional. The media library type whose available artwork providers are retrieved.</param>
/// <returns>The created <see cref="GetLibraryTypeArtworkProvidersRequest"/>.</returns>
public GetLibraryTypeArtworkProvidersRequest Create(
string? libraryType = null)
{
return new GetLibraryTypeArtworkProvidersRequest(libraryType ?? "Book");
}
/// <summary>
/// Creates a list of <see cref="GetLibraryTypeArtworkProvidersRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryTypeArtworkProvidersRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
/// <summary>
/// Fixture class for the <see cref="GetLibraryTypeBookReadersRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="GetLibraryTypeBookReadersRequest"/>.
/// </summary>
/// <param name="libraryType">Optional. The media library type whose available book readers are retrieved.</param>
/// <returns>The created <see cref="GetLibraryTypeBookReadersRequest"/>.</returns>
public GetLibraryTypeBookReadersRequest Create(
string? libraryType = null)
{
return new GetLibraryTypeBookReadersRequest(libraryType ?? "Book");
}
/// <summary>
/// Creates a list of <see cref="GetLibraryTypeBookReadersRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryTypeBookReadersRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
/// <summary>
/// Fixture class for the <see cref="GetLibraryTypeMetadataProvidersRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="GetLibraryTypeMetadataProvidersRequest"/>.
/// </summary>
/// <param name="libraryType">Optional. The media library type whose available metadata providers are retrieved.</param>
/// <returns>The created <see cref="GetLibraryTypeMetadataProvidersRequest"/>.</returns>
public GetLibraryTypeMetadataProvidersRequest Create(
string? libraryType = null)
{
return new GetLibraryTypeMetadataProvidersRequest(libraryType ?? "Book");
}
/// <summary>
/// Creates a list of <see cref="GetLibraryTypeMetadataProvidersRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryTypeMetadataProvidersRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,45 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
/// <summary>
/// Fixture class for the <see cref="ReorderLibraryArtworkProvidersRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="ReorderLibraryArtworkProvidersRequest"/> instance with randomized test data.
/// </summary>
/// <param name="libraryId">Optional identifier of the media library.</param>
/// <param name="pluginIds">Optional plugin Ids in the new order.</param>
/// <returns>A configured <see cref="ReorderLibraryArtworkProvidersRequest"/> instance.</returns>
public ReorderLibraryArtworkProvidersRequest Create(
Guid? libraryId = null,
List<Guid>? pluginIds = null)
{
return new ReorderLibraryArtworkProvidersRequest(
LibraryId: libraryId ?? Guid.NewGuid(),
PluginIds: pluginIds ?? [_faker.Random.Guid(), _faker.Random.Guid()]
);
}
/// <summary>
/// Creates multiple <see cref="ReorderLibraryArtworkProvidersRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ReorderLibraryArtworkProvidersRequest"/> instances.</returns>
public List<ReorderLibraryArtworkProvidersRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,45 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
/// <summary>
/// Fixture class for the <see cref="ReorderLibraryMetadataProvidersRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="ReorderLibraryMetadataProvidersRequest"/> instance with randomized test data.
/// </summary>
/// <param name="libraryId">Optional identifier of the media library.</param>
/// <param name="pluginIds">Optional plugin Ids in the new order.</param>
/// <returns>A configured <see cref="ReorderLibraryMetadataProvidersRequest"/> instance.</returns>
public ReorderLibraryMetadataProvidersRequest Create(
Guid? libraryId = null,
List<Guid>? pluginIds = null)
{
return new ReorderLibraryMetadataProvidersRequest(
LibraryId: libraryId ?? Guid.NewGuid(),
PluginIds: pluginIds ?? [_faker.Random.Guid(), _faker.Random.Guid()]
);
}
/// <summary>
/// Creates multiple <see cref="ReorderLibraryMetadataProvidersRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ReorderLibraryMetadataProvidersRequest"/> instances.</returns>
public List<ReorderLibraryMetadataProvidersRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,45 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
/// <summary>
/// Fixture class for the <see cref="SetBookReaderEnabledRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetBookReaderEnabledRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="SetBookReaderEnabledRequest"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose book reader is enabled or disabled.</param>
/// <param name="pluginId">Optional. The unique identifier of the plugin providing the book reader.</param>
/// <param name="isEnabled">Optional. Whether the book reader should be enabled for the media library.</param>
/// <returns>The created <see cref="SetBookReaderEnabledRequest"/>.</returns>
public SetBookReaderEnabledRequest Create(
Guid? libraryId = null,
Guid? pluginId = null,
bool? isEnabled = null)
{
return new SetBookReaderEnabledRequest(
LibraryId: libraryId ?? Guid.NewGuid(),
PluginId: pluginId ?? Guid.NewGuid(),
IsEnabled: isEnabled ?? true
);
}
/// <summary>
/// Creates a list of <see cref="SetBookReaderEnabledRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<SetBookReaderEnabledRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,48 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
/// <summary>
/// Fixture class for the <see cref="SetLibraryArtworkProviderEnabledRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="SetLibraryArtworkProviderEnabledRequest"/> instance with randomized test data.
/// </summary>
/// <param name="libraryId">Optional identifier of the media library.</param>
/// <param name="pluginId">Optional identifier of the plugin.</param>
/// <param name="isEnabled">Optional value indicating whether the artwork provider is enabled.</param>
/// <returns>A configured <see cref="SetLibraryArtworkProviderEnabledRequest"/> instance.</returns>
public SetLibraryArtworkProviderEnabledRequest Create(
Guid? libraryId = null,
Guid? pluginId = null,
bool? isEnabled = null)
{
return new SetLibraryArtworkProviderEnabledRequest(
LibraryId: libraryId ?? Guid.NewGuid(),
PluginId: pluginId ?? Guid.NewGuid(),
IsEnabled: isEnabled ?? _faker.Random.Bool()
);
}
/// <summary>
/// Creates multiple <see cref="SetLibraryArtworkProviderEnabledRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="SetLibraryArtworkProviderEnabledRequest"/> instances.</returns>
public List<SetLibraryArtworkProviderEnabledRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,48 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
/// <summary>
/// Fixture class for the <see cref="SetLibraryMetadataProviderEnabledRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="SetLibraryMetadataProviderEnabledRequest"/> instance with randomized test data.
/// </summary>
/// <param name="libraryId">Optional identifier of the media library.</param>
/// <param name="pluginId">Optional identifier of the plugin.</param>
/// <param name="isEnabled">Optional value indicating whether the metadata provider is enabled.</param>
/// <returns>A configured <see cref="SetLibraryMetadataProviderEnabledRequest"/> instance.</returns>
public SetLibraryMetadataProviderEnabledRequest Create(
Guid? libraryId = null,
Guid? pluginId = null,
bool? isEnabled = null)
{
return new SetLibraryMetadataProviderEnabledRequest(
LibraryId: libraryId ?? Guid.NewGuid(),
PluginId: pluginId ?? Guid.NewGuid(),
IsEnabled: isEnabled ?? _faker.Random.Bool()
);
}
/// <summary>
/// Creates multiple <see cref="SetLibraryMetadataProviderEnabledRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="SetLibraryMetadataProviderEnabledRequest"/> instances.</returns>
public List<SetLibraryMetadataProviderEnabledRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,11 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Seed;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Infrastructure.Core.Security;
using Microsoft.Extensions.DependencyInjection;
using System;
@@ -33,6 +35,8 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
PropertyNameCaseInsensitive = true
};
private readonly UserEntityFixture _userEntityFixture = new();
private readonly PermissionEntityFixture _permissionEntityFixture = new();
private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
private readonly LoginRequestFixture _loginRequestFixture = new();
/// <summary>
@@ -43,17 +47,18 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
/// <summary>
/// Creates an HTTP client with authentication headers and a test user
/// </summary>
/// <param name="permissions">The permissions granted directly to the test user, if any.</param>
/// <returns>An HTTP client configured with auth headers</returns>
public async Task<HttpClient> CreateAuthenticatedClientAsync()
public async Task<HttpClient> CreateAuthenticatedClientAsync(params AuthorizationPermission[] permissions)
{
HttpClient client = CreateClient();
TestUsername = $"testuser_{Guid.NewGuid()}";
// add the X-Forwarded-For header
// Add the X-Forwarded-For header.
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}");
// perform authentication
await CreateAndAuthenticateUser(client);
// Perform authentication.
await CreateAndAuthenticateUser(client, permissions);
return client;
}
@@ -62,20 +67,23 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
/// Creates and authenticates a test user.
/// </summary>
/// <param name="client">The HTTP client to configure with auth.</param>
/// <param name="permissions">The permissions granted directly to the test user.</param>
/// <returns>The created user entity.</returns>
private async Task<UserEntity> CreateAndAuthenticateUser(HttpClient client)
private async Task<UserEntity> CreateAndAuthenticateUser(HttpClient client, AuthorizationPermission[] permissions)
{
using IServiceScope scope = Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// create test user
// Create test user, with the permissions granted directly to it.
UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!"));
user.TotpSecret = null;
foreach (AuthorizationPermission permission in permissions)
user.UserPermissions.Add(_userPermissionEntityFixture.Create(user, _permissionEntityFixture.Create(permissionName: permission, createdBy: user.Id)));
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
// authenticate user
// Authenticate user.
LoginRequest loginRequest = _loginRequestFixture.Create(
username: user.Username,
password: "TestPass123!",
@@ -86,7 +94,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
// set auth header for subsequent requests
// Set auth header for subsequent requests.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
return user;
@@ -101,11 +109,11 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
HttpClient client = CreateClient();
TestUsername = $"testuser_{Guid.NewGuid()}";
// add the X-Forwarded-For header
// Add the X-Forwarded-For header.
client.DefaultRequestHeaders.Add("X-Forwarded-For",
$"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}");
// create and authenticate admin user
// Create and authenticate admin user.
await CreateAndAuthenticateAdminUser(client);
return client;
@@ -122,20 +130,20 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService<IDataSeedService>();
// create test user
// Create test user.
UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!"));
user.TotpSecret = null;
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
// set up admin permissions and roles
// Set up admin permissions and roles.
await dataSeedService.SetDefaultAuthorizationPermissionsAsync(user.Id, CancellationToken.None);
await dataSeedService.SetDefaultAuthorizationRolesAsync(user.Id, CancellationToken.None);
await dataSeedService.SetAdminRolePermissionsAsync(user.Id, CancellationToken.None);
await dataSeedService.SetAdminRoleToAdministratorAccount(user.Id, CancellationToken.None);
// authenticate user
// Authenticate user.
LoginRequest loginRequest = _loginRequestFixture.Create(
username: user.Username,
password: "TestPass123!",
@@ -146,7 +154,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
// set auth header for subsequent requests
// Set auth header for subsequent requests.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
return user;
@@ -10,6 +10,7 @@ using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -32,6 +33,7 @@ public class AddLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
@@ -359,6 +361,128 @@ public class AddLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
[Fact]
public async Task AddLibrary_WhenAProviderChoiceNamesAnUnsupportedPlugin_ShouldReturnValidationProblemAndNotPersist()
{
// Arrange
string title = "Unsupported Provider Library";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "Book",
contentLocations: ["C:/Media"],
coverImage: null,
metadataProviders: [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)]
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
await AssertValidationProblemAsync(response, "PluginNotSupportedForLibraryType");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
[Fact]
public async Task AddLibrary_WhenAProviderChoiceIsNull_ShouldReturnValidationProblemAndNotPersist()
{
// Arrange
string title = "Null Provider Choice Library";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "Book",
contentLocations: ["C:/Media"],
coverImage: null,
bookReaders: [null]
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
await AssertValidationProblemAsync(response, "PluginIdCannotBeEmpty");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
[Fact]
public async Task AddLibrary_WhenAPathTemplatePartIsNull_ShouldReturnValidationProblemAndNotPersist()
{
// Arrange
string title = "Null Path Template Part Library";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "Book",
contentLocations: ["C:/Media"],
coverImage: null,
pathTemplateParts: [null]
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
await AssertValidationProblemAsync(response, "PathTemplatePartKindNotSupportedForLibraryType");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
[Fact]
public async Task AddLibrary_WhenProviderPluginIdsAreDuplicated_ShouldReturnValidationProblemAndNotPersist()
{
// Arrange
string title = "Duplicated Provider Library";
Guid pluginId = Guid.NewGuid();
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "Book",
contentLocations: ["C:/Media"],
coverImage: null,
bookReaders: [_libraryProviderSelectionRequestFixture.Create(pluginId: pluginId), _libraryProviderSelectionRequestFixture.Create(pluginId: pluginId, isEnabled: false)]
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
await AssertValidationProblemAsync(response, "PluginIdsMustBeUnique");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
[Fact]
public async Task AddLibrary_WhenProviderChoicesAreEmpty_ShouldCreateLibrary()
{
// Arrange
string title = "Empty Provider Choices Library";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "Book",
contentLocations: ["C:/Media"],
coverImage: null,
metadataProviders: [],
artworkProviders: [],
bookReaders: []
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.True(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
/// <summary>
/// Asserts that <paramref name="response"/> carries the standard validation problem of the add library route.
/// </summary>
@@ -395,12 +519,12 @@ public class AddLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// clear junction tables first
// Clear junction tables first.
await dbContext.Set<Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity>().ExecuteDeleteAsync();
// then clear main tables
// Then clear main tables.
await dbContext.Set<Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity>().ExecuteDeleteAsync();
await dbContext.Set<Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity>().ExecuteDeleteAsync();
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.DeleteLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -54,7 +55,7 @@ public class DeleteLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
_client = await _apiFactory.CreateAuthenticatedClientAsync(AuthorizationPermission.CanCreateLibraries);
}
[Fact]
@@ -6,6 +6,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.UpdateLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -41,6 +42,7 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateLibraryEndpointTests"/> class.
@@ -57,7 +59,7 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
_client = await _apiFactory.CreateAuthenticatedClientAsync(AuthorizationPermission.CanCreateLibraries);
}
[Fact]
@@ -69,7 +71,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title");
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -105,7 +106,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
Guid libraryId = Guid.NewGuid();
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: Guid.NewGuid(),
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -144,7 +144,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: false, completionThresholdPercentage: null);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -185,7 +184,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -226,7 +224,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -267,7 +264,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: false, completionThresholdPercentage: null);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -308,7 +304,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -345,7 +340,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -373,6 +367,69 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateLibrary_WhenAProviderChoiceNamesAnUnsupportedPlugin_ShouldReturnValidationProblemAndKeepTheStoredLibrary()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 70,
artworkProviders: [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)]
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
await AssertValidationProblemAsync(response, $"/api/v1/libraries/{libraryId}", "PluginNotSupportedForLibraryType");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal("Original Title", storedLibrary!.Title);
}
[Fact]
public async Task UpdateLibrary_WhenProviderChoicesAreEmpty_ShouldUpdateTheLibrary()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 70,
metadataProviders: [],
artworkProviders: [],
bookReaders: []
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
response.EnsureSuccessStatusCode();
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal("Updated Title", storedLibrary!.Title);
}
/// <summary>
/// Asserts that <paramref name="response"/> carries the standard validation problem of the update library route.
/// </summary>
@@ -0,0 +1,112 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.Plugins;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryTypeArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryTypeArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Theory]
[InlineData("Book")]
[InlineData("music")] // The casing of the type is ignored.
public async Task GetLibraryTypeArtworkProviders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableProviders(string libraryType)
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<LibraryArtworkProviderResponse>? providers = JsonSerializer.Deserialize<List<LibraryArtworkProviderResponse>>(content, _jsonOptions);
Assert.NotNull(providers);
// The test host loads no plugins, so no provider supports the type; every provider that is returned starts disabled.
Assert.All(providers!, provider => Assert.False(provider.IsEnabled));
}
[Fact]
public async Task GetLibraryTypeArtworkProviders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult()
{
// Arrange
string libraryType = "NotARealLibraryType";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, 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.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
Assert.Equal($"/api/v1/libraries/artwork-providers/{libraryType}", problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
}
[Fact]
public async Task GetLibraryTypeArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/artwork-providers/Book");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,112 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.Plugins;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryTypeBookReadersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeBookReadersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryTypeBookReadersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Theory]
[InlineData("Book")]
[InlineData("music")] // The casing of the type is ignored.
public async Task GetLibraryTypeBookReaders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableReaders(string libraryType)
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<LibraryBookReaderResponse>? readers = JsonSerializer.Deserialize<List<LibraryBookReaderResponse>>(content, _jsonOptions);
Assert.NotNull(readers);
// The test host loads no plugins, so no reader supports the type; every reader that is returned starts disabled.
Assert.All(readers!, reader => Assert.False(reader.IsEnabled));
}
[Fact]
public async Task GetLibraryTypeBookReaders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult()
{
// Arrange
string libraryType = "NotARealLibraryType";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, 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.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
Assert.Equal($"/api/v1/libraries/book-readers/{libraryType}", problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
}
[Fact]
public async Task GetLibraryTypeBookReaders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/book-readers/Book");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,112 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.Plugins;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryTypeMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryTypeMetadataProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Theory]
[InlineData("Book")]
[InlineData("music")] // The casing of the type is ignored.
public async Task GetLibraryTypeMetadataProviders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableProviders(string libraryType)
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<LibraryMetadataProviderResponse>? providers = JsonSerializer.Deserialize<List<LibraryMetadataProviderResponse>>(content, _jsonOptions);
Assert.NotNull(providers);
// The test host loads no plugins, so no provider supports the type; every provider that is returned starts disabled.
Assert.All(providers!, provider => Assert.False(provider.IsEnabled));
}
[Fact]
public async Task GetLibraryTypeMetadataProviders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult()
{
// Arrange
string libraryType = "NotARealLibraryType";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, 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.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
Assert.Equal($"/api/v1/libraries/metadata-providers/{libraryType}", problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
}
[Fact]
public async Task GetLibraryTypeMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/metadata-providers/Book");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -1,140 +0,0 @@
#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();
}
}
@@ -1,140 +0,0 @@
#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.ReorderLibraryMetadataProviders;
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.ReorderLibraryMetadataProviders;
/// <summary>
/// Contains integration tests for the <see cref="ReorderLibraryMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ReorderLibraryMetadataProvidersEndpointTests(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 ReorderLibraryMetadataProviders_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);
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(
libraryId: libraryId,
pluginIds: [pluginIdB, pluginIdA]
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-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<LibraryMetadataProviderConfigurationEntity> configurations = await dbContext.LibraryMetadataProviderConfigurations
.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="LibraryMetadataProviderConfigurationEntity"/> 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.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.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();
}
}
@@ -1,156 +0,0 @@
#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();
}
}
@@ -1,199 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
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.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
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.SetLibraryBookReaderEnabled;
/// <summary>
/// Contains integration tests for the <see cref="SetLibraryBookReaderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new();
private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryBookReaderEnabledEndpointTests(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 SetLibraryBookReaderEnabled_WhenNoConfigurationExists_ShouldCreateIt()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginId = Guid.NewGuid();
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryBookReaderConfigurationEntity? configuration = await dbContext.LibraryBookReaderConfigurations
.FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
Assert.NotNull(configuration);
Assert.True(configuration!.IsEnabled);
}
[Fact]
public async Task SetLibraryBookReaderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginId = Guid.NewGuid();
await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false);
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryBookReaderConfigurationEntity configuration = await dbContext.LibraryBookReaderConfigurations
.SingleAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
Assert.True(configuration.IsEnabled);
}
[Fact]
public async Task SetLibraryBookReaderEnabled_WhenLibraryIsNotOwned_ShouldReturnForbidden()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, otherUserId);
Guid pluginId = Guid.NewGuid();
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task SetLibraryBookReaderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Seeds a library 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>
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: Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary.LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a book reader configuration for the library and plugin.
/// </summary>
/// <param name="libraryId">The Id of the library.</param>
/// <param name="pluginId">The Id of the plugin.</param>
/// <param name="isEnabled">Whether the book reader is enabled.</param>
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryBookReaderConfigurations.Add(_libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: isEnabled));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a user that is not the authenticated one and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <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();
}
}
@@ -1,156 +0,0 @@
#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.SetLibraryMetadataProviderEnabled;
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.SetLibraryMetadataProviderEnabled;
/// <summary>
/// Contains integration tests for the <see cref="SetLibraryMetadataProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryMetadataProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryMetadataProviderEnabledEndpointTests(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 SetLibraryMetadataProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginId = Guid.NewGuid();
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-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>();
LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations
.FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
Assert.NotNull(configuration);
Assert.True(configuration!.IsEnabled);
Assert.Equal(1, configuration.Rank);
}
[Fact]
public async Task SetLibraryMetadataProviderEnabled_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);
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-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>();
LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations
.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="LibraryMetadataProviderConfigurationEntity"/> 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.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.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,96 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryTypeArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly LibraryArtworkProviderDtoFixture _libraryArtworkProviderDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetLibraryTypeArtworkProvidersEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetLibraryTypeArtworkProviders_WhenCalledByAuthenticatedUser_ShouldReturnProvidersJson()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
string libraryType = "Book";
LibraryArtworkProviderDto[] expectedProviders =
[
_libraryArtworkProviderDtoFixture.Create(name: "EPUB Reader", isEnabled: false)
];
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{libraryType}", expectedProviders);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-artwork-providers/{libraryType}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
JsonElement data = json.RootElement.GetProperty("data");
Assert.Equal(1, data.GetArrayLength());
Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString());
}
[Fact]
public async Task GetLibraryTypeArtworkProviders_WhenCalled_ShouldRequestProvidersFromApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
string libraryType = "Book";
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{libraryType}", Array.Empty<LibraryArtworkProviderDto>());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-artwork-providers/{libraryType}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
// Assert
response.EnsureSuccessStatusCode();
Assert.Contains($"libraries/artwork-providers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task GetLibraryTypeArtworkProviders_WhenNotAuthenticated_ShouldRedirectToLogin()
{
// Arrange
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-artwork-providers/Book");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
}
}
@@ -0,0 +1,96 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryTypeBookReadersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeBookReadersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetLibraryTypeBookReadersEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetLibraryTypeBookReaders_WhenCalledByAuthenticatedUser_ShouldReturnBookReadersJson()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
string libraryType = "Book";
LibraryBookReaderDto[] expectedReaders =
[
_libraryBookReaderDtoFixture.Create(name: "EPUB Reader", isEnabled: false)
];
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{libraryType}", expectedReaders);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-book-readers/{libraryType}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
JsonElement data = json.RootElement.GetProperty("data");
Assert.Equal(1, data.GetArrayLength());
Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString());
}
[Fact]
public async Task GetLibraryTypeBookReaders_WhenCalled_ShouldRequestBookReadersFromApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
string libraryType = "Book";
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{libraryType}", Array.Empty<LibraryBookReaderDto>());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-book-readers/{libraryType}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
// Assert
response.EnsureSuccessStatusCode();
Assert.Contains($"libraries/book-readers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task GetLibraryTypeBookReaders_WhenNotAuthenticated_ShouldRedirectToLogin()
{
// Arrange
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-book-readers/Book");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
}
}
@@ -0,0 +1,96 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryTypeMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly LibraryMetadataProviderDtoFixture _libraryMetadataProviderDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetLibraryTypeMetadataProvidersEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetLibraryTypeMetadataProviders_WhenCalledByAuthenticatedUser_ShouldReturnProvidersJson()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
string libraryType = "Book";
LibraryMetadataProviderDto[] expectedProviders =
[
_libraryMetadataProviderDtoFixture.Create(name: "EPUB Reader", isEnabled: false)
];
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{libraryType}", expectedProviders);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-metadata-providers/{libraryType}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
JsonElement data = json.RootElement.GetProperty("data");
Assert.Equal(1, data.GetArrayLength());
Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString());
}
[Fact]
public async Task GetLibraryTypeMetadataProviders_WhenCalled_ShouldRequestProvidersFromApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
string libraryType = "Book";
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{libraryType}", Array.Empty<LibraryMetadataProviderDto>());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-metadata-providers/{libraryType}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
// Assert
response.EnsureSuccessStatusCode();
Assert.Contains($"libraries/metadata-providers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task GetLibraryTypeMetadataProviders_WhenNotAuthenticated_ShouldRedirectToLogin()
{
// Arrange
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-metadata-providers/Book");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
}
}
@@ -1,7 +1,10 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index;
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
@@ -17,6 +20,7 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Manage
public class LibrariesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibrariesIndexViewEndpointTests"/> class.
@@ -44,8 +48,8 @@ public class LibrariesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
}
[Theory]
[InlineData("/en-us/libraries/manage", "%2Fen-us%2Flibraries%2Fmanage")] // plain page
[InlineData("/en-us/libraries/manage?tab=scans", "%2Fen-us%2Flibraries%2Fmanage%3Ftab%3Dscans")] // query string is kept
[InlineData("/en-us/libraries/manage", "%2Fen-us%2Flibraries%2Fmanage")] // Plain page.
[InlineData("/en-us/libraries/manage?tab=scans", "%2Fen-us%2Flibraries%2Fmanage%3Ftab%3Dscans")] // Query string is kept.
public async Task LibrariesIndexView_WhenNavigatedToWithoutAuthentication_ShouldRedirectToLoginWithRequestedPageAsReturnUrl(string requestedUrl, string expectedEncodedReturnUrl)
{
// Arrange
@@ -60,4 +64,45 @@ public class LibrariesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal($"http://localhost/en-us/auth/login?returnUrl={expectedEncodedReturnUrl}", response.Headers.Location!.ToString());
}
[Theory]
[InlineData("User", true, "true")] // The permission lets a user manage the libraries they own.
[InlineData("User", false, "false")] // Without the permission, a user cannot change even the libraries they own.
[InlineData("Admin", false, "true")] // An administrator can manage every library, with or without the permission.
public async Task LibrariesIndexView_WhenRendered_ShouldOfferTheEditAndDeleteActionsOnlyToUsersAllowedToManageLibraries(string role, bool hasManagePermission, string expectedCanManageLibraries)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(
userId: Guid.NewGuid(),
role: role,
permissions: hasManagePermission ? [AuthorizationPermission.CanCreateLibraries] : []);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage");
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Assert.Contains($"const canManageLibraries = {expectedCanManageLibraries};", content);
}
[Fact]
public async Task LibrariesIndexView_WhenRenderedInACultureWithNonAsciiLabels_ShouldInjectTheScriptLabelsAsJson()
{
// Arrange
// Razor would encode the non-ASCII letters of a raw label as HTML entities, which the browser shows literally inside a script, while JSON escapes them
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync("/ro-ro/libraries/manage");
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("\"LibraryDeleted\":\"Biblioteca a fost \\u0219tears\\u0103!\"", content);
Assert.DoesNotContain("&#x219;tears", content);
}
}
@@ -1,71 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderArtworkProviders;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderArtworkProviders;
/// <summary>
/// Contains integration tests for the <see cref="ReorderArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderArtworkProvidersEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public ReorderArtworkProvidersEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task ReorderArtworkProviders_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldReorderProvidersAndReturnSuccess()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid firstPluginId = Guid.NewGuid();
Guid secondPluginId = Guid.NewGuid();
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(
libraryId: libraryId,
pluginIds: [firstPluginId, secondPluginId]
);
string expectedEndpoint = $"libraries/{libraryId}/artwork-providers/reorder";
_apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-artwork-providers")
{
Content = JsonContent.Create(request)
};
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
}
}
@@ -1,71 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderMetadataProviders;
/// <summary>
/// Contains integration tests for the <see cref="ReorderMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderMetadataProvidersEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public ReorderMetadataProvidersEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task ReorderMetadataProviders_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldReorderProvidersAndReturnSuccess()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid firstPluginId = Guid.NewGuid();
Guid secondPluginId = Guid.NewGuid();
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(
libraryId: libraryId,
pluginIds: [firstPluginId, secondPluginId]
);
string expectedEndpoint = $"libraries/{libraryId}/metadata-providers/reorder";
_apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-metadata-providers")
{
Content = JsonContent.Create(request)
};
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
}
}
@@ -64,6 +64,43 @@ public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
}
[Fact]
public async Task SaveLibrary_WhenAProviderChoiceHasNoEnabledState_ShouldForwardItWithoutAState()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid pluginId = Guid.NewGuid();
LibraryDto request = _libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book");
request.Id = null;
_apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// The choice is sent without its enabled state, the way a caller that only reorders the providers would send it.
HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item")
{
Content = JsonContent.Create(new
{
request.Title,
request.LibraryType,
request.ContentLocations,
MetadataProviders = new[] { new { PluginId = pluginId } }
})
};
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
// Assert
response.EnsureSuccessStatusCode();
(string _, object? data) = Assert.Single(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
LibraryDto forwardedLibrary = Assert.IsType<LibraryDto>(data);
LibraryProviderSelectionDto forwardedChoice = Assert.Single(forwardedLibrary.MetadataProviders!);
Assert.Equal(pluginId, forwardedChoice.PluginId);
Assert.Null(forwardedChoice.IsEnabled);
}
[Fact]
public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldReturnBadRequest()
{
@@ -1,71 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetArtworkProviderEnabled;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetArtworkProviderEnabled;
/// <summary>
/// Contains integration tests for the <see cref="SetArtworkProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetArtworkProviderEnabledEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetArtworkProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public SetArtworkProviderEnabledEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task SetArtworkProviderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableProviderAndReturnSuccess()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(
libraryId: libraryId,
pluginId: pluginId,
isEnabled: true
);
string expectedEndpoint = $"libraries/{libraryId}/artwork-providers/{pluginId}/enabled";
_apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-artwork-provider-enabled")
{
Content = JsonContent.Create(request)
};
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
}
}
@@ -1,87 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Common;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetBookReaderEnabled;
/// <summary>
/// Contains integration tests for the <see cref="SetBookReaderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetBookReaderEnabledEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetBookReaderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public SetBookReaderEnabledEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task SetBookReaderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableReaderAndReturnSuccess()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
string expectedEndpoint = $"libraries/{libraryId}/book-readers/{pluginId}/enabled";
_apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled")
{
Content = JsonContent.Create(request)
};
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
}
[Fact]
public async Task SetBookReaderEnabled_WhenNotAuthenticated_ShouldRedirectToLogin()
{
// Arrange
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create();
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled")
{
Content = JsonContent.Create(request)
};
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Act
HttpResponseMessage response = await anonymousClient.SendAsync(updateRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
}
}
@@ -1,71 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetMetadataProviderEnabled;
/// <summary>
/// Contains integration tests for the <see cref="SetMetadataProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetMetadataProviderEnabledEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetMetadataProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public SetMetadataProviderEnabledEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task SetMetadataProviderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableProviderAndReturnSuccess()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(
libraryId: libraryId,
pluginId: pluginId,
isEnabled: true
);
string expectedEndpoint = $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled";
_apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-metadata-provider-enabled")
{
Content = JsonContent.Create(request)
};
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
}
}
@@ -9,6 +9,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Common.Interceptors;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.Security;
using Microsoft.AspNetCore.Authentication.JwtBearer;
@@ -45,6 +46,8 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
private readonly UserEntityFixture _userEntityFixture = new();
private readonly RoleEntityFixture _roleEntityFixture = new();
private readonly UserRoleEntityFixture _userRoleEntityFixture = new();
private readonly PermissionEntityFixture _permissionEntityFixture = new();
private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=";
@@ -55,11 +58,11 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
/// </summary>
public LuminaApiFactory()
{
// each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another;
// Each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another;
// the shared cache allows each DbContext to open its own pooled connection to the same database, instead of sharing a single connection,
// which would otherwise serialize every request on one connection and cause nested transaction errors between requests
// which would otherwise serialize every request on one connection and cause nested transaction errors between requests.
_sharedInMemoryConnectionString = string.Format(SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX, Guid.NewGuid());
// keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped
// Keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped.
_connection = new SqliteConnection(_sharedInMemoryConnectionString);
_connection.Open();
}
@@ -202,6 +205,40 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
return (userId, username);
}
/// <summary>
/// Creates a test user that holds a single permission directly, authenticates it on <paramref name="client"/>, and returns its Id and username.
/// </summary>
/// <param name="client">The HTTP client to configure with authentication headers.</param>
/// <param name="permission">The permission granted to the created user.</param>
/// <returns>The Id and username of the created test user.</returns>
public async Task<(Guid UserId, string Username)> CreateAndAuthenticateUserWithPermissionAsync(HttpClient client, AuthorizationPermission permission)
{
// A unique X-Forwarded-For isolates rate limiting state per test.
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("X-Forwarded-For", GetUniqueTestIp());
using IServiceScope scope = Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"testuser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
user.TotpSecret = null;
dbContext.Users.Add(user);
PermissionEntity permissionEntity = _permissionEntityFixture.Create(permissionName: permission);
dbContext.Permissions.Add(permissionEntity);
dbContext.UserPermissions.Add(_userPermissionEntityFixture.Create(user, permissionEntity));
await dbContext.SaveChangesAsync();
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
return (userId, username);
}
/// <summary>
/// Removes a test user and its owned libraries from the database.
/// </summary>
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
@@ -60,12 +61,12 @@ public class DeleteLibraryEndpointTests : IClassFixture<LuminaApiFactory>
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task DeleteLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId)
{
// Arrange
// authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized
// Authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized.
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
await SeedLibraryAsync(userId);
@@ -74,10 +75,9 @@ public class DeleteLibraryEndpointTests : IClassFixture<LuminaApiFactory>
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}");
// Assert
// note: the {id} 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
// Note: the {id} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler.
// The 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).
// 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);
@@ -86,6 +86,68 @@ public class DeleteLibraryEndpointTests : IClassFixture<LuminaApiFactory>
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task DeleteLibrary_WhenTheOwnerLacksTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
{
// Arrange
// The created user holds no permission, so it owns the library without being allowed to change it.
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, 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.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.Libraries.FindAsync(libraryId));
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
}
[Fact]
public async Task DeleteLibrary_WhenNonOwnerHoldsTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
{
// Arrange
// Ownership and the manage permission are both required, so a user that holds the permission must not delete a library it does not own.
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
(Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserWithPermissionAsync(client, AuthorizationPermission.CanCreateLibraries);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, 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.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.Libraries.FindAsync(libraryId));
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(attackerUsername);
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
@@ -4,6 +4,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Manage
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
@@ -13,6 +14,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Nodes;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.UpdateLibrary;
@@ -49,7 +51,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
string libraryId = Guid.NewGuid().ToString();
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: Guid.NewGuid(),
userId: Guid.NewGuid(),
title: "Updated Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -79,8 +80,8 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task UpdateLibrary_WithSQLInjectionInTitle_ShouldNotLeakOrError(string maliciousTitle)
{
// Arrange
@@ -90,7 +91,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
await SeedLibraryAsync(libraryId, userId);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: maliciousTitle,
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -106,7 +106,7 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
// the malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim
// The malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
@@ -123,10 +123,10 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
}
[Theory]
[InlineData(-1)] // just below the allowed range
[InlineData(101)] // just above the allowed range
[InlineData(int.MinValue)] // lowest possible value
[InlineData(int.MaxValue)] // highest possible value
[InlineData(-1)] // Just below the allowed range.
[InlineData(101)] // Just above the allowed range.
[InlineData(int.MinValue)] // Lowest possible value.
[InlineData(int.MaxValue)] // Highest possible value.
public async Task UpdateLibrary_WhenThresholdIsOutsideAllowedRange_ShouldRejectTheRequestAndKeepTheStoredSettings(int completionThresholdPercentage)
{
// Arrange
@@ -136,7 +136,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -177,7 +176,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -223,7 +221,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
(Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: ownerId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -275,6 +272,129 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
await _apiFactory.RemoveTestUserAsync(ownerUsername);
}
[Fact]
public async Task UpdateLibrary_WhenNonOwnerHoldsTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
{
// Arrange
// Ownership and the manage permission are both required, so a user that holds the permission must not update a library it does not own.
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, ownerId, title: "Original Title");
(Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserWithPermissionAsync(client, AuthorizationPermission.CanCreateLibraries);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, 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.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal("Original Title", storedLibrary!.Title);
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(attackerUsername);
}
[Fact]
public async Task UpdateLibrary_WhenTheOwnerLacksTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
{
// Arrange
// The created user holds no permission, so it owns the library without being allowed to change it.
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, ownerId, title: "Original Title");
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Updated Title",
libraryType: "Book",
contentLocations: ["C:/Media"],
coverImage: null
);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, 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.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal("Original Title", storedLibrary!.Title);
Assert.Equal(LibraryType.EBook, storedLibrary.LibraryType);
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
}
[Fact]
public async Task UpdateLibrary_WhenBodyNamesAnotherOwner_ShouldKeepTheStoredOwner()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, ownerId);
HttpClient client = _apiFactory.CreateClient();
Guid adminId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true
);
// The request has no owner, so the claimed owner is added to the raw body, the way a crafted request would carry it.
JsonObject body = JsonSerializer.SerializeToNode(request, new JsonSerializerOptions(JsonSerializerDefaults.Web))!.AsObject();
body["userId"] = adminId.ToString();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", body);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal(ownerId, storedLibrary!.UserId);
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveAdminUserAsync(adminId);
}
/// <summary>
/// Asserts that <paramref name="response"/> carries the standard validation problem of the update library route.
/// </summary>
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
/// <summary>
/// Contains security tests for the <see cref="GetLibraryTypeArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryTypeArtworkProvidersEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetLibraryTypeArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryType = "Music";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}");
// 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/artwork-providers/{libraryType}", 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 SQL injection.
[InlineData("Music; rm -rf /")] // Command injection.
[InlineData("$(whoami)")] // Command substitution injection.
[InlineData("`whoami`")] // Backtick command injection.
[InlineData("{0}{1}{0}")] // Template/placeholder injection.
[InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal.
[InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal.
public async Task GetLibraryTypeArtworkProviders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/artwork-providers/{Uri.EscapeDataString(maliciousLibraryType)}");
string content = await response.Content.ReadAsStringAsync();
// Assert
// An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response
// must stay generic: the failed request leaks no database, filesystem or framework internals.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
Assert.StartsWith("/api/v1/libraries/artwork-providers/", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
}
}
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
/// <summary>
/// Contains security tests for the <see cref="GetLibraryTypeBookReadersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeBookReadersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryTypeBookReadersEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetLibraryTypeBookReaders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryType = "Music";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}");
// 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/book-readers/{libraryType}", 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 SQL injection.
[InlineData("Music; rm -rf /")] // Command injection.
[InlineData("$(whoami)")] // Command substitution injection.
[InlineData("`whoami`")] // Backtick command injection.
[InlineData("{0}{1}{0}")] // Template/placeholder injection.
[InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal.
[InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal.
public async Task GetLibraryTypeBookReaders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/book-readers/{Uri.EscapeDataString(maliciousLibraryType)}");
string content = await response.Content.ReadAsStringAsync();
// Assert
// An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response
// must stay generic: the failed request leaks no database, filesystem or framework internals.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
Assert.StartsWith("/api/v1/libraries/book-readers/", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
}
}
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
/// <summary>
/// Contains security tests for the <see cref="GetLibraryTypeMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryTypeMetadataProvidersEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetLibraryTypeMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryType = "Music";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}");
// 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/metadata-providers/{libraryType}", 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 SQL injection.
[InlineData("Music; rm -rf /")] // Command injection.
[InlineData("$(whoami)")] // Command substitution injection.
[InlineData("`whoami`")] // Backtick command injection.
[InlineData("{0}{1}{0}")] // Template/placeholder injection.
[InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal.
[InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal.
public async Task GetLibraryTypeMetadataProviders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/metadata-providers/{Uri.EscapeDataString(maliciousLibraryType)}");
string content = await response.Content.ReadAsStringAsync();
// Assert
// An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response
// must stay generic: the failed request leaks no database, filesystem or framework internals.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
Assert.StartsWith("/api/v1/libraries/metadata-providers/", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
}
}
@@ -1,133 +0,0 @@
#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 <see cref="ReorderLibraryArtworkProvidersEndpoint"/> class.
/// </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();
}
}
@@ -1,133 +0,0 @@
#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.ReorderLibraryMetadataProviders;
/// <summary>
/// Contains security tests for the <see cref="ReorderLibraryMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ReorderLibraryMetadataProvidersEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ReorderLibraryMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(
libraryId: Guid.NewGuid(),
pluginIds: [Guid.NewGuid()]
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-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}/metadata-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 ReorderLibraryMetadataProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId)
{
// Arrange
// authenticate with an admin user and seed a library with metadata 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}/metadata-providers/reorder",
new { libraryId = 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="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="LibraryMetadataProviderConfigurationEntity"/> 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.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank));
await dbContext.SaveChangesAsync();
}
}
@@ -1,126 +0,0 @@
#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 <see cref="SetLibraryArtworkProviderEnabledEndpoint"/> class.
/// </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();
}
}
@@ -1,77 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
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.SetLibraryBookReaderEnabled;
/// <summary>
/// Contains security tests for the <see cref="SetLibraryBookReaderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryBookReaderEnabledEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task SetLibraryBookReaderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{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("Authentication failed", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE LibraryBookReaderConfigurations--")] // destructive injection
public async Task SetLibraryBookReaderEnabled_WithSQLInjectionInPluginId_ShouldNotLeakDatabaseDetails(string maliciousPluginId)
{
// Arrange
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: Guid.NewGuid(), pluginId: Guid.NewGuid(), isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/book-readers/{Uri.EscapeDataString(maliciousPluginId)}/enabled", request);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
}
@@ -1,126 +0,0 @@
#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.SetLibraryMetadataProviderEnabled;
/// <summary>
/// Contains security tests for the <see cref="SetLibraryMetadataProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryMetadataProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryMetadataProviderEnabledEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task SetLibraryMetadataProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
string pluginId = Guid.NewGuid().ToString();
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create();
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-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}/metadata-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 SetLibraryMetadataProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId)
{
// Arrange
// authenticate with an admin user and seed a library with a metadata 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);
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), isEnabled: true);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/metadata-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="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="LibraryMetadataProviderConfigurationEntity"/> 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.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false));
await dbContext.SaveChangesAsync();
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.AddLibrary;
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
@@ -15,6 +16,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen
public class AddLibraryViewEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="AddLibraryViewEndpointTests"/> class.
@@ -39,4 +41,20 @@ public class AddLibraryViewEndpointTests : IClassFixture<LuminaWebFactory>
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
}
[Fact]
public async Task AddLibraryView_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDenied()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/item");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Contains("access-denied", response.Headers.Location!.ToString());
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary;
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
@@ -17,6 +18,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen
public class DeleteLibraryEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DeleteLibraryEndpointTests"/> class.
@@ -64,6 +66,47 @@ public class DeleteLibraryEndpointTests : IClassFixture<LuminaWebFactory>
Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
}
[Fact]
public async Task DeleteLibrary_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDeniedWithoutDeletingTheLibrary()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
Guid libraryId = Guid.NewGuid();
HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId);
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Contains("access-denied", response.Headers.Location!.ToString());
Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
}
[Fact]
public async Task DeleteLibrary_WhenAnAdministratorLacksTheManagePermission_ShouldForwardTheDeletion()
{
// Arrange
// The API lets administrators delete any library, so the Web must not refuse them for lacking the permission.
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
Guid libraryId = Guid.NewGuid();
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}");
HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId);
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
}
/// <summary>
/// Builds the delete request for the library identified by <paramref name="libraryId"/>.
/// </summary>
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.EditLibrary;
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
@@ -15,6 +16,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen
public class EditLibraryViewEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="EditLibraryViewEndpointTests"/> class.
@@ -41,4 +43,22 @@ public class EditLibraryViewEndpointTests : IClassFixture<LuminaWebFactory>
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
}
[Fact]
public async Task EditLibraryView_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDeniedWithoutLoadingTheLibrary()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
Guid libraryId = Guid.NewGuid();
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Contains("access-denied", response.Headers.Location!.ToString());
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
}
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
using System.Net;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
/// <summary>
/// Contains security tests for the <see cref="GetLibraryTypeArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetLibraryTypeArtworkProvidersEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetLibraryTypeArtworkProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-library-type-artwork-providers/Book");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.Contains("artwork-providers", StringComparison.Ordinal));
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task GetLibraryTypeArtworkProviders_WhenCalledWithInjectionInLibraryType_ShouldRemainSecure(string maliciousLibraryType)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{Uri.EscapeDataString(maliciousLibraryType)}", Array.Empty<LibraryArtworkProviderDto>());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/api-get-library-type-artwork-providers/{Uri.EscapeDataString(maliciousLibraryType)}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
}
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
using System.Net;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
/// <summary>
/// Contains security tests for the <see cref="GetLibraryTypeBookReadersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeBookReadersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetLibraryTypeBookReadersEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetLibraryTypeBookReaders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-library-type-book-readers/Book");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.Contains("book-readers", StringComparison.Ordinal));
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task GetLibraryTypeBookReaders_WhenCalledWithInjectionInLibraryType_ShouldRemainSecure(string maliciousLibraryType)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{Uri.EscapeDataString(maliciousLibraryType)}", Array.Empty<LibraryBookReaderDto>());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/api-get-library-type-book-readers/{Uri.EscapeDataString(maliciousLibraryType)}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
}
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
using System.Net;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
/// <summary>
/// Contains security tests for the <see cref="GetLibraryTypeMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetLibraryTypeMetadataProvidersEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetLibraryTypeMetadataProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-library-type-metadata-providers/Book");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.Contains("metadata-providers", StringComparison.Ordinal));
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task GetLibraryTypeMetadataProviders_WhenCalledWithInjectionInLibraryType_ShouldRemainSecure(string maliciousLibraryType)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{Uri.EscapeDataString(maliciousLibraryType)}", Array.Empty<LibraryMetadataProviderDto>());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/api-get-library-type-metadata-providers/{Uri.EscapeDataString(maliciousLibraryType)}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
}
}
@@ -1,89 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.ReorderMetadataProviders;
/// <summary>
/// Contains security tests for the <see cref="ReorderMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderMetadataProvidersEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public ReorderMetadataProvidersEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task ReorderMetadataProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
Guid libraryId = Guid.NewGuid();
HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId);
updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
// Act
HttpResponseMessage response = await client.SendAsync(updateRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/reorder");
}
[Fact]
public async Task ReorderMetadataProviders_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
Guid libraryId = Guid.NewGuid();
HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/reorder");
}
/// <summary>
/// Builds the update request that reorders the metadata providers of the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <returns>The configured update request.</returns>
private HttpRequestMessage CreateUpdateRequest(Guid libraryId)
{
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(
libraryId: libraryId,
pluginIds: [Guid.NewGuid(), Guid.NewGuid()]
);
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-metadata-providers")
{
Content = JsonContent.Create(request)
};
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return updateRequest;
}
}
@@ -1,7 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
@@ -20,6 +22,7 @@ public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly LibraryDtoFixture _libraryDtoFixture = new();
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SaveLibraryEndpointTests"/> class.
@@ -34,7 +37,7 @@ public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
ResetApiStub();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"));
@@ -50,7 +53,7 @@ public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
public async Task SaveLibrary_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequest()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
ResetApiStub();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"));
saveRequest.Headers.Remove("RequestVerificationToken");
@@ -64,11 +67,52 @@ public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
}
[Fact]
public async Task SaveLibrary_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDeniedWithoutSaving()
{
// Arrange
ResetApiStub();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"));
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Contains("access-denied", response.Headers.Location!.ToString());
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
}
[Fact]
public async Task SaveLibrary_WhenAnAdministratorLacksTheManagePermission_ShouldForwardTheSave()
{
// Arrange
// The API lets administrators save any library, so the Web must not refuse them for lacking the permission.
ResetApiStub();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
LibraryDto request = _libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book");
request.Id = null;
_apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType));
HttpRequestMessage saveRequest = CreateSaveRequest(request);
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
}
[Fact]
public async Task SaveLibrary_WhenCalledWithInjectionInLibraryTitle_ShouldRemainSecure()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
ResetApiStub();
LibraryDto request = _libraryDtoFixture.Create(title: "'; DROP TABLE Libraries--", libraryType: "Book");
request.Id = null;
_apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType));
@@ -85,6 +129,18 @@ public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
Assert.DoesNotContain("Exception", content);
}
/// <summary>
/// Resets the stubbed API client and restores the authorization state of an administrator with every permission, because the stub is shared by all the tests of the class.
/// </summary>
private void ResetApiStub()
{
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(
userId: Guid.NewGuid(),
role: "Admin",
permissions: Enum.GetValues<AuthorizationPermission>());
}
/// <summary>
/// Builds the save request that sends the given <paramref name="request"/> to the library save endpoint.
/// </summary>
@@ -1,81 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SetBookReaderEnabled;
/// <summary>
/// Contains security tests for the <see cref="SetBookReaderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetBookReaderEnabledEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetBookReaderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public SetBookReaderEnabledEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task SetBookReaderEnabled_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create();
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled")
{
Content = JsonContent.Create(request)
};
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Act
HttpResponseMessage response = await client.SendAsync(updateRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
}
[Fact]
public async Task SetBookReaderEnabled_WhenCalledWithoutAntiforgeryToken_ShouldReturnBadRequest()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create();
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled")
{
Content = JsonContent.Create(request)
};
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
}
@@ -1,93 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SetMetadataProviderEnabled;
/// <summary>
/// Contains security tests for the <see cref="SetMetadataProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetMetadataProviderEnabledEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetMetadataProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public SetMetadataProviderEnabledEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task SetMetadataProviderEnabled_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId, pluginId);
updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
// Act
HttpResponseMessage response = await client.SendAsync(updateRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled");
}
[Fact]
public async Task SetMetadataProviderEnabled_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId, pluginId);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled");
}
/// <summary>
/// Builds the update request that enables the metadata provider of the library identified by <paramref name="libraryId"/> and <paramref name="pluginId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <param name="pluginId">The Id of the plugin providing the metadata.</param>
/// <returns>The configured update request.</returns>
private HttpRequestMessage CreateUpdateRequest(Guid libraryId, Guid pluginId)
{
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(
libraryId: libraryId,
pluginId: pluginId,
isEnabled: true
);
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-metadata-provider-enabled")
{
Content = JsonContent.Create(request)
};
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return updateRequest;
}
}
@@ -1,10 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
@@ -16,6 +19,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class AddMediaLibraryRequestMappingTests
{
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new();
private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new();
[Fact]
@@ -245,4 +249,85 @@ public class AddMediaLibraryRequestMappingTests
Assert.False(result.ShouldTrackConsumptionProgress.Value);
Assert.Null(result.CompletionThresholdPercentage);
}
[Fact]
public void ToCommand_WhenProviderChoicesAreProvided_ShouldMapThemInOrder()
{
// Arrange
LibraryProviderSelectionRequest[] metadataProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true), _libraryProviderSelectionRequestFixture.Create(isEnabled: false)];
LibraryProviderSelectionRequest[] artworkProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: false)];
LibraryProviderSelectionRequest[] bookReaders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)];
AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
Assert.Equal(metadataProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.MetadataProviders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
Assert.Equal(artworkProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.ArtworkProviders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
Assert.Equal(bookReaders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.BookReaders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
}
[Fact]
public void ToCommand_WhenProviderChoicesAreNotProvided_ShouldMapThemAsNull()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
Assert.Null(result.MetadataProviders);
Assert.Null(result.ArtworkProviders);
Assert.Null(result.BookReaders);
}
[Fact]
public void ToCommand_WhenAProviderChoiceIsNull_ShouldMapItToAChoiceWithoutPluginId()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: [null], artworkProviders: [null], bookReaders: [null]);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
Assert.Equal(Guid.Empty, Assert.Single(result.MetadataProviders!).PluginId);
Assert.Null(result.MetadataProviders![0].IsEnabled);
Assert.Equal(Guid.Empty, Assert.Single(result.ArtworkProviders!).PluginId);
Assert.Equal(Guid.Empty, Assert.Single(result.BookReaders!).PluginId);
}
[Fact]
public void ToCommand_WhenAPathTemplatePartIsNull_ShouldMapItToAPartWithoutKind()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(pathTemplateParts: [null]);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
LibraryPathTemplatePartDto part = Assert.Single(result.PathTemplateParts!);
Assert.Null(part.Kind);
Assert.Null(part.Representation);
Assert.False(part.IsOptional);
}
[Fact]
public void ToCommand_WhenAProviderChoiceHasNoEnabledState_ShouldMapTheStateAsNull()
{
// Arrange
LibraryProviderSelectionRequest choice = _libraryProviderSelectionRequestFixture.Create(includeIsEnabled: false);
AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: [choice]);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
LibraryProviderSelectionDto mappedChoice = Assert.Single(result.MetadataProviders!);
Assert.Equal(choice.PluginId, mappedChoice.PluginId);
Assert.Null(mappedChoice.IsEnabled);
}
}
@@ -1,10 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
@@ -16,6 +19,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class UpdateLibraryRequestMappingTests
{
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new();
private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new();
[Fact]
@@ -148,4 +152,85 @@ public class UpdateLibraryRequestMappingTests
Assert.False(result.ShouldTrackConsumptionProgress.Value);
Assert.Null(result.CompletionThresholdPercentage);
}
[Fact]
public void ToCommand_WhenProviderChoicesAreProvided_ShouldMapThemInOrder()
{
// Arrange
LibraryProviderSelectionRequest[] metadataProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true), _libraryProviderSelectionRequestFixture.Create(isEnabled: false)];
LibraryProviderSelectionRequest[] artworkProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: false)];
LibraryProviderSelectionRequest[] bookReaders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)];
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
Assert.Equal(metadataProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.MetadataProviders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
Assert.Equal(artworkProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.ArtworkProviders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
Assert.Equal(bookReaders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.BookReaders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
}
[Fact]
public void ToCommand_WhenProviderChoicesAreNotProvided_ShouldMapThemAsNull()
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
Assert.Null(result.MetadataProviders);
Assert.Null(result.ArtworkProviders);
Assert.Null(result.BookReaders);
}
[Fact]
public void ToCommand_WhenAProviderChoiceIsNull_ShouldMapItToAChoiceWithoutPluginId()
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: [null], artworkProviders: [null], bookReaders: [null]);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
Assert.Equal(Guid.Empty, Assert.Single(result.MetadataProviders!).PluginId);
Assert.Null(result.MetadataProviders![0].IsEnabled);
Assert.Equal(Guid.Empty, Assert.Single(result.ArtworkProviders!).PluginId);
Assert.Equal(Guid.Empty, Assert.Single(result.BookReaders!).PluginId);
}
[Fact]
public void ToCommand_WhenAPathTemplatePartIsNull_ShouldMapItToAPartWithoutKind()
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(pathTemplateParts: [null]);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
LibraryPathTemplatePartDto part = Assert.Single(result.PathTemplateParts!);
Assert.Null(part.Kind);
Assert.Null(part.Representation);
Assert.False(part.IsOptional);
}
[Fact]
public void ToCommand_WhenAProviderChoiceHasNoEnabledState_ShouldMapTheStateAsNull()
{
// Arrange
LibraryProviderSelectionRequest choice = _libraryProviderSelectionRequestFixture.Create(includeIsEnabled: false);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: [choice]);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
LibraryProviderSelectionDto mappedChoice = Assert.Single(result.MetadataProviders!);
Assert.Equal(choice.PluginId, mappedChoice.PluginId);
Assert.Null(mappedChoice.IsEnabled);
}
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeArtworkProvidersRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersRequestMappingTests
{
private readonly GetLibraryTypeArtworkProvidersRequestFixture _getLibraryTypeArtworkProvidersRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(libraryType: "Music");
// Act
GetLibraryTypeArtworkProvidersQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryType, result.LibraryType);
}
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeBookReadersRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersRequestMappingTests
{
private readonly GetLibraryTypeBookReadersRequestFixture _getLibraryTypeBookReadersRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(libraryType: "Music");
// Act
GetLibraryTypeBookReadersQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryType, result.LibraryType);
}
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeMetadataProvidersRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersRequestMappingTests
{
private readonly GetLibraryTypeMetadataProvidersRequestFixture _getLibraryTypeMetadataProvidersRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(libraryType: "Music");
// Act
GetLibraryTypeMetadataProvidersQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryType, result.LibraryType);
}
}
@@ -1,32 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryArtworkProvidersRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersRequestMappingTests
{
private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create();
// Act
ReorderLibraryArtworkProvidersCommand result = request.ToCommand();
// Assert
Assert.Equal(request.LibraryId, result.LibraryId);
Assert.Equal(request.PluginIds, result.PluginIds);
}
}
@@ -1,35 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryMetadataProvidersRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersRequestMappingTests
{
private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(Guid.NewGuid(), [Guid.NewGuid(), Guid.NewGuid()]);
// Act
ReorderLibraryMetadataProvidersCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryId, result.LibraryId);
Assert.Equal(request.PluginIds, result.PluginIds);
}
}
@@ -1,33 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryArtworkProviderEnabledRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledRequestMappingTests
{
private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(isEnabled: true);
// Act
SetLibraryArtworkProviderEnabledCommand result = request.ToCommand();
// Assert
Assert.Equal(request.LibraryId, result.LibraryId);
Assert.Equal(request.PluginId, result.PluginId);
Assert.Equal(request.IsEnabled, result.IsEnabled);
}
}
@@ -1,34 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryBookReaderEnabledRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledRequestMappingTests
{
private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create();
// Act
SetLibraryBookReaderEnabledCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryId, result.LibraryId);
Assert.Equal(request.PluginId, result.PluginId);
Assert.Equal(request.IsEnabled, result.IsEnabled);
}
}
@@ -1,35 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryMetadataProviderEnabledRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledRequestMappingTests
{
private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(Guid.NewGuid(), Guid.NewGuid(), true);
// Act
SetLibraryMetadataProviderEnabledCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryId, result.LibraryId);
Assert.Equal(request.PluginId, result.PluginId);
Assert.Equal(request.IsEnabled, result.IsEnabled);
}
}
@@ -56,6 +56,7 @@ public class AddLibraryCommandHandlerTests
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new();
private readonly Guid _userId;
/// <summary>
@@ -76,14 +77,14 @@ public class AddLibraryCommandHandlerTests
_mockValidator = Substitute.For<IValidator<AddLibraryCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated, is an admin, the cover image is a valid image, and the provider configurations are seeded successfully
// Default stubs: the current user is authenticated, is an admin, the cover image is a valid image, and the provider configurations are seeded successfully.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.PNG));
_mockLibraryRepository.InsertAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
_mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockValidator.Validate(Arg.Any<AddLibraryCommand>()).Returns([]);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(LibraryPathTemplate.Empty()));
@@ -107,8 +108,8 @@ public class AddLibraryCommandHandlerTests
Assert.False(result.IsFailure);
Assert.Equal(persistedLibrary.Id, result.Value.Id);
await _mockLibraryRepository.Received(1).InsertAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync(
Arg.Any<Guid>(), Arg.Is<LibraryType>(libraryType => libraryType == Enum.Parse<LibraryType>(command.LibraryType)), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync(
Arg.Any<Guid>(), Arg.Is<LibraryType>(libraryType => libraryType == Enum.Parse<LibraryType>(command.LibraryType!)), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Is(true), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Any<LibrarySavedDomainEvent>());
}
@@ -157,12 +158,40 @@ public class AddLibraryCommandHandlerTests
}
[Fact]
public async Task HandleAsync_WhenProviderConfigurationSeedingFails_ShouldReturnErrorWithoutSaving()
public async Task HandleAsync_WhenProviderChoicesAreMade_ShouldConfigureProvidersWithTheChoices()
{
// Arrange
LibraryProviderSelectionDto[] metadataProviders = [.. _libraryProviderSelectionDtoFixture.CreateMany(2)];
LibraryProviderSelectionDto[] artworkProviders = [_libraryProviderSelectionDtoFixture.Create(isEnabled: false)];
LibraryProviderSelectionDto[] bookReaders = [_libraryProviderSelectionDtoFixture.Create()];
AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders);
LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(persistedLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync(
Arg.Any<Guid>(),
Enum.Parse<LibraryType>(command.LibraryType!),
Arg.Is<IReadOnlyList<LibraryProviderSelectionDto>?>(selections => selections == metadataProviders),
Arg.Is<IReadOnlyList<LibraryProviderSelectionDto>?>(selections => selections == artworkProviders),
Arg.Is<IReadOnlyList<LibraryProviderSelectionDto>?>(selections => selections == bookReaders),
Arg.Is(true),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenConfiguringProvidersFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create();
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to seed provider configurations"));
_mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to configure provider configurations"));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -7,6 +7,7 @@ using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -22,6 +23,7 @@ public class AddLibraryCommandValidatorTests
private readonly AddLibraryCommandValidator _validator = new();
private readonly AddLibraryCommandFixture _addLibraryCommandFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new();
[Fact]
public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError()
@@ -37,12 +39,14 @@ public class AddLibraryCommandValidatorTests
result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull);
}
[Fact]
public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError()
[Theory]
[InlineData("UnknownLibraryType")] // Not a library type.
[InlineData("999")] // A number that is not a defined library type.
public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType)
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create();
command = command with { LibraryType = "UnknownLibraryType" };
command = command with { LibraryType = libraryType };
// Act
List<Error> result = _validator.TestValidate(command);
@@ -65,6 +69,36 @@ public class AddLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Theory]
[InlineData("book")] // The casing of the name does not matter.
[InlineData("eBook")] // The casing of the name does not matter.
public void Validate_WhenLibraryTypeDiffersInCasing_ShouldNotHaveValidationError(string libraryType)
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create();
command = command with { LibraryType = libraryType };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Fact]
public void Validate_WhenLibraryTypeIsTheNumericValueOfADefinedMember_ShouldHaveValidationError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create();
command = command with { LibraryType = "0" }; // Book
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Fact]
public void Validate_WhenContentLocationsIsNull_ShouldHaveValidationError()
{
@@ -220,9 +254,9 @@ public class AddLibraryCommandValidatorTests
}
[Theory]
[InlineData(null)] // an absent kind
[InlineData("")] // an empty kind
[InlineData(" ")] // a whitespace kind
[InlineData(null)] // An absent kind.
[InlineData("")] // An empty kind.
[InlineData(" ")] // A whitespace kind.
public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind)
{
// Arrange
@@ -237,9 +271,9 @@ public class AddLibraryCommandValidatorTests
}
[Theory]
[InlineData(null)] // an absent representation
[InlineData("")] // an empty representation
[InlineData(" ")] // a whitespace representation
[InlineData(null)] // An absent representation.
[InlineData("")] // An empty representation.
[InlineData(" ")] // A whitespace representation.
public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation)
{
// Arrange
@@ -305,8 +339,8 @@ public class AddLibraryCommandValidatorTests
}
[Theory]
[InlineData(-1)] // just below the allowed range
[InlineData(int.MinValue)] // the lowest possible value
[InlineData(-1)] // Just below the allowed range.
[InlineData(int.MinValue)] // The lowest possible value.
public void Validate_WhenThresholdIsBelowZero_ShouldHaveValidationError(int completionThresholdPercentage)
{
// Arrange
@@ -323,8 +357,8 @@ public class AddLibraryCommandValidatorTests
}
[Theory]
[InlineData(101)] // just above the allowed range
[InlineData(int.MaxValue)] // the highest possible value
[InlineData(101)] // Just above the allowed range.
[InlineData(int.MaxValue)] // The highest possible value.
public void Validate_WhenThresholdIsAboveOneHundred_ShouldHaveValidationError(int completionThresholdPercentage)
{
// Arrange
@@ -341,8 +375,8 @@ public class AddLibraryCommandValidatorTests
}
[Theory]
[InlineData(0)] // the lowest allowed boundary
[InlineData(100)] // the highest allowed boundary
[InlineData(0)] // The lowest allowed boundary.
[InlineData(100)] // The highest allowed boundary.
public void Validate_WhenThresholdIsAtAnAllowedBoundary_ShouldNotHaveValidationError(int completionThresholdPercentage)
{
// Arrange
@@ -408,4 +442,116 @@ public class AddLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff);
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
}
[Fact]
public void Validate_WhenMetadataProviderPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenMetadataProviderPluginIdsAreDuplicated_ShouldHaveValidationError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenArtworkProviderPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtworkProviderPluginIdsAreDuplicated_ShouldHaveValidationError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
AddLibraryCommand command = _addLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenBookReaderPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenBookReaderPluginIdsAreDuplicated_ShouldHaveValidationError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
AddLibraryCommand command = _addLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenProviderChoicesAreValid_ShouldNotHaveProviderValidationErrors()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
metadataProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)],
artworkProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)],
bookReaders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenProviderChoicesAreNotProvided_ShouldNotHaveProviderValidationErrors()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
}
@@ -14,6 +14,7 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.DeleteLi
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using NSubstitute;
using System;
using System.Collections.Generic;
@@ -60,10 +61,12 @@ public class DeleteLibraryCommandHandlerTests
_mockValidator = Substitute.For<IValidator<DeleteLibraryCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated, the ownership policy allows the deletion, and the provider configurations are removed successfully
// Default stubs: the current user is authenticated, the ownership policy allows the deletion, the user has the manage permission, and the provider configurations are removed successfully.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>())
.Returns(true);
_mockProviderConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockLibraryRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
@@ -170,6 +173,49 @@ public class DeleteLibraryCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheOwnerLacksTheManagePermission_ShouldReturnNotAuthorizedError()
{
// Arrange
DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockProviderConfigurationStore.DidNotReceive().RemoveProviderConfigurationsForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAnAdminWithoutTheManagePermissionDeletesTheLibraryOfAnotherUser_ShouldDeleteIt()
{
// Arrange
DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid());
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>())
.Returns(false);
_mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any<CancellationToken>())
.Returns(true);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).DeleteByIdAsync(command.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError()
{
@@ -58,6 +58,7 @@ public class UpdateLibraryCommandHandlerTests
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new();
private readonly Guid _userId;
/// <summary>
@@ -78,15 +79,17 @@ public class UpdateLibraryCommandHandlerTests
_mockValidator = Substitute.For<IValidator<UpdateLibraryCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated, has the manage permission, the cover image is a valid image, and the provider configurations are reconciled successfully
// Default stubs: the current user is authenticated, owns the library, has the manage permission, the cover image is a valid image, and the provider configurations are configured successfully.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.PNG));
_mockLibraryRepository.UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
_mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockValidator.Validate(Arg.Any<UpdateLibraryCommand>()).Returns([]);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(LibraryPathTemplate.Empty()));
@@ -99,8 +102,8 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryType commandLibraryType = Enum.Parse<LibraryType>(command.LibraryType);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryType commandLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book;
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -112,8 +115,8 @@ public class UpdateLibraryCommandHandlerTests
Assert.False(result.IsFailure);
Assert.Equal(existingLibrary.Id, result.Value.Id);
await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).ReconcileProviderConfigurationsAsync(
command.Id, Arg.Is<LibraryType>(libraryType => libraryType == commandLibraryType), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync(
command.Id, Arg.Is<LibraryType>(libraryType => libraryType == commandLibraryType), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Is(true), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Any<LibrarySavedDomainEvent>());
}
@@ -127,7 +130,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: 50);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
shouldTrackConsumptionProgress: false);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -152,7 +155,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Music,
shouldTrackConsumptionProgress: false);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
@@ -171,12 +174,34 @@ public class UpdateLibraryCommandHandlerTests
}
[Fact]
public async Task HandleAsync_WhenLibraryTypeIsUnchanged_ShouldNotReconcileProviderConfigurations()
public async Task HandleAsync_WhenAnAdminUpdatesTheLibraryOfAnotherUser_ShouldKeepTheStoredOwner()
{
// Arrange
Guid ownerId = Guid.NewGuid();
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: ownerId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any<CancellationToken>())
.Returns(true);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).UpdateAsync(
Arg.Is<LibraryEntity>(library => library.UserId == ownerId),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryTypeIsUnchangedAndNoProviderChoicesAreMade_ShouldNotConfigureProviders()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
existingLibrary.LibraryType = Enum.Parse<LibraryType>(command.LibraryType);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.LibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -185,21 +210,144 @@ public class UpdateLibraryCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockProviderConfigurationStore.DidNotReceive().ReconcileProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.DidNotReceive().ConfigureProvidersAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenProviderConfigurationReconciliationFails_ShouldReturnErrorWithoutSaving()
public async Task HandleAsync_WhenProviderChoicesAreMadeAndLibraryTypeIsUnchanged_ShouldConfigureProvidersWithTheChoices()
{
// Arrange
LibraryProviderSelectionDto[] metadataProviders = [.. _libraryProviderSelectionDtoFixture.CreateMany(2)];
LibraryProviderSelectionDto[] artworkProviders = [_libraryProviderSelectionDtoFixture.Create(isEnabled: false)];
LibraryProviderSelectionDto[] bookReaders = [_libraryProviderSelectionDtoFixture.Create()];
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders);
LibraryType commandLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.LibraryType = commandLibraryType;
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync(
command.Id,
commandLibraryType,
Arg.Is<IReadOnlyList<LibraryProviderSelectionDto>?>(selections => selections == metadataProviders),
Arg.Is<IReadOnlyList<LibraryProviderSelectionDto>?>(selections => selections == artworkProviders),
Arg.Is<IReadOnlyList<LibraryProviderSelectionDto>?>(selections => selections == bookReaders),
Arg.Is(false),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task HandleAsync_WhenANonOwnerWithTheManagePermissionUpdatesTheLibrary_ShouldReturnNotAuthorizedWithoutChangingAnything(bool hasProviderChoices)
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(bookReaders: hasProviderChoices ? [_libraryProviderSelectionDtoFixture.Create()] : null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid());
existingLibrary.LibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.DidNotReceive().ConfigureProvidersAsync(
Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenANonOwnerWithTheManagePermissionChangesTheLibraryType_ShouldReturnNotAuthorizedWithoutChangingTheConfigurations()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(libraryType: nameof(LibraryType.Book));
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid(), libraryType: LibraryType.Music);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockProviderConfigurationStore.DidNotReceive().ConfigureProvidersAsync(
Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheOwnerLacksTheManagePermission_ShouldReturnNotAuthorizedWithoutChangingAnything()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryType commandLibraryType = Enum.Parse<LibraryType>(command.LibraryType);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAnAdminWithoutTheManagePermissionUpdatesTheLibraryOfAnotherUser_ShouldUpdateIt()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid());
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>())
.Returns(false);
_mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any<CancellationToken>())
.Returns(true);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenConfiguringProvidersFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryType commandLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book;
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to reconcile provider configurations"));
_mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to configure provider configurations"));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -215,7 +363,7 @@ public class UpdateLibraryCommandHandlerTests
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { CoverImage = null };
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -234,7 +382,7 @@ public class UpdateLibraryCommandHandlerTests
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { CoverImage = "C:/Users/user/cover.jpg" };
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.CoverImage = null;
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -257,7 +405,7 @@ public class UpdateLibraryCommandHandlerTests
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { CoverImage = "C:/Users/user/cover.jpg" };
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.CoverImage = null;
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -279,7 +427,7 @@ public class UpdateLibraryCommandHandlerTests
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { CoverImage = " " };
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.CoverImage = null;
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -294,12 +442,39 @@ public class UpdateLibraryCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserLacksManagePermissionAndCoverImageIsNew_ShouldNotProbeCoverImage()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { CoverImage = @"\\server\share\cover.jpg" };
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.CoverImage = null;
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any<CancellationToken>())
.Returns(false);
_mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockEnvironmentContext.FileTypeService.DidNotReceive()
.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCoverImageIsUnchanged_ShouldSkipImageTypeCheck()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.CoverImage = command.CoverImage;
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -333,6 +508,28 @@ public class UpdateLibraryCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExistAndUserLacksPermission_ShouldReturnNotFoundWithoutAuthorizing()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result<LibraryEntity?>.Success(null));
_mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any<CancellationToken>())
.Returns(false);
_mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByIdFails_ShouldReturnError()
{
@@ -355,7 +552,7 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>())
@@ -395,7 +592,7 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
command = command with { ContentLocations = [""] };
@@ -415,7 +612,7 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockLibraryRepository.UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>())
@@ -434,7 +631,7 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary), Error.Failure(description: "Failed to retrieve updated library"));
@@ -450,7 +647,7 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary), Result<LibraryEntity?>.Success(null));
@@ -486,7 +683,7 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
LibraryPathPart defaultPart = _libraryPathPartFixture.Create(
@@ -524,7 +721,7 @@ public class UpdateLibraryCommandHandlerTests
representation: "{0}",
isOptional: false);
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [providedDto]);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
LibraryPathPart providedPart = _libraryPathPartFixture.Create(
@@ -562,7 +759,7 @@ public class UpdateLibraryCommandHandlerTests
// Arrange
LibraryPathTemplatePartDto invalidPart = _libraryPathTemplatePartDtoFixture.Create() with { Kind = "NotARealLibraryPathPartKind" };
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [invalidPart]);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -585,7 +782,7 @@ public class UpdateLibraryCommandHandlerTests
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}");
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [validPart]);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
Error validationError = DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType;
@@ -611,7 +808,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
@@ -641,7 +838,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: 60);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
@@ -671,7 +868,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
@@ -701,7 +898,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: 50);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
@@ -728,7 +925,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
@@ -758,7 +955,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Music,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
@@ -788,7 +985,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: 65);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Music,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
@@ -23,6 +23,7 @@ public class UpdateLibraryCommandValidatorTests
private readonly UpdateLibraryCommandValidator _validator = new();
private readonly UpdateLibraryCommandFixture _updateLibraryCommandFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new();
[Fact]
public void Validate_WhenIdIsEmpty_ShouldHaveValidationError()
@@ -51,33 +52,6 @@ public class UpdateLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenOwnerIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { OwnerId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Users.UserIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenOwnerIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Users.UserIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError()
{
@@ -92,12 +66,14 @@ public class UpdateLibraryCommandValidatorTests
result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull);
}
[Fact]
public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError()
[Theory]
[InlineData("UnknownLibraryType")] // Not a library type.
[InlineData("999")] // A number that is not a defined library type.
public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType)
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { LibraryType = "UnknownLibraryType" };
command = command with { LibraryType = libraryType };
// Act
List<Error> result = _validator.TestValidate(command);
@@ -120,6 +96,36 @@ public class UpdateLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Theory]
[InlineData("book")] // The casing of the name does not matter.
[InlineData("eBook")] // The casing of the name does not matter.
public void Validate_WhenLibraryTypeDiffersInCasing_ShouldNotHaveValidationError(string libraryType)
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { LibraryType = libraryType };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Fact]
public void Validate_WhenLibraryTypeIsTheNumericValueOfADefinedMember_ShouldHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { LibraryType = "0" }; // Book
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Fact]
public void Validate_WhenContentLocationsIsNull_ShouldHaveValidationError()
{
@@ -275,9 +281,9 @@ public class UpdateLibraryCommandValidatorTests
}
[Theory]
[InlineData(null)] // an absent kind
[InlineData("")] // an empty kind
[InlineData(" ")] // a whitespace kind
[InlineData(null)] // An absent kind.
[InlineData("")] // An empty kind.
[InlineData(" ")] // A whitespace kind.
public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind)
{
// Arrange
@@ -292,9 +298,9 @@ public class UpdateLibraryCommandValidatorTests
}
[Theory]
[InlineData(null)] // an absent representation
[InlineData("")] // an empty representation
[InlineData(" ")] // a whitespace representation
[InlineData(null)] // An absent representation.
[InlineData("")] // An empty representation.
[InlineData(" ")] // A whitespace representation.
public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation)
{
// Arrange
@@ -360,8 +366,8 @@ public class UpdateLibraryCommandValidatorTests
}
[Theory]
[InlineData(-1)] // just below the allowed range
[InlineData(int.MinValue)] // the lowest possible value
[InlineData(-1)] // Just below the allowed range.
[InlineData(int.MinValue)] // The lowest possible value.
public void Validate_WhenThresholdIsBelowZero_ShouldHaveValidationError(int completionThresholdPercentage)
{
// Arrange
@@ -378,8 +384,8 @@ public class UpdateLibraryCommandValidatorTests
}
[Theory]
[InlineData(101)] // just above the allowed range
[InlineData(int.MaxValue)] // the highest possible value
[InlineData(101)] // Just above the allowed range.
[InlineData(int.MaxValue)] // The highest possible value.
public void Validate_WhenThresholdIsAboveOneHundred_ShouldHaveValidationError(int completionThresholdPercentage)
{
// Arrange
@@ -396,8 +402,8 @@ public class UpdateLibraryCommandValidatorTests
}
[Theory]
[InlineData(0)] // the lowest allowed boundary
[InlineData(100)] // the highest allowed boundary
[InlineData(0)] // The lowest allowed boundary.
[InlineData(100)] // The highest allowed boundary.
public void Validate_WhenThresholdIsAtAnAllowedBoundary_ShouldNotHaveValidationError(int completionThresholdPercentage)
{
// Arrange
@@ -463,4 +469,116 @@ public class UpdateLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff);
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
}
[Fact]
public void Validate_WhenMetadataProviderPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenMetadataProviderPluginIdsAreDuplicated_ShouldHaveValidationError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenArtworkProviderPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtworkProviderPluginIdsAreDuplicated_ShouldHaveValidationError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenBookReaderPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenBookReaderPluginIdsAreDuplicated_ShouldHaveValidationError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenProviderChoicesAreValid_ShouldNotHaveProviderValidationErrors()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
metadataProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)],
artworkProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)],
bookReaders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenProviderChoicesAreNotProvided_ShouldNotHaveProviderValidationErrors()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
}
@@ -51,9 +51,10 @@ public class GetLibraryPathTemplatePartsQueryHandlerTests
}
[Theory]
[InlineData("")] // an absent library type
[InlineData(" ")] // a whitespace library type
[InlineData("NotARealLibraryType")] // an unknown library type
[InlineData("")] // An absent library type.
[InlineData(" ")] // A whitespace library type.
[InlineData("NotARealLibraryType")] // An unknown library type.
[InlineData("999")] // A number that is not a defined library type.
public async Task HandleAsync_WhenLibraryTypeIsUnknownOrAbsent_ShouldReturnUnknownLibraryTypeError(string libraryType)
{
// Arrange
@@ -1,184 +0,0 @@
#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 _libraryArtworkProviderConfigurationEntityFixture = 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>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_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 = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2);
LibraryArtworkProviderConfigurationEntity secondProvider = _libraryArtworkProviderConfigurationEntityFixture.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 = _libraryArtworkProviderConfigurationEntityFixture.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>());
}
}
@@ -1,104 +0,0 @@
#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();
}
}
@@ -1,144 +0,0 @@
#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.ReorderLibraryMetadataProviders;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
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.ReorderLibraryMetadataProviders;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryMetadataProvidersCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<ReorderLibraryMetadataProvidersCommand> _mockValidator;
private readonly ReorderLibraryMetadataProvidersCommandHandler _sut;
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly ReorderLibraryMetadataProvidersCommandFixture _reorderLibraryMetadataProvidersCommandFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryMetadataProvidersCommandHandlerTests"/> class.
/// </summary>
public ReorderLibraryMetadataProvidersCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<ReorderLibraryMetadataProvidersCommand>>();
_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<ReorderLibraryMetadataProvidersCommand>())
.Returns([]);
_sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldAssignRanksInTheProvidedOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryMetadataProviderConfigurationEntity firstProvider = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2);
LibraryMetadataProviderConfigurationEntity secondProvider = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1);
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryMetadataProviderConfigurationEntity> { firstProvider, secondProvider });
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == secondProvider.PluginId && configuration.Rank == 1),
Arg.Any<CancellationToken>());
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == firstProvider.PluginId && configuration.Rank == 2),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockValidator.Validate(Arg.Any<ReorderLibraryMetadataProvidersCommand>()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.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<LibraryMetadataProviderConfigurationEntity>(), 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(_reorderLibraryMetadataProvidersCommandFixture.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<LibraryMetadataProviderConfigurationEntity>(), 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(_reorderLibraryMetadataProvidersCommandFixture.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>());
}
}
@@ -1,104 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
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.ReorderLibraryMetadataProviders;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryMetadataProvidersCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersCommandValidatorTests
{
private readonly ReorderLibraryMetadataProvidersCommandValidator _validator = new();
private readonly ReorderLibraryMetadataProvidersCommandFixture _reorderLibraryMetadataProvidersCommandFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.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
ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdsIsNull_ShouldHaveValidationError()
{
// Arrange
ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.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
ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.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
ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.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
ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -1,243 +0,0 @@
#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>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_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>());
}
}
@@ -1,89 +0,0 @@
#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();
}
}
@@ -1,210 +0,0 @@
#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.Reading;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
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.SetLibraryBookReaderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryBookReaderEnabledCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryBookReaderConfigurationRepository _mockLibraryBookReaderConfigurationRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IBookReaderEnablementCache _mockEnablementCache;
private readonly IValidator<SetLibraryBookReaderEnabledCommand> _mockValidator;
private readonly SetLibraryBookReaderEnabledCommandHandler _sut;
private readonly SetLibraryBookReaderEnabledCommandFixture _setLibraryBookReaderEnabledCommandFixture = new();
private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledCommandHandlerTests"/> class.
/// </summary>
public SetLibraryBookReaderEnabledCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryBookReaderConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockLibraryBookReaderConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockEnablementCache = Substitute.For<IBookReaderEnablementCache>();
_mockValidator = Substitute.For<IValidator<SetLibraryBookReaderEnabledCommand>>();
_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<SetLibraryBookReaderEnabledCommand>()).Returns([]);
_mockLibraryBookReaderConfigurationRepository.UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_sut = new SetLibraryBookReaderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockEnablementCache, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldInsertNewConfigurationAndPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(isEnabled: false);
_mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryBookReaderConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryBookReaderConfigurationEntity>(configuration =>
configuration.LibraryId == command.LibraryId &&
configuration.PluginId == command.PluginId &&
configuration.IsEnabled == command.IsEnabled),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).Invalidate(command.LibraryId, command.PluginId);
}
[Fact]
public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledStateAndPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(isEnabled: true);
LibraryBookReaderConfigurationEntity existingConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(
libraryId: command.LibraryId,
pluginId: command.PluginId,
isEnabled: false);
_mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(existingConfiguration));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.True(existingConfiguration.IsEnabled);
await _mockLibraryBookReaderConfigurationRepository.Received(1).UpsertAsync(existingConfiguration, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).Invalidate(command.LibraryId, command.PluginId);
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
_mockValidator.Validate(Arg.Any<SetLibraryBookReaderEnabledCommand>()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
[Fact]
public async Task HandleAsync_WhenGetConfigurationFails_ShouldReturnErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
Error error = Error.Failure(description: "Failed to get configuration");
_mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
[Fact]
public async Task HandleAsync_WhenUpsertFails_ShouldReturnErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
Error error = Error.Failure(description: "Failed to upsert configuration");
_mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
_mockLibraryBookReaderConfigurationRepository.UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
}
@@ -1,62 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
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.SetLibraryBookReaderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryBookReaderEnabledCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledCommandValidatorTests
{
private readonly SetLibraryBookReaderEnabledCommandValidator _validator = new();
private readonly SetLibraryBookReaderEnabledCommandFixture _setLibraryBookReaderEnabledCommandFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(libraryId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(pluginId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
}
@@ -1,172 +0,0 @@
#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.SetLibraryMetadataProviderEnabled;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
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.SetLibraryMetadataProviderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryMetadataProviderEnabledCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<SetLibraryMetadataProviderEnabledCommand> _mockValidator;
private readonly SetLibraryMetadataProviderEnabledCommandHandler _sut;
private readonly SetLibraryMetadataProviderEnabledCommandFixture _setLibraryMetadataProviderEnabledCommandFixture = new();
private readonly Guid _userId;
/// <summary>
/// Fixture for generating <see cref="LibraryMetadataProviderConfigurationEntity"/> test data.
/// </summary>
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryMetadataProviderEnabledCommandHandlerTests"/> class.
/// </summary>
public SetLibraryMetadataProviderEnabledCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<SetLibraryMetadataProviderEnabledCommand>>();
_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<SetLibraryMetadataProviderEnabledCommand>())
.Returns([]);
_sut = new SetLibraryMetadataProviderEnabledCommandHandler(_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((LibraryMetadataProviderConfigurationEntity?)null);
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryMetadataProviderConfigurationEntity>());
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.IsEnabled && configuration.Rank == 1),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState()
{
// Arrange
LibraryMetadataProviderConfigurationEntity existingConfiguration = _libraryMetadataProviderConfigurationEntityFixture.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<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.IsEnabled && configuration.Rank == 2),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockValidator.Validate(Arg.Any<SetLibraryMetadataProviderEnabledCommand>()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.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<LibraryMetadataProviderConfigurationEntity>(), 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(_setLibraryMetadataProviderEnabledCommandFixture.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<LibraryMetadataProviderConfigurationEntity>(), 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(_setLibraryMetadataProviderEnabledCommandFixture.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>());
}
}
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff. Show more