mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 12:01:10 +00:00
Merge branch 'feature/add-metadata-aggregation' into feature/add-artwork-provider-and-metadata-aggregation
This commit is contained in:
commit
b47588cf83
168 files changed
+3503
-1062
No files matched your search
+42
@@ -0,0 +1,42 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="LibraryContentLocationEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryContentLocationEntityFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="LibraryContentLocationEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">Optional. The path of the media library content location.</param>
|
||||
/// <returns>The created <see cref="LibraryContentLocationEntity"/>.</returns>
|
||||
public LibraryContentLocationEntity Create(
|
||||
string? path = null)
|
||||
{
|
||||
return new LibraryContentLocationEntity
|
||||
{
|
||||
Path = path ?? _faker.System.DirectoryPath()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="LibraryContentLocationEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="LibraryContentLocationEntity"/> instances.</returns>
|
||||
public List<LibraryContentLocationEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -27,7 +27,7 @@ public class LibraryEntityFixture
|
||||
/// <param name="coverImage">Optional. The cover image path of the media library.</param>
|
||||
/// <param name="isEnabled">Whether the media library is enabled or not.</param>
|
||||
/// <param name="isLocked">Whether the media library is locked or not.</param>
|
||||
/// <param name="downloadMetadataFromWeb">Whether the media library should download metadata from the web or not.</param>
|
||||
/// <param name="canDownloadMetadataFromWeb">Whether the media library should download metadata from the web or not.</param>
|
||||
/// <param name="shouldSaveMetadataInMediaDirectories">Whether the metadata should be saved in the media directories or not.</param>
|
||||
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during a scan or not.</param>
|
||||
/// <returns>The created media library entity.</returns>
|
||||
@@ -40,7 +40,7 @@ public class LibraryEntityFixture
|
||||
string? coverImage = null,
|
||||
bool isEnabled = true,
|
||||
bool isLocked = false,
|
||||
bool downloadMetadataFromWeb = true,
|
||||
bool canDownloadMetadataFromWeb = true,
|
||||
bool shouldSaveMetadataInMediaDirectories = true,
|
||||
bool shouldSkipUnchangedDirectoriesDuringScan = false)
|
||||
{
|
||||
@@ -56,7 +56,7 @@ public class LibraryEntityFixture
|
||||
LibraryScans = [],
|
||||
IsEnabled = isEnabled,
|
||||
IsLocked = isLocked,
|
||||
DownloadMetadataFromWeb = downloadMetadataFromWeb,
|
||||
CanDownloadMetadataFromWeb = canDownloadMetadataFromWeb,
|
||||
ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan,
|
||||
CreatedOnUtc = default,
|
||||
|
||||
+7
-2
@@ -21,14 +21,19 @@ public class LibraryMetadataProviderConfigurationEntityFixture
|
||||
/// <param name="libraryId">The Id of the media library the configuration belongs to.</param>
|
||||
/// <param name="pluginId">The Id of the plugin providing the metadata.</param>
|
||||
/// <param name="rank">The rank of the metadata provider, determining the order in which providers are tried.</param>
|
||||
/// <param name="isEnabled">Whether the metadata provider is enabled or not.</param>
|
||||
/// <returns>The created <see cref="LibraryMetadataProviderConfigurationEntity"/>.</returns>
|
||||
public LibraryMetadataProviderConfigurationEntity Create(Guid libraryId, Guid pluginId, int rank)
|
||||
public LibraryMetadataProviderConfigurationEntity Create(
|
||||
Guid libraryId,
|
||||
Guid pluginId,
|
||||
int rank,
|
||||
bool isEnabled = true)
|
||||
{
|
||||
return new Faker<LibraryMetadataProviderConfigurationEntity>()
|
||||
.RuleFor(configuration => configuration.Id, faker => faker.Random.Guid())
|
||||
.RuleFor(configuration => configuration.LibraryId, libraryId)
|
||||
.RuleFor(configuration => configuration.PluginId, pluginId)
|
||||
.RuleFor(configuration => configuration.IsEnabled, faker => faker.Random.Bool())
|
||||
.RuleFor(configuration => configuration.IsEnabled, isEnabled)
|
||||
.RuleFor(configuration => configuration.Rank, rank)
|
||||
.RuleFor(configuration => configuration.CreatedOnUtc, faker => faker.Date.Past())
|
||||
.RuleFor(configuration => configuration.CreatedBy, faker => faker.Random.Guid())
|
||||
|
||||
+13
-4
@@ -21,17 +21,26 @@ public class PluginEntityFixture
|
||||
/// Creates a random valid <see cref="PluginEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the plugin, or <see langword="null"/> to generate a random one.</param>
|
||||
/// <param name="name">The name of the plugin, or <see langword="null"/> to generate a random one.</param>
|
||||
/// <param name="loadStatus">The load status of the plugin, or <see langword="null"/> to generate a random one.</param>
|
||||
/// <param name="settingsJson">The serialized settings of the plugin, or <see langword="null"/> to generate random ones.</param>
|
||||
/// <param name="includeSettingsJson">Whether the settings should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="PluginEntity"/>.</returns>
|
||||
public PluginEntity Create(Guid? id = null)
|
||||
public PluginEntity Create(
|
||||
Guid? id = null,
|
||||
string? name = null,
|
||||
PluginLoadStatus? loadStatus = null,
|
||||
string? settingsJson = null,
|
||||
bool includeSettingsJson = true)
|
||||
{
|
||||
return new Faker<PluginEntity>()
|
||||
.RuleFor(plugin => plugin.Id, faker => id ?? faker.Random.Guid())
|
||||
.RuleFor(plugin => plugin.Name, faker => faker.Company.CompanyName())
|
||||
.RuleFor(plugin => plugin.Name, faker => name ?? faker.Company.CompanyName())
|
||||
.RuleFor(plugin => plugin.Author, faker => faker.Name.FullName())
|
||||
.RuleFor(plugin => plugin.Version, faker => faker.System.Semver())
|
||||
.RuleFor(plugin => plugin.Description, faker => faker.Lorem.Sentence())
|
||||
.RuleFor(plugin => plugin.LoadStatus, faker => faker.PickRandom<PluginLoadStatus>())
|
||||
.RuleFor(plugin => plugin.SettingsJson, faker => JsonSerializer.Serialize(new Dictionary<string, string> { [faker.Random.String2(1, 10)] = faker.Random.String2(1, 20) }))
|
||||
.RuleFor(plugin => plugin.LoadStatus, faker => loadStatus ?? faker.PickRandom<PluginLoadStatus>())
|
||||
.RuleFor(plugin => plugin.SettingsJson, faker => includeSettingsJson ? settingsJson ?? JsonSerializer.Serialize(new Dictionary<string, string> { [faker.Random.String2(1, 10)] = faker.Random.String2(1, 20) }) : null)
|
||||
.RuleFor(plugin => plugin.CreatedOnUtc, faker => faker.Date.Past())
|
||||
.RuleFor(plugin => plugin.CreatedBy, faker => faker.Random.Guid())
|
||||
.RuleFor(plugin => plugin.UpdatedOnUtc, faker => faker.Date.Recent())
|
||||
|
||||
+8
-5
@@ -22,16 +22,18 @@ public class UserSettingsEntityFixture
|
||||
/// <param name="userId">Optional. The Id of the user that owns these settings.</param>
|
||||
/// <param name="isPaginationEnabled">Optional. Whether pagination is enabled for the user, or not.</param>
|
||||
/// <param name="itemsPerPage">Optional. The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Optional. Whether the "The" prefix is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Optional. Whether the "The" prefix is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="isThemeCachingEnabled">Optional. Whether the theme data served to this user is cached, or not.</param>
|
||||
/// <param name="shouldAggregateMetadataWhenMissing">Optional. Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.</param>
|
||||
/// <returns>The created user settings entity.</returns>
|
||||
public UserSettingsEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? userId = null,
|
||||
bool? isPaginationEnabled = null,
|
||||
int? itemsPerPage = null,
|
||||
bool? ignoreThePrefixForAlphaPicker = null,
|
||||
bool? isThemeCachingEnabled = null)
|
||||
bool? shouldIgnoreThePrefixForAlphaPicker = null,
|
||||
bool? isThemeCachingEnabled = null,
|
||||
bool? shouldAggregateMetadataWhenMissing = null)
|
||||
{
|
||||
return new Faker<UserSettingsEntity>()
|
||||
.CustomInstantiator(f => new UserSettingsEntity
|
||||
@@ -40,8 +42,9 @@ public class UserSettingsEntityFixture
|
||||
UserId = userId ?? Guid.NewGuid(),
|
||||
IsPaginationEnabled = isPaginationEnabled ?? f.Random.Bool(),
|
||||
ItemsPerPage = itemsPerPage ?? f.Random.Int(1, 100),
|
||||
IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker ?? f.Random.Bool(),
|
||||
IsThemeCachingEnabled = isThemeCachingEnabled ?? f.Random.Bool()
|
||||
ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker ?? f.Random.Bool(),
|
||||
IsThemeCachingEnabled = isThemeCachingEnabled ?? f.Random.Bool(),
|
||||
ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing ?? f.Random.Bool()
|
||||
})
|
||||
.Generate();
|
||||
}
|
||||
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MediaSettingsDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaSettingsDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="MediaSettingsDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="rootDirectory">Optional. The root directory where media files are stored.</param>
|
||||
/// <param name="librariesDirectory">Optional. The directory where media library files are stored.</param>
|
||||
/// <param name="booksDirectory">Optional. The directory where the media item files are stored.</param>
|
||||
/// <returns>The created <see cref="MediaSettingsDto"/>.</returns>
|
||||
public MediaSettingsDto Create(
|
||||
string? rootDirectory = null,
|
||||
string? librariesDirectory = null,
|
||||
string? booksDirectory = null)
|
||||
{
|
||||
return new MediaSettingsDto
|
||||
{
|
||||
RootDirectory = rootDirectory ?? _faker.System.DirectoryPath(),
|
||||
LibrariesDirectory = librariesDirectory ?? _faker.System.DirectoryPath(),
|
||||
BooksDirectory = booksDirectory ?? _faker.System.DirectoryPath()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="MediaSettingsDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MediaSettingsDto"/> instances.</returns>
|
||||
public List<MediaSettingsDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+3
-4
@@ -2,7 +2,6 @@
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -25,7 +24,7 @@ public class AddLibraryCommandFixture
|
||||
/// <param name="coverImage">Optional. The cover image path of the media library.</param>
|
||||
/// <param name="isEnabled">Whether the media library is enabled or not.</param>
|
||||
/// <param name="isLocked">Whether the media library is locked or not.</param>
|
||||
/// <param name="downloadMetadataFromWeb">Whether the media library should download metadata from the web or not.</param>
|
||||
/// <param name="canDownloadMetadataFromWeb">Whether the media library should download metadata from the web or not.</param>
|
||||
/// <param name="shouldSaveMetadataInMediaDirectories">Whether the metadata should be saved in the media directories or not.</param>
|
||||
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during a scan or not.</param>
|
||||
/// <returns>The created command.</returns>
|
||||
@@ -36,7 +35,7 @@ public class AddLibraryCommandFixture
|
||||
string? coverImage = null,
|
||||
bool isEnabled = true,
|
||||
bool isLocked = false,
|
||||
bool downloadMetadataFromWeb = true,
|
||||
bool canDownloadMetadataFromWeb = true,
|
||||
bool shouldSaveMetadataInMediaDirectories = true,
|
||||
bool shouldSkipUnchangedDirectoriesDuringScan = false)
|
||||
{
|
||||
@@ -58,7 +57,7 @@ public class AddLibraryCommandFixture
|
||||
.RuleFor(x => x.CoverImage, f => coverImage ?? f.System.FilePath())
|
||||
.RuleFor(x => x.IsEnabled, isEnabled)
|
||||
.RuleFor(x => x.IsLocked, isLocked)
|
||||
.RuleFor(x => x.DownloadMetadataFromWeb, downloadMetadataFromWeb)
|
||||
.RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb)
|
||||
.RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories)
|
||||
.RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan)
|
||||
.Generate();
|
||||
|
||||
+3
-3
@@ -27,7 +27,7 @@ public class UpdateLibraryCommandFixture
|
||||
/// <param name="coverImage">Optional. The cover image path of the media library.</param>
|
||||
/// <param name="isEnabled">Whether the media library is enabled or not.</param>
|
||||
/// <param name="isLocked">Whether the media library is locked or not.</param>
|
||||
/// <param name="downloadMetadataFromWeb">Whether the media library should download metadata from the web or not.</param>
|
||||
/// <param name="canDownloadMetadataFromWeb">Whether the media library should download metadata from the web or not.</param>
|
||||
/// <param name="shouldSaveMetadataInMediaDirectories">Whether the metadata should be saved in the media directories or not.</param>
|
||||
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during a scan or not.</param>
|
||||
/// <returns>The created command.</returns>
|
||||
@@ -40,7 +40,7 @@ public class UpdateLibraryCommandFixture
|
||||
string? coverImage = null,
|
||||
bool isEnabled = true,
|
||||
bool isLocked = false,
|
||||
bool downloadMetadataFromWeb = true,
|
||||
bool canDownloadMetadataFromWeb = true,
|
||||
bool shouldSaveMetadataInMediaDirectories = true,
|
||||
bool shouldSkipUnchangedDirectoriesDuringScan = false)
|
||||
{
|
||||
@@ -66,7 +66,7 @@ public class UpdateLibraryCommandFixture
|
||||
.RuleFor(x => x.CoverImage, f => coverImage ?? f.System.FilePath())
|
||||
.RuleFor(x => x.IsEnabled, isEnabled)
|
||||
.RuleFor(x => x.IsLocked, isLocked)
|
||||
.RuleFor(x => x.DownloadMetadataFromWeb, downloadMetadataFromWeb)
|
||||
.RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb)
|
||||
.RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories)
|
||||
.RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan)
|
||||
.Generate();
|
||||
|
||||
+7
-5
@@ -19,21 +19,23 @@ public class UpdateUserSettingsCommandFixture
|
||||
/// </summary>
|
||||
/// <param name="isPaginationEnabled">Optional. Whether pagination is enabled for the user, or not.</param>
|
||||
/// <param name="itemsPerPage">Optional. The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Optional. Whether the "The" prefix is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Optional. Whether the "The" prefix is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="isThemeCachingEnabled">Optional. Whether the theme data served to this user is cached, or not.</param>
|
||||
/// <returns>The created command.</returns>
|
||||
public UpdateUserSettingsCommand Create(
|
||||
bool? isPaginationEnabled = null,
|
||||
int? itemsPerPage = null,
|
||||
bool? ignoreThePrefixForAlphaPicker = null,
|
||||
bool? isThemeCachingEnabled = null)
|
||||
bool? shouldIgnoreThePrefixForAlphaPicker = null,
|
||||
bool? isThemeCachingEnabled = null,
|
||||
bool? shouldAggregateMetadataWhenMissing = null)
|
||||
{
|
||||
return new Faker<UpdateUserSettingsCommand>()
|
||||
.CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default, default))
|
||||
.CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default, default, default))
|
||||
.RuleFor(x => x.IsPaginationEnabled, f => isPaginationEnabled ?? f.Random.Bool())
|
||||
.RuleFor(x => x.ItemsPerPage, f => itemsPerPage ?? f.Random.Int(1, 100))
|
||||
.RuleFor(x => x.IgnoreThePrefixForAlphaPicker, f => ignoreThePrefixForAlphaPicker ?? f.Random.Bool())
|
||||
.RuleFor(x => x.ShouldIgnoreThePrefixForAlphaPicker, f => shouldIgnoreThePrefixForAlphaPicker ?? f.Random.Bool())
|
||||
.RuleFor(x => x.IsThemeCachingEnabled, f => isThemeCachingEnabled ?? f.Random.Bool())
|
||||
.RuleFor(x => x.ShouldAggregateMetadataWhenMissing, f => shouldAggregateMetadataWhenMissing ?? f.Random.Bool())
|
||||
.Generate();
|
||||
}
|
||||
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -26,7 +25,7 @@ public class AddLibraryRequestFixture
|
||||
/// <param name="coverImage">Optional. The path of the image file used as the cover.</param>
|
||||
/// <param name="isEnabled">Optional. Whether the media library is enabled.</param>
|
||||
/// <param name="isLocked">Optional. Whether the media library is locked.</param>
|
||||
/// <param name="downloadMetadataFromWeb">Optional. Whether metadata should be downloaded from the web.</param>
|
||||
/// <param name="canDownloadMetadataFromWeb">Optional. Whether metadata should be downloaded from the web.</param>
|
||||
/// <param name="shouldSaveMetadataInMediaDirectories">Optional. Whether metadata should be saved in the media directories.</param>
|
||||
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Optional. Whether unchanged directories should be skipped during scan.</param>
|
||||
/// <returns>The created <see cref="AddLibraryRequest"/>.</returns>
|
||||
@@ -37,7 +36,7 @@ public class AddLibraryRequestFixture
|
||||
string? coverImage = null,
|
||||
bool? isEnabled = null,
|
||||
bool? isLocked = null,
|
||||
bool? downloadMetadataFromWeb = null,
|
||||
bool? canDownloadMetadataFromWeb = null,
|
||||
bool? shouldSaveMetadataInMediaDirectories = null,
|
||||
bool? shouldSkipUnchangedDirectoriesDuringScan = null)
|
||||
{
|
||||
@@ -48,7 +47,7 @@ public class AddLibraryRequestFixture
|
||||
coverImage ?? null,
|
||||
isEnabled ?? _faker.Random.Bool(),
|
||||
isLocked ?? _faker.Random.Bool(),
|
||||
downloadMetadataFromWeb ?? _faker.Random.Bool(),
|
||||
canDownloadMetadataFromWeb ?? _faker.Random.Bool(),
|
||||
shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(),
|
||||
shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool()
|
||||
);
|
||||
|
||||
+3
-3
@@ -28,7 +28,7 @@ public class UpdateLibraryRequestFixture
|
||||
/// <param name="coverImage">Optional. The path of the image file used as the cover.</param>
|
||||
/// <param name="isEnabled">Optional. Whether the media library is enabled.</param>
|
||||
/// <param name="isLocked">Optional. Whether the media library is locked.</param>
|
||||
/// <param name="downloadMetadataFromWeb">Optional. Whether metadata should be downloaded from the web.</param>
|
||||
/// <param name="canDownloadMetadataFromWeb">Optional. Whether metadata should be downloaded from the web.</param>
|
||||
/// <param name="shouldSaveMetadataInMediaDirectories">Optional. Whether metadata should be saved in the media directories.</param>
|
||||
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Optional. Whether unchanged directories should be skipped during scan.</param>
|
||||
/// <returns>The created <see cref="UpdateLibraryRequest"/>.</returns>
|
||||
@@ -41,7 +41,7 @@ public class UpdateLibraryRequestFixture
|
||||
string? coverImage = null,
|
||||
bool? isEnabled = null,
|
||||
bool? isLocked = null,
|
||||
bool? downloadMetadataFromWeb = null,
|
||||
bool? canDownloadMetadataFromWeb = null,
|
||||
bool? shouldSaveMetadataInMediaDirectories = null,
|
||||
bool? shouldSkipUnchangedDirectoriesDuringScan = null)
|
||||
{
|
||||
@@ -54,7 +54,7 @@ public class UpdateLibraryRequestFixture
|
||||
coverImage ?? null,
|
||||
isEnabled ?? _faker.Random.Bool(),
|
||||
isLocked ?? _faker.Random.Bool(),
|
||||
downloadMetadataFromWeb ?? _faker.Random.Bool(),
|
||||
canDownloadMetadataFromWeb ?? _faker.Random.Bool(),
|
||||
shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(),
|
||||
shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool()
|
||||
);
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.UsersManagement.Settings;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateUserSettingsRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="UpdateUserSettingsRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="isPaginationEnabled">Whether pagination is enabled for the user.</param>
|
||||
/// <param name="itemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix is ignored by the alpha picker.</param>
|
||||
/// <param name="isThemeCachingEnabled">Whether the theme data served to this user is cached.</param>
|
||||
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing.</param>
|
||||
/// <returns>The created <see cref="UpdateUserSettingsRequest"/>.</returns>
|
||||
public UpdateUserSettingsRequest Create(
|
||||
bool? isPaginationEnabled = null,
|
||||
int? itemsPerPage = null,
|
||||
bool? shouldIgnoreThePrefixForAlphaPicker = null,
|
||||
bool? isThemeCachingEnabled = null,
|
||||
bool? shouldAggregateMetadataWhenMissing = null)
|
||||
{
|
||||
return new UpdateUserSettingsRequest(
|
||||
isPaginationEnabled ?? _faker.Random.Bool(),
|
||||
itemsPerPage ?? _faker.Random.Int(1, 100),
|
||||
shouldIgnoreThePrefixForAlphaPicker ?? _faker.Random.Bool(),
|
||||
isThemeCachingEnabled ?? _faker.Random.Bool(),
|
||||
shouldAggregateMetadataWhenMissing ?? _faker.Random.Bool());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="UpdateUserSettingsRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<UpdateUserSettingsRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -29,7 +29,7 @@ public class LibraryResponseFixture
|
||||
/// <param name="coverImage">Optional. The path of the image file used as the cover of the library.</param>
|
||||
/// <param name="isEnabled">Optional. Whether the media library is enabled.</param>
|
||||
/// <param name="isLocked">Optional. Whether the media library is locked.</param>
|
||||
/// <param name="downloadMetadataFromWeb">Optional. Whether metadata should be downloaded from the web.</param>
|
||||
/// <param name="canDownloadMetadataFromWeb">Optional. Whether metadata should be downloaded from the web.</param>
|
||||
/// <param name="shouldSaveMetadataInMediaDirectories">Optional. Whether metadata should be saved in the media directories.</param>
|
||||
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Optional. Whether unchanged directories should be skipped during scan.</param>
|
||||
/// <param name="createdOnUtc">Optional. The date and time when the library was created.</param>
|
||||
@@ -44,7 +44,7 @@ public class LibraryResponseFixture
|
||||
string? coverImage = null,
|
||||
bool? isEnabled = null,
|
||||
bool? isLocked = null,
|
||||
bool? downloadMetadataFromWeb = null,
|
||||
bool? canDownloadMetadataFromWeb = null,
|
||||
bool? shouldSaveMetadataInMediaDirectories = null,
|
||||
bool? shouldSkipUnchangedDirectoriesDuringScan = null,
|
||||
DateTime? createdOnUtc = null,
|
||||
@@ -59,7 +59,7 @@ public class LibraryResponseFixture
|
||||
coverImage,
|
||||
isEnabled ?? _faker.Random.Bool(),
|
||||
isLocked ?? _faker.Random.Bool(),
|
||||
downloadMetadataFromWeb ?? _faker.Random.Bool(),
|
||||
canDownloadMetadataFromWeb ?? _faker.Random.Bool(),
|
||||
shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(),
|
||||
shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(),
|
||||
createdOnUtc ?? _faker.Date.Past().ToUniversalTime(),
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Responses.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="LibraryMetadataProviderResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryMetadataProviderResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="LibraryMetadataProviderResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">Optional. The Id of the plugin providing the metadata.</param>
|
||||
/// <param name="name">Optional. The display name of the metadata provider.</param>
|
||||
/// <param name="isEnabled">Optional. Whether the metadata provider is enabled for the media library.</param>
|
||||
/// <param name="rank">Optional. The rank of the metadata provider.</param>
|
||||
/// <returns>The created <see cref="LibraryMetadataProviderResponse"/>.</returns>
|
||||
public LibraryMetadataProviderResponse Create(
|
||||
Guid? pluginId = null,
|
||||
string? name = null,
|
||||
bool? isEnabled = null,
|
||||
int? rank = null)
|
||||
{
|
||||
return new LibraryMetadataProviderResponse(
|
||||
pluginId ?? Guid.NewGuid(),
|
||||
name ?? _faker.Company.CompanyName(),
|
||||
isEnabled ?? _faker.Random.Bool(),
|
||||
rank ?? _faker.Random.Int(1, 100));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="LibraryMetadataProviderResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<LibraryMetadataProviderResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UserSettingsResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserSettingsResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="UserSettingsResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional. The Id of the user that owns these settings.</param>
|
||||
/// <param name="isPaginationEnabled">Optional. Whether pagination is enabled for the user.</param>
|
||||
/// <param name="itemsPerPage">Optional. The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Optional. Whether the "The" prefix is ignored by the alpha picker.</param>
|
||||
/// <param name="isThemeCachingEnabled">Optional. Whether the theme data served to this user is cached.</param>
|
||||
/// <param name="shouldAggregateMetadataWhenMissing">Optional. Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing.</param>
|
||||
/// <returns>The created <see cref="UserSettingsResponse"/>.</returns>
|
||||
public UserSettingsResponse Create(
|
||||
Guid? userId = null,
|
||||
bool? isPaginationEnabled = null,
|
||||
int? itemsPerPage = null,
|
||||
bool? shouldIgnoreThePrefixForAlphaPicker = null,
|
||||
bool? isThemeCachingEnabled = null,
|
||||
bool? shouldAggregateMetadataWhenMissing = null)
|
||||
{
|
||||
return new UserSettingsResponse(
|
||||
userId ?? Guid.NewGuid(),
|
||||
isPaginationEnabled ?? _faker.Random.Bool(),
|
||||
itemsPerPage ?? _faker.Random.Int(1, 100),
|
||||
shouldIgnoreThePrefixForAlphaPicker ?? _faker.Random.Bool(),
|
||||
isThemeCachingEnabled ?? _faker.Random.Bool(),
|
||||
shouldAggregateMetadataWhenMissing ?? _faker.Random.Bool());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="UserSettingsResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<UserSettingsResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -35,7 +35,7 @@ public class LibraryFixture
|
||||
/// <param name="includeCoverImage">Whether to include a cover image or not.</param>
|
||||
/// <param name="isEnabled">Whether the library is enabled.</param>
|
||||
/// <param name="isLocked">Whether the library is locked.</param>
|
||||
/// <param name="downloadMetadataFromWeb">Whether metadata download from the web is enabled.</param>
|
||||
/// <param name="canDownloadMetadataFromWeb">Whether metadata download from the web is enabled.</param>
|
||||
/// <param name="shouldSaveMetadataInMediaDirectories">Whether metadata should be saved in the media directories.</param>
|
||||
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during scan.</param>
|
||||
/// <param name="scanIds">Optional. The scan Ids associated with the library.</param>
|
||||
@@ -50,7 +50,7 @@ public class LibraryFixture
|
||||
bool includeCoverImage = true,
|
||||
bool isEnabled = true,
|
||||
bool isLocked = false,
|
||||
bool downloadMetadataFromWeb = true,
|
||||
bool canDownloadMetadataFromWeb = true,
|
||||
bool shouldSaveMetadataInMediaDirectories = false,
|
||||
bool shouldSkipUnchangedDirectoriesDuringScan = false,
|
||||
IEnumerable<Guid>? scanIds = null)
|
||||
@@ -75,7 +75,7 @@ public class LibraryFixture
|
||||
resolvedCoverImage,
|
||||
isEnabled,
|
||||
isLocked,
|
||||
downloadMetadataFromWeb,
|
||||
canDownloadMetadataFromWeb,
|
||||
shouldSaveMetadataInMediaDirectories,
|
||||
shouldSkipUnchangedDirectoriesDuringScan,
|
||||
resolvedScanIds
|
||||
@@ -89,7 +89,7 @@ public class LibraryFixture
|
||||
resolvedCoverImage,
|
||||
isEnabled,
|
||||
isLocked,
|
||||
downloadMetadataFromWeb,
|
||||
canDownloadMetadataFromWeb,
|
||||
shouldSaveMetadataInMediaDirectories,
|
||||
shouldSkipUnchangedDirectoriesDuringScan,
|
||||
resolvedScanIds
|
||||
|
||||
+8
-5
@@ -22,22 +22,25 @@ public class UserSettingsFixture
|
||||
/// <param name="userId">Optional. The Id of the user that owns the settings.</param>
|
||||
/// <param name="isPaginationEnabled">Whether pagination is enabled for the user.</param>
|
||||
/// <param name="itemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker.</param>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker.</param>
|
||||
/// <param name="isThemeCachingEnabled">Whether the theme data served to this user is cached.</param>
|
||||
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing.</param>
|
||||
/// <returns>The created <see cref="UserSettings"/>.</returns>
|
||||
public UserSettings Create(
|
||||
Guid? userId = null,
|
||||
bool isPaginationEnabled = true,
|
||||
int itemsPerPage = 48,
|
||||
bool ignoreThePrefixForAlphaPicker = false,
|
||||
bool isThemeCachingEnabled = true)
|
||||
bool shouldIgnoreThePrefixForAlphaPicker = false,
|
||||
bool isThemeCachingEnabled = true,
|
||||
bool shouldAggregateMetadataWhenMissing = false)
|
||||
{
|
||||
Result<UserSettings> settings = UserSettings.Create(
|
||||
userId is null ? UserId.CreateUnique() : UserId.Create(userId.Value),
|
||||
isPaginationEnabled,
|
||||
itemsPerPage,
|
||||
ignoreThePrefixForAlphaPicker,
|
||||
isThemeCachingEnabled);
|
||||
shouldIgnoreThePrefixForAlphaPicker,
|
||||
isThemeCachingEnabled,
|
||||
shouldAggregateMetadataWhenMissing);
|
||||
return settings.Value;
|
||||
}
|
||||
|
||||
|
||||
+7
-6
@@ -15,6 +15,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="LibraryDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
@@ -26,16 +28,15 @@ public class LibraryDtoFixture
|
||||
/// <returns>A configured <see cref="LibraryDto"/> instance.</returns>
|
||||
public LibraryDto Create(Guid? id = null, string? title = null, string? libraryType = null, bool? isEnabled = null, List<string>? contentLocations = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
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(),
|
||||
ContentLocations = contentLocations ?? [faker.System.DirectoryPath()],
|
||||
IsEnabled = isEnabled ?? faker.Random.Bool()
|
||||
Title = title ?? _faker.Commerce.Department(),
|
||||
LibraryType = libraryType ?? _faker.PickRandom("Book", "Video", "Photo"),
|
||||
CoverImage = _faker.Image.PicsumUrl(),
|
||||
ContentLocations = contentLocations ?? [_faker.System.DirectoryPath()],
|
||||
IsEnabled = isEnabled ?? _faker.Random.Bool()
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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 generating <see cref="ScanLibraryDto"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScanLibraryDtoFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ScanLibraryDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="scanId">Optional Id of the media library scan.</param>
|
||||
/// <param name="libraryId">Optional Id of the scanned media library.</param>
|
||||
/// <returns>A configured <see cref="ScanLibraryDto"/> instance.</returns>
|
||||
public ScanLibraryDto Create(
|
||||
Guid? scanId = null,
|
||||
Guid? libraryId = null)
|
||||
{
|
||||
return new ScanLibraryDto
|
||||
{
|
||||
ScanId = scanId ?? Guid.NewGuid(),
|
||||
LibraryId = libraryId ?? Guid.NewGuid()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="ScanLibraryDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ScanLibraryDto"/> instances.</returns>
|
||||
public List<ScanLibraryDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="LibraryMetadataProviderDto"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryMetadataProviderDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="LibraryMetadataProviderDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">Optional unique identifier of the plugin providing the metadata.</param>
|
||||
/// <param name="name">Optional display name of the metadata provider.</param>
|
||||
/// <param name="isEnabled">Whether the metadata provider is enabled for the media library or not.</param>
|
||||
/// <param name="rank">Optional rank of the metadata provider, determining the order in which providers are tried.</param>
|
||||
/// <returns>A configured <see cref="LibraryMetadataProviderDto"/> instance.</returns>
|
||||
public LibraryMetadataProviderDto Create(
|
||||
Guid? pluginId = null,
|
||||
string? name = null,
|
||||
bool? isEnabled = null,
|
||||
int? rank = null)
|
||||
{
|
||||
return new LibraryMetadataProviderDto
|
||||
{
|
||||
PluginId = pluginId ?? Guid.NewGuid(),
|
||||
Name = name ?? _faker.Company.CompanyName(),
|
||||
IsEnabled = isEnabled ?? _faker.Random.Bool(),
|
||||
Rank = rank ?? _faker.Random.Int(0, 100)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="LibraryMetadataProviderDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="LibraryMetadataProviderDto"/> instances.</returns>
|
||||
public List<LibraryMetadataProviderDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Common.Enums.Plugins;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PluginSettingDescriptorDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginSettingDescriptorDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="PluginSettingDescriptorDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="key">Optional. The key of the setting.</param>
|
||||
/// <param name="label">Optional. The display label of the setting.</param>
|
||||
/// <param name="type">Optional. The type of the setting.</param>
|
||||
/// <param name="defaultValue">Optional. The default value of the setting.</param>
|
||||
/// <param name="allowedValues">Optional. The list of allowed values of the setting.</param>
|
||||
/// <returns>The created <see cref="PluginSettingDescriptorDto"/>.</returns>
|
||||
public PluginSettingDescriptorDto Create(
|
||||
string? key = null,
|
||||
string? label = null,
|
||||
PluginSettingType? type = null,
|
||||
string? defaultValue = null,
|
||||
IReadOnlyList<string>? allowedValues = null)
|
||||
{
|
||||
return new PluginSettingDescriptorDto
|
||||
{
|
||||
Key = key ?? _faker.Random.String2(4, 32),
|
||||
Label = label ?? _faker.Commerce.ProductName(),
|
||||
Type = type ?? _faker.Random.Enum<PluginSettingType>(),
|
||||
DefaultValue = defaultValue,
|
||||
AllowedValues = allowedValues
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="PluginSettingDescriptorDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<PluginSettingDescriptorDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="PluginSettingsDto"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginSettingsDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly PluginSettingDescriptorDtoFixture _pluginSettingDescriptorDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="PluginSettingsDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">Optional unique identifier of the plugin.</param>
|
||||
/// <param name="includeSettings">Whether to populate the current settings values, or leave them null.</param>
|
||||
/// <param name="includeSchema">Whether to populate the settings schema, or leave it empty.</param>
|
||||
/// <returns>A configured <see cref="PluginSettingsDto"/> instance.</returns>
|
||||
public PluginSettingsDto Create(
|
||||
Guid? pluginId = null,
|
||||
bool includeSettings = true,
|
||||
bool includeSchema = true)
|
||||
{
|
||||
string settingKey = _faker.Lorem.Word();
|
||||
return new PluginSettingsDto
|
||||
{
|
||||
PluginId = pluginId ?? Guid.NewGuid(),
|
||||
Schema = includeSchema
|
||||
? [_pluginSettingDescriptorDtoFixture.Create(key: settingKey)]
|
||||
: [],
|
||||
Settings = includeSettings
|
||||
? new Dictionary<string, string> { [settingKey] = _faker.Lorem.Word() }
|
||||
: null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="PluginSettingsDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="PluginSettingsDto"/> instances.</returns>
|
||||
public List<PluginSettingsDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+17
-6
@@ -15,23 +15,34 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserSettingsDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="UserSettingsDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional identifier of the user that owns the settings.</param>
|
||||
/// <param name="isPaginationEnabled">Whether pagination is enabled for the user.</param>
|
||||
/// <param name="itemsPerPage">Number of library items displayed per page.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Whether the "The" prefix is ignored by the alpha picker.</param>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix is ignored by the alpha picker.</param>
|
||||
/// <param name="isThemeCachingEnabled">Whether the theme data served to this user is cached.</param>
|
||||
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing.</param>
|
||||
/// <returns>A configured <see cref="UserSettingsDto"/> instance.</returns>
|
||||
public UserSettingsDto Create(Guid? userId = null, bool? isPaginationEnabled = null, int? itemsPerPage = null, bool? ignoreThePrefixForAlphaPicker = null)
|
||||
public UserSettingsDto Create(
|
||||
Guid? userId = null,
|
||||
bool? isPaginationEnabled = null,
|
||||
int? itemsPerPage = null,
|
||||
bool? shouldIgnoreThePrefixForAlphaPicker = null,
|
||||
bool? isThemeCachingEnabled = null,
|
||||
bool? shouldAggregateMetadataWhenMissing = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new UserSettingsDto
|
||||
{
|
||||
UserId = userId ?? Guid.NewGuid(),
|
||||
IsPaginationEnabled = isPaginationEnabled ?? faker.Random.Bool(),
|
||||
ItemsPerPage = itemsPerPage ?? faker.Random.Int(1, 200),
|
||||
IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker ?? faker.Random.Bool()
|
||||
IsPaginationEnabled = isPaginationEnabled ?? _faker.Random.Bool(),
|
||||
ItemsPerPage = itemsPerPage ?? _faker.Random.Int(1, 200),
|
||||
ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker ?? _faker.Random.Bool(),
|
||||
IsThemeCachingEnabled = isThemeCachingEnabled ?? _faker.Random.Bool(),
|
||||
ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing ?? _faker.Random.Bool()
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
#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 generating <see cref="ReorderLibraryMetadataProvidersRequest"/> test data.
|
||||
/// </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())];
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#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 generating <see cref="SetLibraryMetadataProviderEnabledRequest"/> test data.
|
||||
/// </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())];
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -15,19 +15,22 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdatePluginSettingsRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="UpdatePluginSettingsRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">Optional identifier of the plugin.</param>
|
||||
/// <param name="settings">Optional dictionary of settings.</param>
|
||||
/// <returns>A configured <see cref="UpdatePluginSettingsRequest"/> instance.</returns>
|
||||
public UpdatePluginSettingsRequest Create(Guid? pluginId = null, Dictionary<string, string>? settings = null)
|
||||
public UpdatePluginSettingsRequest Create(
|
||||
Guid? pluginId = null,
|
||||
Dictionary<string, string>? settings = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new UpdatePluginSettingsRequest
|
||||
{
|
||||
PluginId = pluginId ?? Guid.NewGuid(),
|
||||
Settings = settings ?? new Dictionary<string, string> { [faker.Lorem.Word()] = faker.Lorem.Word() }
|
||||
Settings = settings ?? new Dictionary<string, string> { [_faker.Lorem.Word()] = _faker.Lorem.Word() }
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+27
-27
@@ -1,8 +1,10 @@
|
||||
#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.Responses.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryMetadataProviders;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@@ -33,6 +35,8 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture<Authentica
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryMetadataProvidersEndpointTests"/> class.
|
||||
@@ -56,11 +60,12 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture<Authentica
|
||||
public async Task GetLibraryMetadataProviders_WhenProvidersAreConfigured_ShouldReturnThemOrderedByRank()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
Guid pluginIdA = Guid.NewGuid();
|
||||
Guid pluginIdB = Guid.NewGuid();
|
||||
await SeedConfigurationAsync(libraryId, pluginIdA, pluginIdB, userId);
|
||||
await SeedConfigurationAsync(libraryId, pluginIdA, pluginIdB);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/metadata-providers");
|
||||
@@ -81,7 +86,9 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture<Authentica
|
||||
public async Task GetLibraryMetadataProviders_WhenNoProvidersAreConfigured_ShouldReturnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/metadata-providers");
|
||||
@@ -94,40 +101,33 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture<Authentica
|
||||
Assert.Empty(providers!);
|
||||
}
|
||||
|
||||
/// <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 two <see cref="LibraryMetadataProviderConfigurationEntity"/> instances in the database.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library.</param>
|
||||
/// <param name="pluginIdA">The Id of the first plugin.</param>
|
||||
/// <param name="pluginIdB">The Id of the second plugin.</param>
|
||||
/// <param name="userId">The Id of the user that owns the data.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginIdA, Guid pluginIdB, Guid userId)
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginIdA, Guid pluginIdB)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
PluginId = pluginIdA,
|
||||
IsEnabled = true,
|
||||
Rank = 1,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
PluginId = pluginIdB,
|
||||
IsEnabled = false,
|
||||
Rank = 2,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdA, rank: 1, isEnabled: true));
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdB, rank: 2, isEnabled: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
|
||||
+3
-30
@@ -1,6 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPluginSettings;
|
||||
@@ -10,7 +9,6 @@ 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;
|
||||
@@ -34,6 +32,7 @@ public class GetPluginSettingsEndpointTests : IClassFixture<AuthenticatedLuminaA
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly PluginEntityFixture _pluginEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginSettingsEndpointTests"/> class.
|
||||
@@ -105,36 +104,10 @@ public class GetPluginSettingsEndpointTests : IClassFixture<AuthenticatedLuminaA
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = GetCurrentUserId();
|
||||
dbContext.Plugins.Add(new PluginEntity
|
||||
{
|
||||
Id = pluginId,
|
||||
Name = name,
|
||||
Author = "Test Author",
|
||||
Version = "1.0.0",
|
||||
Description = "A test plugin.",
|
||||
LoadStatus = PluginLoadStatus.Loaded,
|
||||
LoadError = null,
|
||||
SettingsJson = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Plugins.Add(_pluginEntityFixture.Create(id: pluginId, name: name, loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
|
||||
+30
-21
@@ -1,8 +1,12 @@
|
||||
#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;
|
||||
@@ -14,8 +18,6 @@ using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -29,6 +31,9 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<Authen
|
||||
{
|
||||
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.
|
||||
@@ -52,15 +57,16 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<Authen
|
||||
public async Task ReorderLibraryMetadataProviders_WhenCalledWithValidData_ShouldReorderTheProviders()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
Guid pluginIdA = Guid.NewGuid();
|
||||
Guid pluginIdB = Guid.NewGuid();
|
||||
await SeedConfigurationAsync(libraryId, pluginIdA, userId, rank: 1);
|
||||
await SeedConfigurationAsync(libraryId, pluginIdB, userId, rank: 2);
|
||||
ReorderLibraryMetadataProvidersRequest request = new(
|
||||
LibraryId: libraryId,
|
||||
PluginIds: [pluginIdB, pluginIdA]
|
||||
await SeedConfigurationAsync(libraryId, pluginIdA, rank: 1);
|
||||
await SeedConfigurationAsync(libraryId, pluginIdB, rank: 2);
|
||||
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
pluginIds: [pluginIdB, pluginIdA]
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -83,29 +89,32 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<Authen
|
||||
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="userId">The Id of the user that owns the data.</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, Guid userId, int rank)
|
||||
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(new LibraryMetadataProviderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
PluginId = pluginId,
|
||||
IsEnabled = true,
|
||||
Rank = rank,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
|
||||
+31
-36
@@ -1,23 +1,22 @@
|
||||
#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.Contracts.Responses.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
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.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -31,11 +30,9 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<Auth
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
|
||||
private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLibraryMetadataProviderEnabledEndpointTests"/> class.
|
||||
@@ -59,13 +56,11 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<Auth
|
||||
public async Task SetLibraryMetadataProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
SetLibraryMetadataProviderEnabledRequest request = new(
|
||||
LibraryId: libraryId,
|
||||
PluginId: pluginId,
|
||||
IsEnabled: true
|
||||
);
|
||||
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);
|
||||
@@ -87,15 +82,12 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<Auth
|
||||
public async Task SetLibraryMetadataProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConfigurationAsync(libraryId, pluginId, userId, isEnabled: false, rank: 1);
|
||||
SetLibraryMetadataProviderEnabledRequest request = new(
|
||||
LibraryId: libraryId,
|
||||
PluginId: pluginId,
|
||||
IsEnabled: true
|
||||
);
|
||||
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);
|
||||
@@ -112,30 +104,33 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<Auth
|
||||
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="userId">The Id of the user that owns the data.</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, Guid userId, bool isEnabled, int rank)
|
||||
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(new LibraryMetadataProviderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
PluginId = pluginId,
|
||||
IsEnabled = isEnabled,
|
||||
Rank = rank,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
|
||||
+11
-35
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
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.Plugins;
|
||||
@@ -12,7 +13,6 @@ 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;
|
||||
@@ -36,6 +36,8 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture<AuthenticatedLumi
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly PluginEntityFixture _pluginEntityFixture = new();
|
||||
private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePluginSettingsEndpointTests"/> class.
|
||||
@@ -61,9 +63,9 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture<AuthenticatedLumi
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
await SeedPluginAsync(pluginId, "Test Plugin");
|
||||
UpdatePluginSettingsRequest request = new(
|
||||
PluginId: pluginId,
|
||||
Settings: new Dictionary<string, string> { ["Key1"] = "Value1" }
|
||||
UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create(
|
||||
pluginId: pluginId,
|
||||
settings: new Dictionary<string, string> { ["Key1"] = "Value1" }
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -85,9 +87,9 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture<AuthenticatedLumi
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
UpdatePluginSettingsRequest request = new(
|
||||
PluginId: pluginId,
|
||||
Settings: new Dictionary<string, string> { ["Key1"] = "Value1" }
|
||||
UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create(
|
||||
pluginId: pluginId,
|
||||
settings: new Dictionary<string, string> { ["Key1"] = "Value1" }
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -118,36 +120,10 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture<AuthenticatedLumi
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = GetCurrentUserId();
|
||||
dbContext.Plugins.Add(new PluginEntity
|
||||
{
|
||||
Id = pluginId,
|
||||
Name = name,
|
||||
Author = "Test Author",
|
||||
Version = "1.0.0",
|
||||
Description = "A test plugin.",
|
||||
LoadStatus = PluginLoadStatus.Loaded,
|
||||
LoadError = null,
|
||||
SettingsJson = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Plugins.Add(_pluginEntityFixture.Create(id: pluginId, name: name, loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
|
||||
+9
-12
@@ -1,13 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
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;
|
||||
using System.Net;
|
||||
@@ -27,6 +26,7 @@ public class GetUserSettingsEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -71,7 +71,7 @@ public class GetUserSettingsEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
Assert.Equal(storedSettings.UserId, result!.UserId);
|
||||
Assert.Equal(storedSettings.IsPaginationEnabled, result.IsPaginationEnabled);
|
||||
Assert.Equal(storedSettings.ItemsPerPage, result.ItemsPerPage);
|
||||
Assert.Equal(storedSettings.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(storedSettings.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -90,7 +90,7 @@ public class GetUserSettingsEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result!.IsPaginationEnabled);
|
||||
Assert.Equal(48, result.ItemsPerPage);
|
||||
Assert.False(result.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.False(result.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -112,14 +112,11 @@ public class GetUserSettingsEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id;
|
||||
UserSettingsEntity settings = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
IsPaginationEnabled = false,
|
||||
ItemsPerPage = 24,
|
||||
IgnoreThePrefixForAlphaPicker = true
|
||||
};
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create(
|
||||
userId: userId,
|
||||
isPaginationEnabled: false,
|
||||
itemsPerPage: 24,
|
||||
shouldIgnoreThePrefixForAlphaPicker: true);
|
||||
|
||||
dbContext.UserSettings.Add(settings);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
+21
-16
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Requests.UsersManagement.Settings;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
@@ -28,6 +29,7 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -56,11 +58,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
public async Task UpdateUserSettings_WhenCalledWithValidRequest_ShouldUpdateSettings()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = new(
|
||||
IsPaginationEnabled: false,
|
||||
ItemsPerPage: 24,
|
||||
IgnoreThePrefixForAlphaPicker: true,
|
||||
IsThemeCachingEnabled: false
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: false,
|
||||
itemsPerPage: 24,
|
||||
shouldIgnoreThePrefixForAlphaPicker: true,
|
||||
isThemeCachingEnabled: false,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -77,7 +80,7 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
Assert.NotNull(storedSettings);
|
||||
Assert.False(storedSettings.IsPaginationEnabled);
|
||||
Assert.Equal(24, storedSettings.ItemsPerPage);
|
||||
Assert.True(storedSettings.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.True(storedSettings.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.False(storedSettings.IsThemeCachingEnabled);
|
||||
}
|
||||
|
||||
@@ -85,11 +88,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
public async Task UpdateUserSettings_WhenItemsPerPageIsNotPositive_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = new(
|
||||
IsPaginationEnabled: true,
|
||||
ItemsPerPage: 0,
|
||||
IgnoreThePrefixForAlphaPicker: false,
|
||||
IsThemeCachingEnabled: true
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: true,
|
||||
itemsPerPage: 0,
|
||||
shouldIgnoreThePrefixForAlphaPicker: false,
|
||||
isThemeCachingEnabled: true,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -118,11 +122,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
UpdateUserSettingsRequest request = new(
|
||||
IsPaginationEnabled: true,
|
||||
ItemsPerPage: 48,
|
||||
IgnoreThePrefixForAlphaPicker: false,
|
||||
IsThemeCachingEnabled: true
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: true,
|
||||
itemsPerPage: 48,
|
||||
shouldIgnoreThePrefixForAlphaPicker: false,
|
||||
isThemeCachingEnabled: true,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
|
||||
+1
@@ -41,6 +41,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Presentation.Api\Lumina.Presentation.Api.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Application.Fixtures\Lumina.Application.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Presentation.Api.Fixtures\Lumina.Presentation.Api.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
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.Tools.Settings.GetUserSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <c>/{culture}/tools/settings/api-get-user-settings</c> route served by the <see cref="GetUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserSettingsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetUserSettingsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserSettings_WhenCalledByAuthenticatedUser_ShouldReturnSettingsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
UserSettingsDto expectedSettings = _userSettingsDtoFixture.Create(itemsPerPage: 24);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("users/me/settings", expectedSettings);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-user-settings");
|
||||
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());
|
||||
Assert.Equal(24, json.RootElement.GetProperty("data").GetProperty("itemsPerPage").GetInt32());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "users/me/settings");
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <c>/{culture}/tools/settings</c> route served by the <see cref="SettingsViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SettingsViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SettingsViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SettingsViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SettingsView_WhenCalledByAuthenticatedUser_ShouldRenderSettingsPage()
|
||||
{
|
||||
// Arrange
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/tools/settings");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("user-settings-form", content);
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Common.Requests.Common;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
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.Tools.Settings.UpdateUserSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <c>/{culture}/tools/settings/api-update-user-settings</c> route served by the <see cref="UpdateUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdateUserSettingsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenCalledByAuthenticatedUser_ShouldUpdateSettings()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings", _ => new EmptyRequest());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
UserSettingsDto settings = _userSettingsDtoFixture.Create(isThemeCachingEnabled: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateUpdateSettingsRequest(settings, webClient.AntiforgeryToken));
|
||||
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.True(json.RootElement.GetProperty("data").GetProperty("isUpdated").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the update request that sends the given <paramref name="settings"/> to the user settings endpoint.
|
||||
/// </summary>
|
||||
/// <param name="settings">The user settings to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured update request.</returns>
|
||||
private static HttpRequestMessage CreateUpdateSettingsRequest(UserSettingsDto settings, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-user-settings")
|
||||
{
|
||||
Content = JsonContent.Create(settings)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return updateRequest;
|
||||
}
|
||||
}
|
||||
+8
-32
@@ -1,19 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryMetadataProviders;
|
||||
@@ -30,6 +25,8 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture<LuminaApiF
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryMetadataProvidersEndpointTests"/> class.
|
||||
@@ -74,7 +71,7 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture<LuminaApiF
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedConfigurationAsync(libraryId, userId);
|
||||
await SeedConfigurationAsync(libraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/metadata-providers");
|
||||
@@ -102,17 +99,7 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture<LuminaApiF
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
@@ -121,23 +108,12 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture<LuminaApiF
|
||||
/// 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="userId">The Id of the user that owns the data.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, Guid userId)
|
||||
private async Task SeedConfigurationAsync(Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
PluginId = Guid.NewGuid(),
|
||||
IsEnabled = true,
|
||||
Rank = 1,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+7
-25
@@ -1,18 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
using Lumina.Presentation.Api.SecurityTests.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.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetPluginSettings;
|
||||
@@ -29,6 +24,7 @@ public class GetPluginSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly PluginEntityFixture _pluginEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginSettingsEndpointTests"/> class.
|
||||
@@ -71,8 +67,8 @@ public class GetPluginSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// Arrange
|
||||
// authenticate with an admin user and seed a plugin, so a valid pluginId would reach the handler
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
await SeedPluginAsync(userId);
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
await SeedPluginAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/plugins/{Uri.EscapeDataString(maliciousPluginId)}/settings");
|
||||
@@ -91,28 +87,14 @@ public class GetPluginSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="PluginEntity"/> created by <paramref name="userId"/>.
|
||||
/// Seeds a <see cref="PluginEntity"/> created by the authenticated admin user.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the creator.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedPluginAsync(Guid userId)
|
||||
private async Task SeedPluginAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Plugins.Add(new PluginEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Test Plugin",
|
||||
Author = "Test Author",
|
||||
Version = "1.0.0",
|
||||
Description = "A test plugin.",
|
||||
LoadStatus = PluginLoadStatus.Loaded,
|
||||
LoadError = null,
|
||||
SettingsJson = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Plugins.Add(_pluginEntityFixture.Create(name: "Test Plugin", loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+14
-36
@@ -1,21 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
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.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders;
|
||||
@@ -32,6 +28,9 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<Lumina
|
||||
{
|
||||
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.
|
||||
@@ -48,9 +47,9 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<Lumina
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
ReorderLibraryMetadataProvidersRequest request = new(
|
||||
LibraryId: Guid.NewGuid(),
|
||||
PluginIds: [Guid.NewGuid()]
|
||||
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(
|
||||
libraryId: Guid.NewGuid(),
|
||||
pluginIds: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -80,8 +79,8 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<Lumina
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedConfigurationAsync(libraryId, userId, rank: 1);
|
||||
await SeedConfigurationAsync(libraryId, userId, rank: 2);
|
||||
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
|
||||
@@ -113,17 +112,7 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<Lumina
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
@@ -132,24 +121,13 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<Lumina
|
||||
/// 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="userId">The Id of the user that owns the data.</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 userId, int rank)
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, int rank)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
PluginId = Guid.NewGuid(),
|
||||
IsEnabled = true,
|
||||
Rank = rank,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+12
-42
@@ -1,21 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
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.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled;
|
||||
@@ -32,6 +28,9 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<Lumi
|
||||
{
|
||||
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.
|
||||
@@ -49,11 +48,7 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<Lumi
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string pluginId = Guid.NewGuid().ToString();
|
||||
SetLibraryMetadataProviderEnabledRequest request = new(
|
||||
LibraryId: Guid.NewGuid(),
|
||||
PluginId: Guid.NewGuid(),
|
||||
IsEnabled: true
|
||||
);
|
||||
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request);
|
||||
@@ -82,12 +77,8 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<Lumi
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedConfigurationAsync(libraryId, userId);
|
||||
SetLibraryMetadataProviderEnabledRequest request = new(
|
||||
LibraryId: libraryId,
|
||||
PluginId: Guid.NewGuid(),
|
||||
IsEnabled: true
|
||||
);
|
||||
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);
|
||||
@@ -115,17 +106,7 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<Lumi
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
@@ -134,23 +115,12 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<Lumi
|
||||
/// 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="userId">The Id of the user that owns the data.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, Guid userId)
|
||||
private async Task SeedConfigurationAsync(Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
PluginId = Guid.NewGuid(),
|
||||
IsEnabled = false,
|
||||
Rank = 1,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+15
-29
@@ -1,5 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
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.Plugins;
|
||||
@@ -7,14 +9,10 @@ using Lumina.Presentation.Api.SecurityTests.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.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.UpdatePluginSettings;
|
||||
@@ -31,6 +29,8 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly PluginEntityFixture _pluginEntityFixture = new();
|
||||
private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePluginSettingsEndpointTests"/> class.
|
||||
@@ -47,9 +47,9 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
// Arrange
|
||||
string pluginId = Guid.NewGuid().ToString();
|
||||
UpdatePluginSettingsRequest request = new(
|
||||
PluginId: Guid.NewGuid(),
|
||||
Settings: new Dictionary<string, string> { ["Key"] = "Value" }
|
||||
UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create(
|
||||
pluginId: Guid.NewGuid(),
|
||||
settings: new Dictionary<string, string> { ["Key"] = "Value" }
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -76,11 +76,11 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
Guid pluginId = await SeedPluginAsync(userId);
|
||||
UpdatePluginSettingsRequest request = new(
|
||||
PluginId: pluginId,
|
||||
Settings: new Dictionary<string, string> { ["Key"] = maliciousValue }
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
Guid pluginId = await SeedPluginAsync();
|
||||
UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create(
|
||||
pluginId: pluginId,
|
||||
settings: new Dictionary<string, string> { ["Key"] = maliciousValue }
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -107,29 +107,15 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="PluginEntity"/> created by <paramref name="userId"/>.
|
||||
/// Seeds a <see cref="PluginEntity"/> created by the authenticated admin user.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the creator.</param>
|
||||
/// <returns>The Id of the seeded plugin.</returns>
|
||||
private async Task<Guid> SeedPluginAsync(Guid userId)
|
||||
private async Task<Guid> SeedPluginAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
dbContext.Plugins.Add(new PluginEntity
|
||||
{
|
||||
Id = pluginId,
|
||||
Name = "Test Plugin",
|
||||
Author = "Test Author",
|
||||
Version = "1.0.0",
|
||||
Description = "A test plugin.",
|
||||
LoadStatus = PluginLoadStatus.Loaded,
|
||||
LoadError = null,
|
||||
SettingsJson = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Plugins.Add(_pluginEntityFixture.Create(id: pluginId, name: "Test Plugin", loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return pluginId;
|
||||
}
|
||||
|
||||
+8
-15
@@ -1,16 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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;
|
||||
@@ -31,6 +30,8 @@ public class GetUserSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointTests"/> class.
|
||||
@@ -95,20 +96,12 @@ public class GetUserSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
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);
|
||||
|
||||
+28
-30
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Requests.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -8,10 +10,8 @@ using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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;
|
||||
@@ -32,6 +32,9 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointTests"/> class.
|
||||
@@ -47,11 +50,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
public async Task UpdateUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = new(
|
||||
IsPaginationEnabled: true,
|
||||
ItemsPerPage: 48,
|
||||
IgnoreThePrefixForAlphaPicker: false,
|
||||
IsThemeCachingEnabled: true
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: true,
|
||||
itemsPerPage: 48,
|
||||
shouldIgnoreThePrefixForAlphaPicker: false,
|
||||
isThemeCachingEnabled: true,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -77,11 +81,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest request = new(
|
||||
IsPaginationEnabled: true,
|
||||
ItemsPerPage: int.MaxValue,
|
||||
IgnoreThePrefixForAlphaPicker: false,
|
||||
IsThemeCachingEnabled: true
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: true,
|
||||
itemsPerPage: int.MaxValue,
|
||||
shouldIgnoreThePrefixForAlphaPicker: false,
|
||||
isThemeCachingEnabled: true,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -100,11 +105,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest request = new(
|
||||
IsPaginationEnabled: true,
|
||||
ItemsPerPage: int.MinValue,
|
||||
IgnoreThePrefixForAlphaPicker: false,
|
||||
IsThemeCachingEnabled: true
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: true,
|
||||
itemsPerPage: int.MinValue,
|
||||
shouldIgnoreThePrefixForAlphaPicker: false,
|
||||
isThemeCachingEnabled: true,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -132,20 +138,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
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);
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings;
|
||||
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;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings.GetUserSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/{culture}/tools/settings/api-get-user-settings</c> route served by the <see cref="GetUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserSettingsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetUserSettingsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserSettings_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-user-settings");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(getRequest);
|
||||
|
||||
// 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 == "users/me/settings");
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings;
|
||||
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.Tools.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/{culture}/tools/settings</c> route served by the <see cref="SettingsViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SettingsViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SettingsViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SettingsViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SettingsView_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/en-us/tools/settings");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
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.Tools.Settings.UpdateUserSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/{culture}/tools/settings/api-update-user-settings</c> route served by the <see cref="UpdateUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdateUserSettingsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-user-settings")
|
||||
{
|
||||
Content = JsonContent.Create(_userSettingsDtoFixture.Create())
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
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 == "users/me/settings");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-user-settings")
|
||||
{
|
||||
Content = JsonContent.Create(_userSettingsDtoFixture.Create())
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings");
|
||||
}
|
||||
}
|
||||
+45
-42
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.Diagnostics.CodeAnalysis;
|
||||
@@ -14,20 +15,22 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddMediaLibraryRequestMappingTests
|
||||
{
|
||||
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AddLibraryRequest request = new(
|
||||
"My Library",
|
||||
"Book",
|
||||
["C:/Books", "D:/Media/Books"],
|
||||
"D:/poster.jpg",
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: "My Library",
|
||||
libraryType: "Book",
|
||||
contentLocations: ["C:/Books", "D:/Media/Books"],
|
||||
coverImage: "D:/poster.jpg",
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -41,7 +44,7 @@ public class AddMediaLibraryRequestMappingTests
|
||||
Assert.Equal(request.CoverImage, result.CoverImage);
|
||||
Assert.Equal(request.IsEnabled, result.IsEnabled);
|
||||
Assert.Equal(request.IsLocked, result.IsLocked);
|
||||
Assert.Equal(request.DownloadMetadataFromWeb, result.DownloadMetadataFromWeb);
|
||||
Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb);
|
||||
Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories);
|
||||
}
|
||||
|
||||
@@ -53,16 +56,16 @@ public class AddMediaLibraryRequestMappingTests
|
||||
public void ToCommand_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType)
|
||||
{
|
||||
// Arrange
|
||||
AddLibraryRequest request = new(
|
||||
"My Library",
|
||||
libraryType.ToString(),
|
||||
["C:/Media"],
|
||||
"D:/poster.jpg",
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: "My Library",
|
||||
libraryType: libraryType.ToString(),
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: "D:/poster.jpg",
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -76,7 +79,7 @@ public class AddMediaLibraryRequestMappingTests
|
||||
Assert.Equal(request.CoverImage, result.CoverImage);
|
||||
Assert.Equal(request.IsEnabled, result.IsEnabled);
|
||||
Assert.Equal(request.IsLocked, result.IsLocked);
|
||||
Assert.Equal(request.DownloadMetadataFromWeb, result.DownloadMetadataFromWeb);
|
||||
Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb);
|
||||
Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories);
|
||||
}
|
||||
|
||||
@@ -92,16 +95,16 @@ public class AddMediaLibraryRequestMappingTests
|
||||
"F:/Reading Material"
|
||||
];
|
||||
|
||||
AddLibraryRequest request = new(
|
||||
"My Library",
|
||||
"Book",
|
||||
contentLocations,
|
||||
"D:/poster.jpg",
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: "My Library",
|
||||
libraryType: "Book",
|
||||
contentLocations: contentLocations,
|
||||
coverImage: "D:/poster.jpg",
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -122,16 +125,16 @@ public class AddMediaLibraryRequestMappingTests
|
||||
"D:/Books"
|
||||
];
|
||||
|
||||
AddLibraryRequest request = new(
|
||||
"My Library",
|
||||
"Book",
|
||||
contentLocations,
|
||||
null,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: "My Library",
|
||||
libraryType: "Book",
|
||||
contentLocations: contentLocations,
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false
|
||||
);
|
||||
|
||||
// Act
|
||||
|
||||
+30
-77
@@ -1,9 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -17,28 +17,17 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryEntityMappingTests
|
||||
{
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidLibraryEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity entity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = "My Library",
|
||||
LibraryType = LibraryType.Book,
|
||||
ContentLocations =
|
||||
[
|
||||
new() { Path = "C:/Books" },
|
||||
new() { Path = "D:/Media/Books" }
|
||||
],
|
||||
CoverImage = "D:/myPoster.jpg",
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null,
|
||||
LibraryScans = []
|
||||
};
|
||||
LibraryEntity entity = _libraryEntityFixture.Create(
|
||||
title: "My Library",
|
||||
libraryType: LibraryType.Book,
|
||||
contentLocations: ["C:/Books", "D:/Media/Books"],
|
||||
coverImage: "D:/myPoster.jpg");
|
||||
|
||||
// Act
|
||||
LibraryResponse result = entity.ToResponse();
|
||||
@@ -63,19 +52,11 @@ public class LibraryEntityMappingTests
|
||||
public void ToResponse_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType)
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity entity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = "My Library",
|
||||
LibraryType = libraryType,
|
||||
ContentLocations = [new() { Path = "C:/Media" }],
|
||||
CoverImage = "D:/myPoster.jpg",
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
};
|
||||
LibraryEntity entity = _libraryEntityFixture.Create(
|
||||
title: "My Library",
|
||||
libraryType: libraryType,
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: "D:/myPoster.jpg");
|
||||
|
||||
// Act
|
||||
LibraryResponse result = entity.ToResponse();
|
||||
@@ -89,25 +70,11 @@ public class LibraryEntityMappingTests
|
||||
public void ToResponse_WhenMappingMultipleContentLocations_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity entity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = "My Library",
|
||||
LibraryType = LibraryType.Book,
|
||||
ContentLocations =
|
||||
[
|
||||
new() { Path = "C:/Media/Books" },
|
||||
new() { Path = "D:/Books" },
|
||||
new() { Path = "E:/Digital Library/Books" },
|
||||
new() { Path = "F:/Reading Material" }
|
||||
],
|
||||
CoverImage = "D:/myPoster.jpg",
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
};
|
||||
LibraryEntity entity = _libraryEntityFixture.Create(
|
||||
title: "My Library",
|
||||
libraryType: LibraryType.Book,
|
||||
contentLocations: ["C:/Media/Books", "D:/Books", "E:/Digital Library/Books", "F:/Reading Material"],
|
||||
coverImage: "D:/myPoster.jpg");
|
||||
|
||||
// Act
|
||||
LibraryResponse result = entity.ToResponse();
|
||||
@@ -122,19 +89,12 @@ public class LibraryEntityMappingTests
|
||||
{
|
||||
// Arrange
|
||||
DateTime updated = DateTime.UtcNow.AddDays(-1);
|
||||
LibraryEntity entity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = "My Library",
|
||||
LibraryType = LibraryType.Book,
|
||||
ContentLocations = [new() { Path = "C:/Books" }],
|
||||
CoverImage = "D:/myPoster.jpg",
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedOnUtc = updated,
|
||||
UpdatedBy = Guid.NewGuid()
|
||||
};
|
||||
LibraryEntity entity = _libraryEntityFixture.Create(
|
||||
title: "My Library",
|
||||
libraryType: LibraryType.Book,
|
||||
contentLocations: ["C:/Books"],
|
||||
coverImage: "D:/myPoster.jpg");
|
||||
entity.UpdatedOnUtc = updated;
|
||||
|
||||
// Act
|
||||
LibraryResponse result = entity.ToResponse();
|
||||
@@ -149,19 +109,12 @@ public class LibraryEntityMappingTests
|
||||
{
|
||||
// Arrange
|
||||
DateTime updated = DateTime.UtcNow.AddDays(-1);
|
||||
LibraryEntity entity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = "My Library",
|
||||
LibraryType = LibraryType.Book,
|
||||
ContentLocations = [new() { Path = "C:/Books" }],
|
||||
CoverImage = null,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedOnUtc = updated,
|
||||
UpdatedBy = Guid.NewGuid()
|
||||
};
|
||||
LibraryEntity entity = _libraryEntityFixture.Create(
|
||||
title: "My Library",
|
||||
libraryType: LibraryType.Book,
|
||||
contentLocations: ["C:/Books"]);
|
||||
entity.CoverImage = null;
|
||||
entity.UpdatedOnUtc = updated;
|
||||
|
||||
// Act
|
||||
LibraryResponse result = entity.ToResponse();
|
||||
|
||||
+4
-5
@@ -3,7 +3,6 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
@@ -34,7 +33,7 @@ public class LibraryMappingTests
|
||||
coverImage: "D:/myPoster.jpg",
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
downloadMetadataFromWeb: true,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
scanIds: [Guid.NewGuid()]);
|
||||
@@ -54,7 +53,7 @@ public class LibraryMappingTests
|
||||
Assert.Equal(library.UpdatedOnUtc, result.UpdatedOnUtc);
|
||||
Assert.True(result.IsEnabled);
|
||||
Assert.False(result.IsLocked);
|
||||
Assert.True(result.DownloadMetadataFromWeb);
|
||||
Assert.True(result.CanDownloadMetadataFromWeb);
|
||||
Assert.False(result.ShouldSaveMetadataInMediaDirectories);
|
||||
Assert.Equal(library.ScanIds.Select(scanId => scanId.Value), result.LibraryScans.Select(libraryScan => libraryScan.Id));
|
||||
}
|
||||
@@ -93,7 +92,7 @@ public class LibraryMappingTests
|
||||
coverImage: "D:/myPoster.jpg",
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
downloadMetadataFromWeb: true,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false);
|
||||
|
||||
// Act
|
||||
@@ -105,7 +104,7 @@ public class LibraryMappingTests
|
||||
Assert.Equal(library.CoverImage, result.CoverImage);
|
||||
Assert.True(result.IsEnabled);
|
||||
Assert.False(result.IsLocked);
|
||||
Assert.True(result.DownloadMetadataFromWeb);
|
||||
Assert.True(result.CanDownloadMetadataFromWeb);
|
||||
Assert.False(result.ShouldSaveMetadataInMediaDirectories);
|
||||
}
|
||||
|
||||
|
||||
+11
-2
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.UsersManagement.Users;
|
||||
using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Requests.UsersManagement.Settings;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
@@ -13,11 +14,19 @@ namespace Lumina.Application.UnitTests.Common.Mapping.UsersManagement.Users;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsRequestMappingTests
|
||||
{
|
||||
private readonly UpdateUserSettingsRequestFixture _requestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = new(IsPaginationEnabled: true, ItemsPerPage: 48, IgnoreThePrefixForAlphaPicker: false, IsThemeCachingEnabled: true);
|
||||
UpdateUserSettingsRequest request = _requestFixture.Create(
|
||||
isPaginationEnabled: true,
|
||||
itemsPerPage: 48,
|
||||
shouldIgnoreThePrefixForAlphaPicker: false,
|
||||
isThemeCachingEnabled: true,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
UpdateUserSettingsCommand result = request.ToCommand();
|
||||
@@ -26,7 +35,7 @@ public class UpdateUserSettingsRequestMappingTests
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(request.IsPaginationEnabled, result.IsPaginationEnabled);
|
||||
Assert.Equal(request.ItemsPerPage, result.ItemsPerPage);
|
||||
Assert.Equal(request.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(request.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(request.IsThemeCachingEnabled, result.IsThemeCachingEnabled);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -33,7 +33,7 @@ public class UserSettingsEntityMappingTests
|
||||
Assert.Equal(entity.UserId, result.Value.UserId.Value);
|
||||
Assert.Equal(entity.IsPaginationEnabled, result.Value.IsPaginationEnabled);
|
||||
Assert.Equal(entity.ItemsPerPage, result.Value.ItemsPerPage);
|
||||
Assert.Equal(entity.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(entity.ShouldIgnoreThePrefixForAlphaPicker, result.Value.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(entity.IsThemeCachingEnabled, result.Value.IsThemeCachingEnabled);
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ public class UserSettingsEntityMappingTests
|
||||
Assert.Equal(entity.UserId, result.UserId);
|
||||
Assert.Equal(entity.IsPaginationEnabled, result.IsPaginationEnabled);
|
||||
Assert.Equal(entity.ItemsPerPage, result.ItemsPerPage);
|
||||
Assert.Equal(entity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(entity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(entity.IsThemeCachingEnabled, result.IsThemeCachingEnabled);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -34,7 +34,7 @@ public class UserSettingsMappingTests
|
||||
Assert.Equal(userId, result.UserId);
|
||||
Assert.Equal(domainEntity.IsPaginationEnabled, result.IsPaginationEnabled);
|
||||
Assert.Equal(domainEntity.ItemsPerPage, result.ItemsPerPage);
|
||||
Assert.Equal(domainEntity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(domainEntity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -52,6 +52,6 @@ public class UserSettingsMappingTests
|
||||
Assert.Equal(userId, result.UserId);
|
||||
Assert.Equal(domainEntity.IsPaginationEnabled, result.IsPaginationEnabled);
|
||||
Assert.Equal(domainEntity.ItemsPerPage, result.ItemsPerPage);
|
||||
Assert.Equal(domainEntity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(domainEntity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
}
|
||||
}
|
||||
+62
-7
@@ -2,17 +2,22 @@
|
||||
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 System.Diagnostics.CodeAnalysis;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
|
||||
@@ -25,8 +30,13 @@ 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 _configurationEntityFixture = new();
|
||||
private readonly ReorderLibraryMetadataProvidersCommandFixture _reorderLibraryMetadataProvidersCommandFixture = new();
|
||||
private readonly Guid _userId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReorderLibraryMetadataProvidersCommandHandlerTests"/> class.
|
||||
@@ -36,10 +46,18 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_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(_mockUnitOfWork, _mockValidator);
|
||||
_sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -47,16 +65,15 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryMetadataProviderConfigurationEntityFixture configurationFixture = new();
|
||||
LibraryMetadataProviderConfigurationEntity firstProvider = configurationFixture.Create(libraryId, Guid.NewGuid(), 2);
|
||||
LibraryMetadataProviderConfigurationEntity secondProvider = configurationFixture.Create(libraryId, Guid.NewGuid(), 1);
|
||||
LibraryMetadataProviderConfigurationEntity firstProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2);
|
||||
LibraryMetadataProviderConfigurationEntity secondProvider = _configurationEntityFixture.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(new ReorderLibraryMetadataProvidersCommand(libraryId, [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None);
|
||||
Result<Success> result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -76,7 +93,7 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests
|
||||
_mockValidator.Validate(Arg.Any<ReorderLibraryMetadataProvidersCommand>()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(new ReorderLibraryMetadataProvidersCommand(libraryId, [Guid.NewGuid()]), CancellationToken.None);
|
||||
Result<Success> result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
@@ -85,4 +102,42 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests
|
||||
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>());
|
||||
}
|
||||
}
|
||||
+72
-16
@@ -2,16 +2,22 @@
|
||||
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 System.Diagnostics.CodeAnalysis;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
|
||||
@@ -24,8 +30,17 @@ 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.
|
||||
@@ -35,10 +50,18 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_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(_mockUnitOfWork, _mockValidator);
|
||||
_sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -55,7 +78,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests
|
||||
.Returns(Result.Updated);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, true), CancellationToken.None);
|
||||
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -68,24 +91,18 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests
|
||||
public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState()
|
||||
{
|
||||
// Arrange
|
||||
LibraryMetadataProviderConfigurationEntity existingConfiguration = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = Guid.NewGuid(),
|
||||
PluginId = Guid.NewGuid(),
|
||||
IsEnabled = false,
|
||||
Rank = 2,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
};
|
||||
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(new SetLibraryMetadataProviderEnabledCommand(existingConfiguration.LibraryId, existingConfiguration.PluginId, true), CancellationToken.None);
|
||||
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -103,7 +120,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests
|
||||
_mockValidator.Validate(Arg.Any<SetLibraryMetadataProviderEnabledCommand>()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, true), CancellationToken.None);
|
||||
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
@@ -112,4 +129,43 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests
|
||||
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>());
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -3,14 +3,15 @@ using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings;
|
||||
using Lumina.Application.Fixtures.Core.Plugins.Commands.UpdatePluginSettings;
|
||||
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 System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.UpdatePluginSettings;
|
||||
@@ -25,6 +26,7 @@ public class UpdatePluginSettingsCommandHandlerTests
|
||||
private readonly IPluginRepository _mockPluginRepository;
|
||||
private readonly IValidator<UpdatePluginSettingsCommand> _mockValidator;
|
||||
private readonly UpdatePluginSettingsCommandHandler _sut;
|
||||
private readonly UpdatePluginSettingsCommandFixture _updatePluginSettingsCommandFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePluginSettingsCommandHandlerTests"/> class.
|
||||
@@ -50,7 +52,7 @@ public class UpdatePluginSettingsCommandHandlerTests
|
||||
.Returns(Result.Updated);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None);
|
||||
Result<Success> result = await _sut.HandleAsync(_updatePluginSettingsCommandFixture.Create(pluginId: pluginId, settings: settings), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -67,7 +69,7 @@ public class UpdatePluginSettingsCommandHandlerTests
|
||||
_mockValidator.Validate(Arg.Any<UpdatePluginSettingsCommand>()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None);
|
||||
Result<Success> result = await _sut.HandleAsync(_updatePluginSettingsCommandFixture.Create(pluginId: pluginId, settings: settings), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
|
||||
+74
-1
@@ -2,10 +2,15 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryMetadataProviders;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
@@ -13,6 +18,7 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryMetadataProviders;
|
||||
@@ -26,10 +32,14 @@ public class GetLibraryMetadataProvidersQueryHandlerTests
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryMetadataProviderConfigurationRepository _mockLibraryMetadataProviderConfigurationRepository;
|
||||
private readonly IPluginRepository _mockPluginRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<GetLibraryMetadataProvidersQuery> _mockValidator;
|
||||
private readonly GetLibraryMetadataProvidersQueryHandler _sut;
|
||||
private readonly GetLibraryMetadataProvidersQueryFixture _getLibraryMetadataProvidersQueryFixture = new();
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new();
|
||||
private readonly PluginEntityFixture _pluginEntityFixture = new();
|
||||
private readonly Guid _userId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryMetadataProvidersQueryHandlerTests"/> class.
|
||||
@@ -41,8 +51,34 @@ public class GetLibraryMetadataProvidersQueryHandlerTests
|
||||
_mockPluginRepository = Substitute.For<IPluginRepository>();
|
||||
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockLibraryMetadataProviderConfigurationRepository);
|
||||
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<GetLibraryMetadataProvidersQuery>>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
_sut = new GetLibraryMetadataProvidersQueryHandler(_mockUnitOfWork);
|
||||
// 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<GetLibraryMetadataProvidersQuery>()).Returns([]);
|
||||
|
||||
_sut = new GetLibraryMetadataProvidersQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryIdIsEmpty_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<GetLibraryMetadataProvidersQuery>()).Returns([Errors.Plugins.LibraryIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<LibraryMetadataProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
await _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -155,4 +191,41 @@ public class GetLibraryMetadataProvidersQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create();
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<LibraryMetadataProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == query.LibraryId), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<LibraryMetadataProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders;
|
||||
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryMetadataProviders;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryMetadataProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibraryMetadataProvidersQueryValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryMetadataProvidersQueryValidatorTests
|
||||
{
|
||||
private readonly GetLibraryMetadataProvidersQueryValidator _validator = new();
|
||||
private readonly GetLibraryMetadataProvidersQueryFixture _getLibraryMetadataProvidersQueryFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create();
|
||||
query = query with { LibraryId = Guid.Empty };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+25
-5
@@ -3,15 +3,15 @@ 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.Plugins;
|
||||
using Lumina.Application.Common.Mapping.Plugins;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.Plugins.Queries.GetPluginSettings;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetPluginSettings;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Lumina.Plugins.Contracts.Fixtures.Common.Models.DTO.Settings;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -33,9 +33,11 @@ public class GetPluginSettingsQueryHandlerTests
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IPluginRepository _mockPluginRepository;
|
||||
private readonly IPluginManager _mockPluginManager;
|
||||
private readonly IValidator<GetPluginSettingsQuery> _mockValidator;
|
||||
private readonly GetPluginSettingsQueryHandler _sut;
|
||||
private readonly GetPluginSettingsQueryFixture _getPluginSettingsQueryFixture = new();
|
||||
private readonly PluginEntityFixture _pluginEntityFixture = new();
|
||||
private readonly PluginSettingDescriptorDtoFixture _pluginSettingDescriptorDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginSettingsQueryHandlerTests"/> class.
|
||||
@@ -46,8 +48,26 @@ public class GetPluginSettingsQueryHandlerTests
|
||||
_mockPluginRepository = Substitute.For<IPluginRepository>();
|
||||
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
|
||||
_mockPluginManager = Substitute.For<IPluginManager>();
|
||||
_mockValidator = Substitute.For<IValidator<GetPluginSettingsQuery>>();
|
||||
_mockValidator.Validate(Arg.Any<GetPluginSettingsQuery>()).Returns([]);
|
||||
|
||||
_sut = new GetPluginSettingsQueryHandler(_mockUnitOfWork, _mockPluginManager);
|
||||
_sut = new GetPluginSettingsQueryHandler(_mockUnitOfWork, _mockPluginManager, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPluginIdIsEmpty_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<GetPluginSettingsQuery>()).Returns([DomainErrors.Plugins.PluginIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<PluginSettingsResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Plugins.PluginIdCannotBeEmpty, result.FirstError);
|
||||
await _mockPluginRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -62,8 +82,8 @@ public class GetPluginSettingsQueryHandlerTests
|
||||
IPlugin loadedPlugin = Substitute.For<IPlugin>();
|
||||
loadedPlugin.GetSettingsSchema().Returns(
|
||||
[
|
||||
new PluginSettingDescriptorDto("key1", "Label 1", PluginSettingType.Text, "default"),
|
||||
new PluginSettingDescriptorDto("key2", "Label 2", PluginSettingType.Select, null, ["a", "b"])
|
||||
_pluginSettingDescriptorDtoFixture.Create(key: "key1", label: "Label 1", type: PluginSettingType.Text, defaultValue: "default"),
|
||||
_pluginSettingDescriptorDtoFixture.Create(key: "key2", label: "Label 2", type: PluginSettingType.Select, allowedValues: ["a", "b"])
|
||||
]);
|
||||
_mockPluginManager.GetPlugin(query.PluginId).Returns(loadedPlugin);
|
||||
IReadOnlyDictionary<string, string>? expectedSettings = JsonSerializer.Deserialize<Dictionary<string, string>>(plugin.SettingsJson!);
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Plugins.Queries.GetPluginSettings;
|
||||
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetPluginSettings;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetPluginSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPluginSettingsQueryValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPluginSettingsQueryValidatorTests
|
||||
{
|
||||
private readonly GetPluginSettingsQueryValidator _validator = new();
|
||||
private readonly GetPluginSettingsQueryFixture _getPluginSettingsQueryFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create();
|
||||
query = query with { PluginId = Guid.Empty };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPluginIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -74,7 +74,7 @@ public class UpdateUserSettingsCommandHandlerTests
|
||||
settings.UserId == _userId &&
|
||||
settings.IsPaginationEnabled == command.IsPaginationEnabled &&
|
||||
settings.ItemsPerPage == command.ItemsPerPage &&
|
||||
settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker),
|
||||
settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
@@ -102,7 +102,7 @@ public class UpdateUserSettingsCommandHandlerTests
|
||||
settings.UserId == _userId &&
|
||||
settings.IsPaginationEnabled == command.IsPaginationEnabled &&
|
||||
settings.ItemsPerPage == command.ItemsPerPage &&
|
||||
settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker),
|
||||
settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
|
||||
+8
-6
@@ -6,6 +6,7 @@ using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Queries.GetUserSettings;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using NSubstitute;
|
||||
@@ -28,6 +29,7 @@ public class GetUserSettingsQueryHandlerTests
|
||||
private readonly IUserSettingsRepository _mockUserSettingsRepository;
|
||||
private readonly GetUserSettingsQueryHandler _sut;
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly GetUserSettingsQueryFixture _getUserSettingsQueryFixture = new();
|
||||
private readonly Guid _userId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
@@ -49,7 +51,7 @@ public class GetUserSettingsQueryHandlerTests
|
||||
public async Task HandleAsync_WhenSettingsExist_ShouldReturnStoredSettings()
|
||||
{
|
||||
// Arrange
|
||||
GetUserSettingsQuery query = new();
|
||||
GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create();
|
||||
UserSettingsEntity storedSettings = _userSettingsEntityFixture.Create(userId: _userId);
|
||||
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(storedSettings));
|
||||
@@ -62,14 +64,14 @@ public class GetUserSettingsQueryHandlerTests
|
||||
Assert.Equal(storedSettings.UserId, result.Value.UserId);
|
||||
Assert.Equal(storedSettings.IsPaginationEnabled, result.Value.IsPaginationEnabled);
|
||||
Assert.Equal(storedSettings.ItemsPerPage, result.Value.ItemsPerPage);
|
||||
Assert.Equal(storedSettings.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(storedSettings.ShouldIgnoreThePrefixForAlphaPicker, result.Value.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSettingsDoNotExist_ShouldReturnDefaultSettings()
|
||||
{
|
||||
// Arrange
|
||||
GetUserSettingsQuery query = new();
|
||||
GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create();
|
||||
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(null));
|
||||
|
||||
@@ -81,14 +83,14 @@ public class GetUserSettingsQueryHandlerTests
|
||||
Assert.NotEqual(Guid.Empty, result.Value.UserId);
|
||||
Assert.True(result.Value.IsPaginationEnabled);
|
||||
Assert.Equal(48, result.Value.ItemsPerPage);
|
||||
Assert.False(result.Value.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
|
||||
{
|
||||
// Arrange
|
||||
GetUserSettingsQuery query = new();
|
||||
GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
@@ -104,7 +106,7 @@ public class GetUserSettingsQueryHandlerTests
|
||||
public async Task HandleAsync_WhenGetByIdReturnsError_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
GetUserSettingsQuery query = new();
|
||||
GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create();
|
||||
Error error = Error.Failure("Database.Error", "Failed to retrieve user settings");
|
||||
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
@@ -43,5 +43,6 @@
|
||||
<ProjectReference Include="..\..\Common\Lumina.Application.Fixtures\Lumina.Application.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Domain.Fixtures\Lumina.Domain.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Plugins.Contracts.Fixtures\Lumina.Plugins.Contracts.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
+24
-22
@@ -1,4 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
@@ -12,6 +13,7 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddLibraryRequestTests
|
||||
{
|
||||
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -21,16 +23,16 @@ public class AddLibraryRequestTests
|
||||
public void RoundTrip_WhenSerializingAddLibraryRequest_ShouldPreserveValues()
|
||||
{
|
||||
// Arrange
|
||||
AddLibraryRequest expected = new(
|
||||
"Books",
|
||||
"Book",
|
||||
[@"C:\Media\Books"],
|
||||
null,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
true
|
||||
AddLibraryRequest expected = _addLibraryRequestFixture.Create(
|
||||
title: "Books",
|
||||
libraryType: "Book",
|
||||
contentLocations: [@"C:\Media\Books"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -45,20 +47,20 @@ public class AddLibraryRequestTests
|
||||
public void Deconstruct_WhenCalled_ShouldReturnAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
AddLibraryRequest sut = new(
|
||||
"Books",
|
||||
"Book",
|
||||
[@"C:\Media\Books"],
|
||||
null,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
true
|
||||
AddLibraryRequest sut = _addLibraryRequestFixture.Create(
|
||||
title: "Books",
|
||||
libraryType: "Book",
|
||||
contentLocations: [@"C:\Media\Books"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
(string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut;
|
||||
(string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(sut.Title, title);
|
||||
@@ -67,7 +69,7 @@ public class AddLibraryRequestTests
|
||||
Assert.Equal(sut.CoverImage, coverImage);
|
||||
Assert.Equal(sut.IsEnabled, isEnabled);
|
||||
Assert.Equal(sut.IsLocked, isLocked);
|
||||
Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb);
|
||||
Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb);
|
||||
Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories);
|
||||
Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan);
|
||||
}
|
||||
|
||||
+28
-26
@@ -1,4 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -13,6 +14,7 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateLibraryRequestTests
|
||||
{
|
||||
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -24,18 +26,18 @@ public class UpdateLibraryRequestTests
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UpdateLibraryRequest expected = new(
|
||||
id,
|
||||
userId,
|
||||
"Books",
|
||||
"Book",
|
||||
[@"C:\Media\Books"],
|
||||
null,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
true
|
||||
UpdateLibraryRequest expected = _updateLibraryRequestFixture.Create(
|
||||
id: id,
|
||||
userId: userId,
|
||||
title: "Books",
|
||||
libraryType: "Book",
|
||||
contentLocations: [@"C:\Media\Books"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -52,22 +54,22 @@ public class UpdateLibraryRequestTests
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UpdateLibraryRequest sut = new(
|
||||
id,
|
||||
userId,
|
||||
"Books",
|
||||
"Book",
|
||||
[@"C:\Media\Books"],
|
||||
null,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
true
|
||||
UpdateLibraryRequest sut = _updateLibraryRequestFixture.Create(
|
||||
id: id,
|
||||
userId: userId,
|
||||
title: "Books",
|
||||
libraryType: "Book",
|
||||
contentLocations: [@"C:\Media\Books"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
(Guid sutId, Guid sutUserId, string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut;
|
||||
(Guid sutId, Guid sutUserId, string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(sut.Id, sutId);
|
||||
@@ -78,7 +80,7 @@ public class UpdateLibraryRequestTests
|
||||
Assert.Equal(sut.CoverImage, coverImage);
|
||||
Assert.Equal(sut.IsEnabled, isEnabled);
|
||||
Assert.Equal(sut.IsLocked, isLocked);
|
||||
Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb);
|
||||
Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb);
|
||||
Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories);
|
||||
Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan);
|
||||
}
|
||||
|
||||
+19
-4
@@ -1,4 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Requests.UsersManagement.Settings;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
@@ -12,6 +13,7 @@ namespace Lumina.Contracts.UnitTests.Requests.UsersManagement.Settings;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsRequestTests
|
||||
{
|
||||
private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -21,7 +23,13 @@ public class UpdateUserSettingsRequestTests
|
||||
public void RoundTrip_WhenSerializingUpdateUserSettingsRequest_ShouldPreserveValues()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest expected = new(true, 50, true, true);
|
||||
UpdateUserSettingsRequest expected = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: true,
|
||||
itemsPerPage: 50,
|
||||
shouldIgnoreThePrefixForAlphaPicker: true,
|
||||
isThemeCachingEnabled: true,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(expected, _jsonOptions);
|
||||
@@ -36,15 +44,22 @@ public class UpdateUserSettingsRequestTests
|
||||
public void Deconstruct_WhenCalled_ShouldReturnAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest sut = new(false, 25, false, false);
|
||||
UpdateUserSettingsRequest sut = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: false,
|
||||
itemsPerPage: 25,
|
||||
shouldIgnoreThePrefixForAlphaPicker: false,
|
||||
isThemeCachingEnabled: false,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
(bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker, bool isThemeCachingEnabled) = sut;
|
||||
(bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing) = sut;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled);
|
||||
Assert.Equal(sut.ItemsPerPage, itemsPerPage);
|
||||
Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled);
|
||||
Assert.Equal(sut.ShouldAggregateMetadataWhenMissing, shouldAggregateMetadataWhenMissing);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -58,7 +58,7 @@ public class LibraryResponseTests
|
||||
LibraryResponse sut = _libraryResponseFixture.Create();
|
||||
|
||||
// Act
|
||||
(Guid id, Guid userId, string title, LibraryType libraryType, List<string> contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, DateTime createdOnUtc, DateTime? updatedOnUtc) = sut;
|
||||
(Guid id, Guid userId, string title, LibraryType libraryType, List<string> contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, DateTime createdOnUtc, DateTime? updatedOnUtc) = sut;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(sut.Id, id);
|
||||
@@ -69,7 +69,7 @@ public class LibraryResponseTests
|
||||
Assert.Equal(sut.CoverImage, coverImage);
|
||||
Assert.Equal(sut.IsEnabled, isEnabled);
|
||||
Assert.Equal(sut.IsLocked, isLocked);
|
||||
Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb);
|
||||
Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb);
|
||||
Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories);
|
||||
Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan);
|
||||
Assert.Equal(sut.CreatedOnUtc, createdOnUtc);
|
||||
|
||||
+21
-4
@@ -1,4 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -13,6 +14,7 @@ namespace Lumina.Contracts.UnitTests.Responses.UsersManagement.Settings;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserSettingsResponseTests
|
||||
{
|
||||
private readonly UserSettingsResponseFixture _userSettingsResponseFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -23,7 +25,14 @@ public class UserSettingsResponseTests
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserSettingsResponse expected = new(userId, true, 50, true, true);
|
||||
UserSettingsResponse expected = _userSettingsResponseFixture.Create(
|
||||
userId: userId,
|
||||
isPaginationEnabled: true,
|
||||
itemsPerPage: 50,
|
||||
shouldIgnoreThePrefixForAlphaPicker: true,
|
||||
isThemeCachingEnabled: true,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(expected, _jsonOptions);
|
||||
@@ -39,16 +48,24 @@ public class UserSettingsResponseTests
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserSettingsResponse sut = new(userId, false, 25, false, false);
|
||||
UserSettingsResponse sut = _userSettingsResponseFixture.Create(
|
||||
userId: userId,
|
||||
isPaginationEnabled: false,
|
||||
itemsPerPage: 25,
|
||||
shouldIgnoreThePrefixForAlphaPicker: false,
|
||||
isThemeCachingEnabled: false,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
(Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker, bool isThemeCachingEnabled) = sut;
|
||||
(Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing) = sut;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(sut.UserId, sutUserId);
|
||||
Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled);
|
||||
Assert.Equal(sut.ItemsPerPage, itemsPerPage);
|
||||
Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled);
|
||||
Assert.Equal(sut.ShouldAggregateMetadataWhenMissing, shouldAggregateMetadataWhenMissing);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -53,7 +53,7 @@ public class LibraryConfigurationTests
|
||||
IProperty titleProperty = entityType.GetProperty(nameof(LibraryEntity.Title));
|
||||
IProperty libraryTypeProperty = entityType.GetProperty(nameof(LibraryEntity.LibraryType));
|
||||
IProperty isEnabledProperty = entityType.GetProperty(nameof(LibraryEntity.IsEnabled));
|
||||
IProperty downloadMetadataProperty = entityType.GetProperty(nameof(LibraryEntity.DownloadMetadataFromWeb));
|
||||
IProperty downloadMetadataProperty = entityType.GetProperty(nameof(LibraryEntity.CanDownloadMetadataFromWeb));
|
||||
|
||||
// Assert
|
||||
Assert.False(titleProperty.IsNullable);
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ public class UserSettingsConfigurationTests
|
||||
IProperty userIdProperty = entityType.GetProperty(nameof(UserSettingsEntity.UserId));
|
||||
IProperty isPaginationEnabledProperty = entityType.GetProperty(nameof(UserSettingsEntity.IsPaginationEnabled));
|
||||
IProperty itemsPerPageProperty = entityType.GetProperty(nameof(UserSettingsEntity.ItemsPerPage));
|
||||
IProperty ignoreThePrefixProperty = entityType.GetProperty(nameof(UserSettingsEntity.IgnoreThePrefixForAlphaPicker));
|
||||
IProperty ignoreThePrefixProperty = entityType.GetProperty(nameof(UserSettingsEntity.ShouldIgnoreThePrefixForAlphaPicker));
|
||||
|
||||
// Assert
|
||||
Assert.False(userIdProperty.IsNullable);
|
||||
|
||||
+36
-26
@@ -4,7 +4,10 @@ using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Filtering;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.DataAccess.Core.Repositories.Books;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
@@ -32,6 +35,13 @@ public class BookRepositoryTests
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly BookRepository _sut;
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookRatingEntityFixture _bookRatingEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly IsbnEntityFixture _isbnEntityFixture = new();
|
||||
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
|
||||
private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new();
|
||||
private readonly BaseFilterDtoFixture _baseFilterDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookRepositoryTests"/> class.
|
||||
@@ -83,12 +93,12 @@ public class BookRepositoryTests
|
||||
public async Task InsertAsync_WhenExistingTagsFound_ShouldReplaceTagsWithExistingOnes()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity existingTag = new("Existing");
|
||||
TagEntity existingTag = _tagEntityFixture.Create(name: "Existing");
|
||||
_mockContext.Set<TagEntity>().Add(existingTag);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
BookEntity bookModel = _bookEntityFixture.Create();
|
||||
bookModel.Tags = [new("Existing"), new("New")];
|
||||
bookModel.Tags = [_tagEntityFixture.Create(name: "Existing"), _tagEntityFixture.Create(name: "New")];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
|
||||
@@ -110,12 +120,12 @@ public class BookRepositoryTests
|
||||
public async Task InsertAsync_WhenExistingGenresFound_ShouldReplaceGenresWithExistingOnes()
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity existingGenre = new("Existing");
|
||||
GenreEntity existingGenre = _genreEntityFixture.Create(name: "Existing");
|
||||
_mockContext.Set<GenreEntity>().Add(existingGenre);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
BookEntity bookModel = _bookEntityFixture.Create();
|
||||
bookModel.Genres = [new("Existing"), new("New")];
|
||||
bookModel.Genres = [_genreEntityFixture.Create(name: "Existing"), _genreEntityFixture.Create(name: "New")];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
|
||||
@@ -168,9 +178,9 @@ public class BookRepositoryTests
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")];
|
||||
book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")];
|
||||
book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)];
|
||||
book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")];
|
||||
book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")];
|
||||
book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)];
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
@@ -341,8 +351,8 @@ public class BookRepositoryTests
|
||||
_mockContext.Books.AddRange(books);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
|
||||
LibraryFilterDto filter = new() { LibraryId = libraryId };
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
|
||||
@@ -360,8 +370,8 @@ public class BookRepositoryTests
|
||||
public async Task GetPaginatedAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
|
||||
BaseFilterDto filter = new();
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
BaseFilterDto filter = _baseFilterDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
|
||||
@@ -375,8 +385,8 @@ public class BookRepositoryTests
|
||||
public async Task GetPaginatedAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
|
||||
LibraryFilterDto filter = new() { LibraryId = Guid.Empty };
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
|
||||
@@ -397,7 +407,7 @@ public class BookRepositoryTests
|
||||
_mockContext.Books.AddRange(books);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryFilterDto filter = new() { LibraryId = libraryId };
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(null, null, null, filter, CancellationToken.None);
|
||||
@@ -425,8 +435,8 @@ public class BookRepositoryTests
|
||||
_mockContext.Books.AddRange(fellowshipBook, towersBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
|
||||
LibraryFilterDto filter = new() { LibraryId = libraryId, SearchTerm = "Fellowship" };
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: "Fellowship");
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
|
||||
@@ -449,8 +459,8 @@ public class BookRepositoryTests
|
||||
_mockContext.Books.AddRange(books);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = new() { CurrentPage = 2, PerPage = 2 };
|
||||
LibraryFilterDto filter = new() { LibraryId = libraryId };
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 2, perPage: 2);
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
|
||||
@@ -478,8 +488,8 @@ public class BookRepositoryTests
|
||||
_mockContext.Books.AddRange(bookA, bookB);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
|
||||
LibraryFilterDto filter = new() { LibraryId = libraryId };
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "title", SortOrder.Descending, filter, CancellationToken.None);
|
||||
@@ -496,15 +506,15 @@ public class BookRepositoryTests
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.LibraryId = libraryId;
|
||||
book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")];
|
||||
book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")];
|
||||
book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)];
|
||||
book.Ratings = [new BookRatingEntity(4.5M, 5, BookRatingSource.Goodreads, 100)];
|
||||
book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")];
|
||||
book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")];
|
||||
book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)];
|
||||
book.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)];
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
|
||||
LibraryFilterDto filter = new() { LibraryId = libraryId };
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
@@ -23,6 +23,7 @@ public class LuminaDbContextTests : IDisposable
|
||||
private readonly string _connectionString;
|
||||
private readonly SqliteConnection _anchorConnection;
|
||||
private readonly LuminaDbContext _context;
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaDbContextTests"/> class.
|
||||
@@ -46,7 +47,7 @@ public class LuminaDbContextTests : IDisposable
|
||||
|
||||
// Assert
|
||||
// The count assertion fails when a table is added or removed, reminding to update the assertions below.
|
||||
Assert.Equal(24, tableNames.Length);
|
||||
Assert.Equal(25, tableNames.Length);
|
||||
Assert.Contains("Books", tableNames);
|
||||
Assert.Contains("Users", tableNames);
|
||||
Assert.Contains("UserSettings", tableNames);
|
||||
@@ -63,6 +64,7 @@ public class LuminaDbContextTests : IDisposable
|
||||
Assert.Contains("DirectoryScanFingerprints", tableNames);
|
||||
Assert.Contains("Plugins", tableNames);
|
||||
Assert.Contains("LibraryMetadataProviderConfigurations", tableNames);
|
||||
Assert.Contains("LibraryArtworkProviderConfigurations", tableNames);
|
||||
Assert.Contains("Tags", tableNames);
|
||||
Assert.Contains("Genres", tableNames);
|
||||
Assert.Contains("LibraryContentLocations", tableNames);
|
||||
@@ -78,17 +80,10 @@ public class LuminaDbContextTests : IDisposable
|
||||
{
|
||||
// Arrange
|
||||
_context.Database.EnsureCreated();
|
||||
BookEntity book = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = Guid.NewGuid(),
|
||||
Path = "/books/test.epub",
|
||||
Title = "Test Book",
|
||||
MetadataStatus = MetadataStatus.Pending,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedBy = null
|
||||
};
|
||||
BookEntity book = _bookEntityFixture.Create(path: "/books/test.epub", title: "Test Book", includeMetadata: false);
|
||||
book.MetadataStatus = MetadataStatus.Pending;
|
||||
book.CreatedOnUtc = DateTime.UtcNow;
|
||||
book.CreatedBy = Guid.NewGuid();
|
||||
_context.Books.Add(book);
|
||||
|
||||
// Act
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
@@ -100,6 +96,26 @@ public class UnitOfWorkTests
|
||||
await dbContext.Received(1).SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearTrackedEntities_WhenCalled_ShouldDetachAllTrackedEntities()
|
||||
{
|
||||
// Arrange
|
||||
DbContextOptions<LuminaDbContext> options = new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
LuminaDbContext dbContext = new(options);
|
||||
UnitOfWork unitOfWork = new(dbContext);
|
||||
dbContext.Roles.Add(new RoleEntity { Id = Guid.NewGuid(), RoleName = "TestRole" });
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
Assert.NotEmpty(dbContext.ChangeTracker.Entries());
|
||||
|
||||
// Act
|
||||
unitOfWork.ClearTrackedEntities();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(dbContext.ChangeTracker.Entries());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnitOfWork_WhenResolvedFromServiceProvider_ShouldExposeRepositories()
|
||||
{
|
||||
|
||||
+5
-7
@@ -3,7 +3,6 @@ using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
@@ -14,7 +13,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
@@ -50,7 +48,7 @@ public class LibraryTests
|
||||
coverImageSourcePath,
|
||||
isEnabled: false,
|
||||
isLocked: true,
|
||||
downloadMetadataFromWeb: false,
|
||||
canDownloadMetadataFromWeb: false,
|
||||
shouldSaveMetadataInMediaDirectories: true,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
scanIds);
|
||||
@@ -64,7 +62,7 @@ public class LibraryTests
|
||||
Assert.Equal(coverImageSourcePath, result.Value.CoverImage);
|
||||
Assert.False(result.Value.IsEnabled);
|
||||
Assert.True(result.Value.IsLocked);
|
||||
Assert.False(result.Value.DownloadMetadataFromWeb);
|
||||
Assert.False(result.Value.CanDownloadMetadataFromWeb);
|
||||
Assert.True(result.Value.ShouldSaveMetadataInMediaDirectories);
|
||||
Assert.True(result.Value.ShouldSkipUnchangedDirectoriesDuringScan);
|
||||
Assert.Equal(scanIds, result.Value.ScanIds);
|
||||
@@ -87,7 +85,7 @@ public class LibraryTests
|
||||
null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
downloadMetadataFromWeb: true,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
scanIds);
|
||||
@@ -109,7 +107,7 @@ public class LibraryTests
|
||||
null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
downloadMetadataFromWeb: true,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
[]);
|
||||
@@ -136,7 +134,7 @@ public class LibraryTests
|
||||
null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
downloadMetadataFromWeb: true,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
[]);
|
||||
|
||||
+12
-9
@@ -5,7 +5,6 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
@@ -34,7 +33,8 @@ public class UserSettingsTests
|
||||
Assert.Equal(userId, result.Value.UserId);
|
||||
Assert.True(result.Value.IsPaginationEnabled);
|
||||
Assert.Equal(48, result.Value.ItemsPerPage);
|
||||
Assert.False(result.Value.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.False(result.Value.ShouldAggregateMetadataWhenMissing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -48,7 +48,8 @@ public class UserSettingsTests
|
||||
Assert.NotNull(result.Value.UserId);
|
||||
Assert.True(result.Value.IsPaginationEnabled);
|
||||
Assert.Equal(48, result.Value.ItemsPerPage);
|
||||
Assert.False(result.Value.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.False(result.Value.ShouldAggregateMetadataWhenMissing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -72,15 +73,16 @@ public class UserSettingsTests
|
||||
UserId userId = _userIdFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, ignoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true);
|
||||
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: true);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(userId, result.Value.UserId);
|
||||
Assert.False(result.Value.IsPaginationEnabled);
|
||||
Assert.Equal(24, result.Value.ItemsPerPage);
|
||||
Assert.True(result.Value.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.True(result.Value.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.True(result.Value.IsThemeCachingEnabled);
|
||||
Assert.True(result.Value.ShouldAggregateMetadataWhenMissing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -106,7 +108,7 @@ public class UserSettingsTests
|
||||
UserId userId = _userIdFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true);
|
||||
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
@@ -120,14 +122,15 @@ public class UserSettingsTests
|
||||
UserSettings userSettings = _userSettingsFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, ignoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false);
|
||||
Result<Updated> result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false, shouldAggregateMetadataWhenMissing: true);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(userSettings.IsPaginationEnabled);
|
||||
Assert.Equal(12, userSettings.ItemsPerPage);
|
||||
Assert.True(userSettings.IgnoreThePrefixForAlphaPicker);
|
||||
Assert.True(userSettings.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.False(userSettings.IsThemeCachingEnabled);
|
||||
Assert.True(userSettings.ShouldAggregateMetadataWhenMissing);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -139,7 +142,7 @@ public class UserSettingsTests
|
||||
UserSettings userSettings = _userSettingsFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true);
|
||||
Result<Updated> result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
|
||||
+435
@@ -1,9 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
@@ -13,14 +26,17 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -45,6 +61,13 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new();
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
@@ -106,6 +129,51 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoMetadataProviderIsConfigured_ShouldSkipEnrichmentWithoutMarkingBooksAsFailed()
|
||||
{
|
||||
// Arrange
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// a library without metadata providers must not mark its books as failed to enrich, so the book repositories are not touched
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenABookPageIsProcessed_ShouldDetachTheTrackedEntitiesAfterSaving()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title"));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the tracked entities of the page are detached after saving, so that the peak memory stays bounded regardless of the library size
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
@@ -139,4 +207,371 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAggregateMetadataIsEnabled_ShouldFeedTheEarlierProvidersFindingsToTheLaterOnes()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
Guid secondPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
IMetadataProvider secondProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", openLibraryId: "OL123", description: "First Description"));
|
||||
secondProvider.Name.Returns("Second Provider");
|
||||
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
secondProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher"));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: true);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
// the book has no known identifiers of its own, so the findings of the first provider are fed to the second one
|
||||
book.OpenLibraryId = null;
|
||||
SetupSingleBookPage(book, firstPluginId, secondPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the second provider receives the lookup enriched with the open library Id discovered by the first provider
|
||||
await secondProvider.Received(1).GetMetadataAsync(
|
||||
Arg.Is<MetadataLookupDto>(lookup => lookup is BookMetadataLookupDto && ((BookMetadataLookupDto)lookup).OpenLibraryId == "OL123"),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAggregateMetadataIsDisabled_ShouldOnlyApplyTheFirstUsableProviderMetadata()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
Guid secondPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
IMetadataProvider secondProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", publisher: "First Publisher"));
|
||||
secondProvider.Name.Returns("Second Provider");
|
||||
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
secondProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher"));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId, secondPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the second provider is not queried when the aggregation is disabled and the first provider returned usable metadata
|
||||
await secondProvider.DidNotReceive().GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoProviderReturnsUsableMetadata_ShouldMarkTheBookAsFailedToEnrich()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(includeTitle: false));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([
|
||||
_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)
|
||||
]));
|
||||
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<BookEntity>(entity => entity.MetadataStatus == MetadataStatus.Failed),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtworkConfigurationRepositoryReturnsFailure_ShouldStillEnrichTheMetadata()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title"));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure(description: "Failed to get the artwork provider configurations"));
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockBookRepository.Received(1).UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndSetTheBookCoverPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
Guid artworkPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title"));
|
||||
|
||||
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
|
||||
|
||||
ServiceCollection services = new();
|
||||
services.AddKeyedSingleton(firstPluginId, firstProvider);
|
||||
services.AddKeyedSingleton(artworkPluginId, artworkProvider);
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
services.AddSingleton(_mockDomainEventPublisher);
|
||||
services.AddSingleton(mockBookArtworkService);
|
||||
using ServiceProvider realServiceProvider = services.BuildServiceProvider();
|
||||
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
|
||||
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
|
||||
|
||||
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
|
||||
|
||||
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await mockBookArtworkService.Received(1).SaveBookArtworkAsync(
|
||||
_libraryId.Value,
|
||||
book.Id,
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
"First Title",
|
||||
Arg.Any<ArtworkDto>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<BookEntity>(entity => entity.CoverImagePath == "\\media\\books\\Library\\Author\\Title\\cover.jpeg"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseMetadataProvidersThatRequireWebAccess()
|
||||
{
|
||||
// Arrange
|
||||
Guid localPluginId = Guid.NewGuid();
|
||||
Guid webPluginId = Guid.NewGuid();
|
||||
IMetadataProvider localProvider = Substitute.For<IMetadataProvider>();
|
||||
localProvider.Name.Returns("Local Provider");
|
||||
localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
localProvider.RequiresWebAccess.Returns(false);
|
||||
localProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(includeTitle: false));
|
||||
IMetadataProvider webProvider = Substitute.For<IMetadataProvider>();
|
||||
webProvider.Name.Returns("Web Provider");
|
||||
webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
webProvider.RequiresWebAccess.Returns(true);
|
||||
webProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "Web Title"));
|
||||
|
||||
SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, localPluginId, webPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the local provider is used, but the provider requiring access to the web is skipped, so the book cannot be enriched
|
||||
await localProvider.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
await webProvider.DidNotReceive().GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheLibraryPermitsWebDownloads_ShouldUseMetadataProvidersThatRequireWebAccess()
|
||||
{
|
||||
// Arrange
|
||||
Guid localPluginId = Guid.NewGuid();
|
||||
Guid webPluginId = Guid.NewGuid();
|
||||
IMetadataProvider localProvider = Substitute.For<IMetadataProvider>();
|
||||
localProvider.Name.Returns("Local Provider");
|
||||
localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
localProvider.RequiresWebAccess.Returns(false);
|
||||
localProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(includeTitle: false));
|
||||
IMetadataProvider webProvider = Substitute.For<IMetadataProvider>();
|
||||
webProvider.Name.Returns("Web Provider");
|
||||
webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
webProvider.RequiresWebAccess.Returns(true);
|
||||
webProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "Web Title"));
|
||||
|
||||
SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: true)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, localPluginId, webPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the provider requiring access to the web is used when the library permits downloading data from the web
|
||||
await webProvider.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseArtworkProvidersThatRequireWebAccess()
|
||||
{
|
||||
// Arrange
|
||||
Guid localPluginId = Guid.NewGuid();
|
||||
Guid artworkPluginId = Guid.NewGuid();
|
||||
IMetadataProvider localProvider = Substitute.For<IMetadataProvider>();
|
||||
localProvider.Name.Returns("Local Provider");
|
||||
localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
localProvider.RequiresWebAccess.Returns(false);
|
||||
localProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "Local Title"));
|
||||
|
||||
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Web Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.RequiresWebAccess.Returns(true);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
ServiceCollection services = new();
|
||||
services.AddKeyedSingleton(localPluginId, localProvider);
|
||||
services.AddKeyedSingleton(artworkPluginId, artworkProvider);
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
services.AddSingleton(_mockDomainEventPublisher);
|
||||
// the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test
|
||||
using ServiceProvider realServiceProvider = services.BuildServiceProvider();
|
||||
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
|
||||
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
|
||||
|
||||
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
|
||||
|
||||
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
|
||||
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, localPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the artwork provider requiring access to the web is skipped when the library does not permit downloading data from the web
|
||||
await artworkProvider.DidNotReceive().GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wires a real service provider with the given metadata providers, so that the job resolves them from the dependency injection container.
|
||||
/// </summary>
|
||||
/// <param name="firstPluginId">The Id of the plugin providing the first metadata provider.</param>
|
||||
/// <param name="firstProvider">The first metadata provider to resolve.</param>
|
||||
/// <param name="secondPluginId">The Id of the plugin providing the second metadata provider, if any.</param>
|
||||
/// <param name="secondProvider">The second metadata provider to resolve, if any.</param>
|
||||
/// <param name="shouldAggregateMetadataWhenMissing">Whether the user settings enable aggregating metadata from multiple providers when fields are missing.</param>
|
||||
private void SetupRealServiceProviderForProviders(Guid firstPluginId, IMetadataProvider firstProvider, Guid? secondPluginId = null, IMetadataProvider? secondProvider = null, bool shouldAggregateMetadataWhenMissing = false)
|
||||
{
|
||||
ServiceCollection services = new();
|
||||
services.AddKeyedSingleton(firstPluginId, firstProvider);
|
||||
if (secondPluginId is not null && secondProvider is not null)
|
||||
services.AddKeyedSingleton(secondPluginId.Value, secondProvider);
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
services.AddSingleton(_mockDomainEventPublisher);
|
||||
// the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test
|
||||
ServiceProvider realServiceProvider = services.BuildServiceProvider();
|
||||
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
|
||||
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
|
||||
|
||||
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: shouldAggregateMetadataWhenMissing)));
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the repositories so that the job processes a single page containing the given book, configured with the given metadata providers.
|
||||
/// </summary>
|
||||
/// <param name="book">The book the job must enrich.</param>
|
||||
/// <param name="configuredPluginIds">The Ids of the plugins configured as metadata providers for the library.</param>
|
||||
private void SetupSingleBookPage(BookEntity book, params Guid[] configuredPluginIds)
|
||||
{
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>(
|
||||
configuredPluginIds.Select((pluginId, index) => _configurationEntityFixture.Create(_libraryId.Value, pluginId, index + 1)).ToList()));
|
||||
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
}
|
||||
}
|
||||
+332
@@ -0,0 +1,332 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MetadataAggregator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MetadataAggregatorTests
|
||||
{
|
||||
private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new();
|
||||
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
|
||||
private readonly IsbnDtoFixture _isbnDtoFixture = new();
|
||||
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
|
||||
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly TagDtoFixture _tagDtoFixture = new();
|
||||
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothMetadataHaveScalarValues_ShouldKeepTheFirstValues()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false,
|
||||
title: "First Title",
|
||||
originalTitle: "First Original Title",
|
||||
description: "First Description",
|
||||
publisher: "First Publisher",
|
||||
pageCount: 100,
|
||||
format: BookFormat.Hardcover,
|
||||
edition: "First Edition",
|
||||
volumeNumber: 1,
|
||||
asin: "FIRST-ASIN",
|
||||
goodreadsId: "FIRST-GOODREADS",
|
||||
lccn: "FIRST-LCCN",
|
||||
oclcNumber: "FIRST-OCLC",
|
||||
openLibraryId: "FIRST-OL",
|
||||
libraryThingId: "FIRST-LT",
|
||||
googleBooksId: "FIRST-GOOGLE",
|
||||
barnesAndNobleId: "FIRST-BN",
|
||||
appleBooksId: "FIRST-APPLE",
|
||||
coverImagePath: "First Cover");
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false,
|
||||
title: "Second Title",
|
||||
originalTitle: "Second Original Title",
|
||||
description: "Second Description",
|
||||
publisher: "Second Publisher",
|
||||
pageCount: 200,
|
||||
format: BookFormat.Paperback,
|
||||
edition: "Second Edition",
|
||||
volumeNumber: 2,
|
||||
asin: "SECOND-ASIN",
|
||||
goodreadsId: "SECOND-GOODREADS",
|
||||
lccn: "SECOND-LCCN",
|
||||
oclcNumber: "SECOND-OCLC",
|
||||
openLibraryId: "SECOND-OL",
|
||||
libraryThingId: "SECOND-LT",
|
||||
googleBooksId: "SECOND-GOOGLE",
|
||||
barnesAndNobleId: "SECOND-BN",
|
||||
appleBooksId: "SECOND-APPLE",
|
||||
coverImagePath: "First Cover");
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("First Title", result.Title);
|
||||
Assert.Equal("First Original Title", result.OriginalTitle);
|
||||
Assert.Equal("First Description", result.Description);
|
||||
Assert.Equal("First Publisher", result.Publisher);
|
||||
Assert.Equal(100, result.PageCount);
|
||||
Assert.Equal(BookFormat.Hardcover, result.Format);
|
||||
Assert.Equal("First Edition", result.Edition);
|
||||
Assert.Equal(1, result.VolumeNumber);
|
||||
Assert.Equal("FIRST-ASIN", result.ASIN);
|
||||
Assert.Equal("FIRST-GOODREADS", result.GoodreadsId);
|
||||
Assert.Equal("FIRST-LCCN", result.LCCN);
|
||||
Assert.Equal("FIRST-OCLC", result.OCLCNumber);
|
||||
Assert.Equal("FIRST-OL", result.OpenLibraryId);
|
||||
Assert.Equal("FIRST-LT", result.LibraryThingId);
|
||||
Assert.Equal("FIRST-GOOGLE", result.GoogleBooksId);
|
||||
Assert.Equal("FIRST-BN", result.BarnesAndNobleId);
|
||||
Assert.Equal("FIRST-APPLE", result.AppleBooksId);
|
||||
Assert.Equal("First Cover", result.CoverImagePath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenFirstHasNullScalars_ShouldFallBackToTheSecondValues()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, description: null, publisher: null, pageCount: null);
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: "Second Title", description: "Second Description", publisher: "Second Publisher", pageCount: 200);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Second Title", result.Title);
|
||||
Assert.Equal("Second Description", result.Description);
|
||||
Assert.Equal("Second Publisher", result.Publisher);
|
||||
Assert.Equal(200, result.PageCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveNullScalars_ShouldReturnNullScalars()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, coverImagePath: null);
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, coverImagePath: null);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Title);
|
||||
Assert.Null(result.Description);
|
||||
Assert.Null(result.Publisher);
|
||||
Assert.Null(result.PageCount);
|
||||
Assert.Null(result.Format);
|
||||
Assert.Null(result.Edition);
|
||||
Assert.Null(result.VolumeNumber);
|
||||
Assert.Null(result.Series);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveReleaseInfo_ShouldCoalesceEachField()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false);
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false);
|
||||
first = first with { ReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, releaseCountry: "US") };
|
||||
second = second with { ReleaseInfo = _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2010, 5, 5), reReleaseYear: 2010, releaseCountry: "UK", releaseVersion: "2.0") };
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate);
|
||||
Assert.Equal(2001, result.ReleaseInfo.OriginalReleaseYear);
|
||||
Assert.Equal(new DateOnly(2010, 5, 5), result.ReleaseInfo.ReReleaseDate);
|
||||
Assert.Equal(2010, result.ReleaseInfo.ReReleaseYear);
|
||||
Assert.Equal("US", result.ReleaseInfo.ReleaseCountry);
|
||||
Assert.Equal("2.0", result.ReleaseInfo.ReleaseVersion);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenFirstReleaseInfoIsNull_ShouldUseTheSecondReleaseInfo()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null };
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001) };
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothReleaseInfosAreNull_ShouldReturnNullReleaseInfo()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null };
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null };
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.ReleaseInfo);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveGenres_ShouldUnionAndDeDuplicateByName()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Genres = [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Space opera")] };
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Genres = [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Fantasy")] };
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(3, result.Genres!.Count);
|
||||
Assert.Contains(result.Genres, genre => genre.Name == "Science fiction");
|
||||
Assert.Contains(result.Genres, genre => genre.Name == "Space opera");
|
||||
Assert.Contains(result.Genres, genre => genre.Name == "Fantasy");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveTags_ShouldUnionAndDeDuplicateByName()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag B")] };
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag C")] };
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(3, result.Tags!.Count);
|
||||
Assert.Contains(result.Tags, tag => tag.Name == "Tag A");
|
||||
Assert.Contains(result.Tags, tag => tag.Name == "Tag B");
|
||||
Assert.Contains(result.Tags, tag => tag.Name == "Tag C");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveIsbns_ShouldUnionAndDeDuplicateByValue()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)] };
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13), _isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)] };
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Isbns!.Count);
|
||||
Assert.Contains(result.Isbns, isbn => isbn.Value == "9780306406157");
|
||||
Assert.Contains(result.Isbns, isbn => isbn.Value == "0306406152");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveContributors_ShouldUnionAndDeDuplicateByDisplayNameAndRole()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author")] };
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author"), _mediaContributorDtoFixture.Create("Translator B", "Translator")] };
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Contributors!.Count);
|
||||
Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Author A");
|
||||
Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Translator B");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveRatings_ShouldUnionAndDeDuplicateBySource()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)] };
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null), _bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)] };
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Ratings!.Count);
|
||||
Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.Calibre);
|
||||
Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.OpenLibrary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenOnlyFirstHasCollections_ShouldReturnTheFirstCollections()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A")], Genres = [_genreDtoFixture.Create(name: "Genre A")], Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)], Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author")], Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)] };
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null };
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Tag A", Assert.Single(result.Tags!).Name);
|
||||
Assert.Equal("Genre A", Assert.Single(result.Genres!).Name);
|
||||
Assert.Equal("9780306406157", Assert.Single(result.Isbns!).Value);
|
||||
Assert.Equal("Author A", Assert.Single(result.Contributors!).Name!.DisplayName);
|
||||
Assert.Equal(BookRatingSource.Calibre, Assert.Single(result.Ratings!).Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenOnlySecondHasCollections_ShouldReturnTheSecondCollections()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null };
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag B")], Genres = [_genreDtoFixture.Create(name: "Genre B")], Isbns = [_isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)], Contributors = [_mediaContributorDtoFixture.Create("Author B", "Author")], Ratings = [_bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)] };
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Tag B", Assert.Single(result.Tags!).Name);
|
||||
Assert.Equal("Genre B", Assert.Single(result.Genres!).Name);
|
||||
Assert.Equal("0306406152", Assert.Single(result.Isbns!).Value);
|
||||
Assert.Equal("Author B", Assert.Single(result.Contributors!).Name!.DisplayName);
|
||||
Assert.Equal(BookRatingSource.OpenLibrary, Assert.Single(result.Ratings!).Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveNullCollections_ShouldReturnNullCollections()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null };
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null };
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Genres);
|
||||
Assert.Null(result.Tags);
|
||||
Assert.Null(result.Isbns);
|
||||
Assert.Null(result.Contributors);
|
||||
Assert.Null(result.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveLanguages_ShouldKeepTheFirstLanguage()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Language = _languageInfoDtoFixture.Create(languageCode: "en", languageName: "English", nativeName: "English") };
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Language = _languageInfoDtoFixture.Create(languageCode: "de", languageName: "German", nativeName: "Deutsch") };
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("en", result.Language!.LanguageCode);
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,7 @@
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Infrastructure\Lumina.Infrastructure.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Domain.Fixtures\Lumina.Domain.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Application.Fixtures\Lumina.Application.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Infrastructure.Fixtures\Lumina.Infrastructure.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.TestPlugin\Lumina.TestPlugin.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
+4
-2
@@ -3,6 +3,7 @@ using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.Plugins;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -28,6 +29,7 @@ public class GetLibraryMetadataProvidersEndpointTests
|
||||
private readonly IQueryHandler<GetLibraryMetadataProvidersQuery, Result<IReadOnlyList<LibraryMetadataProviderResponse>>> _mockHandler;
|
||||
private readonly GetLibraryMetadataProvidersEndpoint _sut;
|
||||
private readonly GetLibraryMetadataProvidersRequestFixture _getLibraryMetadataProvidersRequestFixture = new();
|
||||
private readonly LibraryMetadataProviderResponseFixture _libraryMetadataProviderResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryMetadataProvidersEndpointTests"/> class.
|
||||
@@ -46,8 +48,8 @@ public class GetLibraryMetadataProvidersEndpointTests
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
IReadOnlyList<LibraryMetadataProviderResponse> expectedResponses =
|
||||
[
|
||||
new LibraryMetadataProviderResponse(Guid.NewGuid(), "Provider A", true, 1),
|
||||
new LibraryMetadataProviderResponse(Guid.NewGuid(), "Provider B", false, 2)
|
||||
_libraryMetadataProviderResponseFixture.Create(name: "Provider A", isEnabled: true, rank: 1),
|
||||
_libraryMetadataProviderResponseFixture.Create(name: "Provider B", isEnabled: false, rank: 2)
|
||||
];
|
||||
_mockHandler.HandleAsync(Arg.Any<GetLibraryMetadataProvidersQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponses));
|
||||
|
||||
+8
-6
@@ -3,6 +3,7 @@ using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.Plugins.Queries.GetPluginSettings;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.Plugins;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -27,6 +28,7 @@ public class GetPluginSettingsEndpointTests
|
||||
private readonly IQueryHandler<GetPluginSettingsQuery, Result<PluginSettingsResponse>> _mockHandler;
|
||||
private readonly GetPluginSettingsEndpoint _sut;
|
||||
private readonly GetPluginSettingsRequestFixture _getPluginSettingsRequestFixture = new();
|
||||
private readonly PluginSettingsResponseFixture _pluginSettingsResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginSettingsEndpointTests"/> class.
|
||||
@@ -43,10 +45,10 @@ public class GetPluginSettingsEndpointTests
|
||||
// Arrange
|
||||
GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
PluginSettingsResponse expectedResponse = new(
|
||||
PluginId: request.PluginId,
|
||||
Schema: [],
|
||||
Settings: null
|
||||
PluginSettingsResponse expectedResponse = _pluginSettingsResponseFixture.Create(
|
||||
pluginId: request.PluginId,
|
||||
schema: [],
|
||||
settings: null
|
||||
);
|
||||
_mockHandler.HandleAsync(Arg.Any<GetPluginSettingsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
@@ -92,7 +94,7 @@ public class GetPluginSettingsEndpointTests
|
||||
GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetPluginSettingsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new PluginSettingsResponse(request.PluginId, [], null)));
|
||||
.Returns(Result.From(_pluginSettingsResponseFixture.Create(pluginId: request.PluginId, schema: [], settings: null)));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -118,7 +120,7 @@ public class GetPluginSettingsEndpointTests
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(new PluginSettingsResponse(request.PluginId, [], null));
|
||||
return Result.From(_pluginSettingsResponseFixture.Create(pluginId: request.PluginId, schema: [], settings: null));
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
|
||||
+5
-3
@@ -2,6 +2,7 @@
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetUserSettings;
|
||||
@@ -24,6 +25,7 @@ public class GetUserSettingsEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetUserSettingsQuery, Result<UserSettingsResponse>> _mockHandler;
|
||||
private readonly GetUserSettingsEndpoint _sut;
|
||||
private readonly UserSettingsResponseFixture _userSettingsResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointTests"/> class.
|
||||
@@ -39,7 +41,7 @@ public class GetUserSettingsEndpointTests
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
UserSettingsResponse expectedResponse = new(Guid.NewGuid(), true, 48, false, true);
|
||||
UserSettingsResponse expectedResponse = _userSettingsResponseFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
|
||||
_mockHandler.HandleAsync(Arg.Any<GetUserSettingsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
|
||||
@@ -79,7 +81,7 @@ public class GetUserSettingsEndpointTests
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetUserSettingsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false, true)));
|
||||
.Returns(Result.From(_userSettingsResponseFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false)));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
@@ -104,7 +106,7 @@ public class GetUserSettingsEndpointTests
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false, true));
|
||||
return Result.From(_userSettingsResponseFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false));
|
||||
}, info.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
|
||||
+7
-5
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Requests.UsersManagement.Settings;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings;
|
||||
@@ -23,6 +24,7 @@ public class UpdateUserSettingsEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<UpdateUserSettingsCommand, Result<Updated>> _mockHandler;
|
||||
private readonly UpdateUserSettingsEndpoint _sut;
|
||||
private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointTests"/> class.
|
||||
@@ -37,7 +39,7 @@ public class UpdateUserSettingsEndpointTests
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdatedMarker()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = new(true, 48, false, true);
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
@@ -54,7 +56,7 @@ public class UpdateUserSettingsEndpointTests
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = new(true, 0, false, true);
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 0, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Validation("UserSettings.ItemsPerPageMustBeGreaterThanZero", "ItemsPerPage must be greater than zero.");
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
|
||||
@@ -76,7 +78,7 @@ public class UpdateUserSettingsEndpointTests
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateUserSettingsCommandToHandler()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = new(true, 24, true, true);
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
@@ -89,7 +91,7 @@ public class UpdateUserSettingsEndpointTests
|
||||
Arg.Is<UpdateUserSettingsCommand>(command =>
|
||||
command.IsPaginationEnabled == request.IsPaginationEnabled &&
|
||||
command.ItemsPerPage == request.ItemsPerPage &&
|
||||
command.IgnoreThePrefixForAlphaPicker == request.IgnoreThePrefixForAlphaPicker &&
|
||||
command.ShouldIgnoreThePrefixForAlphaPicker == request.ShouldIgnoreThePrefixForAlphaPicker &&
|
||||
command.IsThemeCachingEnabled == request.IsThemeCachingEnabled),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
@@ -112,7 +114,7 @@ public class UpdateUserSettingsEndpointTests
|
||||
}, info.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(new UpdateUserSettingsRequest(true, 48, false, true), cts.Token);
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(_updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false), cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
+7
-3
@@ -38,6 +38,10 @@ public class UpdateUserSettingsEndpointTests
|
||||
_sut = Factory.Create<UpdateUserSettingsEndpoint>(_mockApiHttpClient, CreateThemeCachePreferenceService());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="ThemeCachePreferenceService"/> backed by an in-memory hybrid cache.
|
||||
/// </summary>
|
||||
/// <returns>The created theme cache preference service.</returns>
|
||||
private static ThemeCachePreferenceService CreateThemeCachePreferenceService()
|
||||
{
|
||||
ServiceCollection services = new();
|
||||
@@ -50,15 +54,15 @@ public class UpdateUserSettingsEndpointTests
|
||||
{
|
||||
// Arrange
|
||||
UserSettingsDto request = _userSettingsDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(Arg.Any<string>(), Arg.Any<UserSettingsDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
|
||||
_mockApiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(Arg.Any<string>(), Arg.Any<UserSettingsDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(
|
||||
await _mockApiHttpClient.Received(1).PutAsync<Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(
|
||||
ApiRoutes.Users.UPDATE_USER_SETTINGS,
|
||||
Arg.Is<UserSettingsDto>(settings => settings.ItemsPerPage == request.ItemsPerPage && settings.IsPaginationEnabled == request.IsPaginationEnabled),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
Reference in new issue
Block a user