Hardens test assertions and adds missing test coverage.

This commit is contained in:
BinaryAlley committed 2026-08-18 08:28:16 -07:00
1 parent 6b86fd5805
commit 1189bbaf36
489 files changed
+39982 -512

No files matched your search

@@ -0,0 +1,154 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryMetadataProviders;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryMetadataProviders;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryMetadataProvidersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryMetadataProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task GetLibraryMetadataProviders_WhenProvidersAreConfigured_ShouldReturnThemOrderedByRank()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid userId = GetCurrentUserId();
Guid pluginIdA = Guid.NewGuid();
Guid pluginIdB = Guid.NewGuid();
await SeedConfigurationAsync(libraryId, pluginIdA, pluginIdB, userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/metadata-providers");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<LibraryMetadataProviderResponse>? providers = await response.Content.ReadFromJsonAsync<List<LibraryMetadataProviderResponse>>(_jsonOptions);
Assert.NotNull(providers);
Assert.Equal(2, providers!.Count);
Assert.Equal(pluginIdA, providers[0].PluginId);
Assert.Equal(1, providers[0].Rank);
Assert.Equal(pluginIdB, providers[1].PluginId);
Assert.Equal(2, providers[1].Rank);
}
[Fact]
public async Task GetLibraryMetadataProviders_WhenNoProvidersAreConfigured_ShouldReturnEmptyList()
{
// Arrange
Guid libraryId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/metadata-providers");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<LibraryMetadataProviderResponse>? providers = await response.Content.ReadFromJsonAsync<List<LibraryMetadataProviderResponse>>(_jsonOptions);
Assert.NotNull(providers);
Assert.Empty(providers!);
}
/// <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)
{
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
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,146 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPluginSettings;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetPluginSettings;
/// <summary>
/// Contains integration tests for the <see cref="GetPluginSettingsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPluginSettingsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetPluginSettingsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPluginSettingsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task GetPluginSettings_WhenPluginExists_ShouldReturnPluginSettings()
{
// Arrange
Guid pluginId = Guid.NewGuid();
await SeedPluginAsync(pluginId, "Test Plugin");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/plugins/{pluginId}/settings");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Lumina.Contracts.Responses.Plugins.PluginSettingsResponse? settings = await response.Content.ReadFromJsonAsync<Lumina.Contracts.Responses.Plugins.PluginSettingsResponse>(_jsonOptions);
Assert.NotNull(settings);
Assert.Equal(pluginId, settings!.PluginId);
}
[Fact]
public async Task GetPluginSettings_WhenPluginDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid pluginId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/plugins/{pluginId}/settings");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("PluginNotFound", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/plugins/{pluginId}/settings", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
/// <summary>
/// Seeds a <see cref="PluginEntity"/> in the database.
/// </summary>
/// <param name="pluginId">The Id of the plugin.</param>
/// <param name="name">The display name of the plugin.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedPluginAsync(Guid pluginId, string name)
{
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
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,145 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPlugins;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetPlugins;
/// <summary>
/// Contains integration tests for the <see cref="GetPluginsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPluginsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly List<Guid> _seededPluginIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetPluginsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPluginsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task GetPlugins_WhenPluginsExist_ShouldReturnTheDetectedPlugins()
{
// Arrange
Guid pluginId = Guid.NewGuid();
await SeedPluginAsync(pluginId, "Test Plugin");
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/plugins");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<Lumina.Contracts.Responses.Plugins.PluginResponse>? plugins = await response.Content.ReadFromJsonAsync<List<Lumina.Contracts.Responses.Plugins.PluginResponse>>(_jsonOptions);
Assert.NotNull(plugins);
Assert.Contains(plugins!, plugin => plugin.Id == pluginId && plugin.Name == "Test Plugin");
}
[Fact]
public async Task GetPlugins_WhenNoPluginsExist_ShouldReturnEmptyList()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/plugins");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<Lumina.Contracts.Responses.Plugins.PluginResponse>? plugins = await response.Content.ReadFromJsonAsync<List<Lumina.Contracts.Responses.Plugins.PluginResponse>>(_jsonOptions);
Assert.NotNull(plugins);
Assert.Empty(plugins!);
}
/// <summary>
/// Seeds a <see cref="PluginEntity"/> in the database.
/// </summary>
/// <param name="pluginId">The Id of the plugin.</param>
/// <param name="name">The display name of the plugin.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedPluginAsync(Guid pluginId, string name)
{
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
});
await dbContext.SaveChangesAsync();
_seededPluginIds.Add(pluginId);
}
/// <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>
/// Removes the seeded plugins and disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
foreach (Guid pluginId in _seededPluginIds)
{
PluginEntity? plugin = await dbContext.Plugins.FindAsync(pluginId);
if (plugin is not null)
dbContext.Plugins.Remove(plugin);
}
await dbContext.SaveChangesAsync();
_apiFactory.Dispose();
}
}
@@ -0,0 +1,132 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders;
/// <summary>
/// Contains integration tests for the <see cref="ReorderLibraryMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ReorderLibraryMetadataProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task ReorderLibraryMetadataProviders_WhenCalledWithValidData_ShouldReorderTheProviders()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid userId = GetCurrentUserId();
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]
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<LibraryMetadataProviderConfigurationEntity> configurations = await dbContext.LibraryMetadataProviderConfigurations
.Where(config => config.LibraryId == libraryId)
.OrderBy(config => config.Rank)
.ToListAsync();
Assert.Equal(2, configurations.Count);
Assert.Equal(pluginIdB, configurations[0].PluginId);
Assert.Equal(1, configurations[0].Rank);
Assert.Equal(pluginIdA, configurations[1].PluginId);
Assert.Equal(2, configurations[1].Rank);
}
/// <summary>
/// Seeds a <see cref="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)
{
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
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,162 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Contracts.Responses.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
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
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled;
/// <summary>
/// Contains integration tests for the <see cref="SetLibraryMetadataProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryMetadataProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryMetadataProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task SetLibraryMetadataProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
SetLibraryMetadataProviderEnabledRequest request = new(
LibraryId: libraryId,
PluginId: pluginId,
IsEnabled: true
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations
.FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
Assert.NotNull(configuration);
Assert.True(configuration!.IsEnabled);
Assert.Equal(1, configuration.Rank);
}
[Fact]
public async Task SetLibraryMetadataProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState()
{
// Arrange
Guid 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
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations
.FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
Assert.NotNull(configuration);
Assert.True(configuration!.IsEnabled);
}
/// <summary>
/// Seeds a <see cref="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)
{
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
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,159 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.UpdatePluginSettings;
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;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.UpdatePluginSettings;
/// <summary>
/// Contains integration tests for the <see cref="UpdatePluginSettingsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePluginSettingsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="UpdatePluginSettingsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdatePluginSettingsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task UpdatePluginSettings_WhenPluginExists_ShouldUpdateTheSettings()
{
// Arrange
Guid pluginId = Guid.NewGuid();
await SeedPluginAsync(pluginId, "Test Plugin");
UpdatePluginSettingsRequest request = new(
PluginId: pluginId,
Settings: new Dictionary<string, string> { ["Key1"] = "Value1" }
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/plugins/{pluginId}/settings", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
PluginEntity? storedPlugin = await dbContext.Plugins.FirstOrDefaultAsync(plugin => plugin.Id == pluginId);
Assert.NotNull(storedPlugin);
Assert.Contains("Value1", storedPlugin!.SettingsJson);
}
[Fact]
public async Task UpdatePluginSettings_WhenPluginDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid pluginId = Guid.NewGuid();
UpdatePluginSettingsRequest request = new(
PluginId: pluginId,
Settings: new Dictionary<string, string> { ["Key1"] = "Value1" }
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/plugins/{pluginId}/settings", request);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("PluginNotFound", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/plugins/{pluginId}/settings", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
/// <summary>
/// Seeds a <see cref="PluginEntity"/> in the database.
/// </summary>
/// <param name="pluginId">The Id of the plugin.</param>
/// <param name="name">The display name of the plugin.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedPluginAsync(Guid pluginId, string name)
{
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
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}