Updates the provider configuration and ownership tests

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

No files matched your search

@@ -10,6 +10,7 @@ using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -32,6 +33,7 @@ public class AddLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
@@ -359,6 +361,128 @@ public class AddLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
[Fact]
public async Task AddLibrary_WhenAProviderChoiceNamesAnUnsupportedPlugin_ShouldReturnValidationProblemAndNotPersist()
{
// Arrange
string title = "Unsupported Provider Library";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "Book",
contentLocations: ["C:/Media"],
coverImage: null,
metadataProviders: [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)]
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
await AssertValidationProblemAsync(response, "PluginNotSupportedForLibraryType");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
[Fact]
public async Task AddLibrary_WhenAProviderChoiceIsNull_ShouldReturnValidationProblemAndNotPersist()
{
// Arrange
string title = "Null Provider Choice Library";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "Book",
contentLocations: ["C:/Media"],
coverImage: null,
bookReaders: [null]
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
await AssertValidationProblemAsync(response, "PluginIdCannotBeEmpty");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
[Fact]
public async Task AddLibrary_WhenAPathTemplatePartIsNull_ShouldReturnValidationProblemAndNotPersist()
{
// Arrange
string title = "Null Path Template Part Library";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "Book",
contentLocations: ["C:/Media"],
coverImage: null,
pathTemplateParts: [null]
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
await AssertValidationProblemAsync(response, "PathTemplatePartKindNotSupportedForLibraryType");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
[Fact]
public async Task AddLibrary_WhenProviderPluginIdsAreDuplicated_ShouldReturnValidationProblemAndNotPersist()
{
// Arrange
string title = "Duplicated Provider Library";
Guid pluginId = Guid.NewGuid();
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "Book",
contentLocations: ["C:/Media"],
coverImage: null,
bookReaders: [_libraryProviderSelectionRequestFixture.Create(pluginId: pluginId), _libraryProviderSelectionRequestFixture.Create(pluginId: pluginId, isEnabled: false)]
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
await AssertValidationProblemAsync(response, "PluginIdsMustBeUnique");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
[Fact]
public async Task AddLibrary_WhenProviderChoicesAreEmpty_ShouldCreateLibrary()
{
// Arrange
string title = "Empty Provider Choices Library";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "Book",
contentLocations: ["C:/Media"],
coverImage: null,
metadataProviders: [],
artworkProviders: [],
bookReaders: []
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.True(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
/// <summary>
/// Asserts that <paramref name="response"/> carries the standard validation problem of the add library route.
/// </summary>
@@ -395,12 +519,12 @@ public class AddLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// clear junction tables first
// Clear junction tables first.
await dbContext.Set<Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity>().ExecuteDeleteAsync();
// then clear main tables
// Then clear main tables.
await dbContext.Set<Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity>().ExecuteDeleteAsync();
await dbContext.Set<Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity>().ExecuteDeleteAsync();
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.DeleteLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -54,7 +55,7 @@ public class DeleteLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
_client = await _apiFactory.CreateAuthenticatedClientAsync(AuthorizationPermission.CanCreateLibraries);
}
[Fact]
@@ -6,6 +6,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.UpdateLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -41,6 +42,7 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateLibraryEndpointTests"/> class.
@@ -57,7 +59,7 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
_client = await _apiFactory.CreateAuthenticatedClientAsync(AuthorizationPermission.CanCreateLibraries);
}
[Fact]
@@ -69,7 +71,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title");
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -105,7 +106,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
Guid libraryId = Guid.NewGuid();
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: Guid.NewGuid(),
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -144,7 +144,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: false, completionThresholdPercentage: null);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -185,7 +184,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -226,7 +224,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -267,7 +264,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: false, completionThresholdPercentage: null);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -308,7 +304,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -345,7 +340,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -373,6 +367,69 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateLibrary_WhenAProviderChoiceNamesAnUnsupportedPlugin_ShouldReturnValidationProblemAndKeepTheStoredLibrary()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 70,
artworkProviders: [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)]
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
await AssertValidationProblemAsync(response, $"/api/v1/libraries/{libraryId}", "PluginNotSupportedForLibraryType");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal("Original Title", storedLibrary!.Title);
}
[Fact]
public async Task UpdateLibrary_WhenProviderChoicesAreEmpty_ShouldUpdateTheLibrary()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 70,
metadataProviders: [],
artworkProviders: [],
bookReaders: []
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
response.EnsureSuccessStatusCode();
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal("Updated Title", storedLibrary!.Title);
}
/// <summary>
/// Asserts that <paramref name="response"/> carries the standard validation problem of the update library route.
/// </summary>
@@ -0,0 +1,112 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.Plugins;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryTypeArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryTypeArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Theory]
[InlineData("Book")]
[InlineData("music")] // The casing of the type is ignored.
public async Task GetLibraryTypeArtworkProviders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableProviders(string libraryType)
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<LibraryArtworkProviderResponse>? providers = JsonSerializer.Deserialize<List<LibraryArtworkProviderResponse>>(content, _jsonOptions);
Assert.NotNull(providers);
// The test host loads no plugins, so no provider supports the type; every provider that is returned starts disabled.
Assert.All(providers!, provider => Assert.False(provider.IsEnabled));
}
[Fact]
public async Task GetLibraryTypeArtworkProviders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult()
{
// Arrange
string libraryType = "NotARealLibraryType";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
Assert.Equal($"/api/v1/libraries/artwork-providers/{libraryType}", problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
}
[Fact]
public async Task GetLibraryTypeArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/artwork-providers/Book");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,112 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.Plugins;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryTypeBookReadersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeBookReadersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryTypeBookReadersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Theory]
[InlineData("Book")]
[InlineData("music")] // The casing of the type is ignored.
public async Task GetLibraryTypeBookReaders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableReaders(string libraryType)
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<LibraryBookReaderResponse>? readers = JsonSerializer.Deserialize<List<LibraryBookReaderResponse>>(content, _jsonOptions);
Assert.NotNull(readers);
// The test host loads no plugins, so no reader supports the type; every reader that is returned starts disabled.
Assert.All(readers!, reader => Assert.False(reader.IsEnabled));
}
[Fact]
public async Task GetLibraryTypeBookReaders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult()
{
// Arrange
string libraryType = "NotARealLibraryType";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
Assert.Equal($"/api/v1/libraries/book-readers/{libraryType}", problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
}
[Fact]
public async Task GetLibraryTypeBookReaders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/book-readers/Book");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,112 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.Plugins;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryTypeMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryTypeMetadataProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Theory]
[InlineData("Book")]
[InlineData("music")] // The casing of the type is ignored.
public async Task GetLibraryTypeMetadataProviders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableProviders(string libraryType)
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<LibraryMetadataProviderResponse>? providers = JsonSerializer.Deserialize<List<LibraryMetadataProviderResponse>>(content, _jsonOptions);
Assert.NotNull(providers);
// The test host loads no plugins, so no provider supports the type; every provider that is returned starts disabled.
Assert.All(providers!, provider => Assert.False(provider.IsEnabled));
}
[Fact]
public async Task GetLibraryTypeMetadataProviders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult()
{
// Arrange
string libraryType = "NotARealLibraryType";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
Assert.Equal($"/api/v1/libraries/metadata-providers/{libraryType}", problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
}
[Fact]
public async Task GetLibraryTypeMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/metadata-providers/Book");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -1,140 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
/// <summary>
/// Contains integration tests for the <see cref="ReorderLibraryArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ReorderLibraryArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task ReorderLibraryArtworkProviders_WhenCalledWithValidData_ShouldReorderTheProviders()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginIdA = Guid.NewGuid();
Guid pluginIdB = Guid.NewGuid();
await SeedConfigurationAsync(libraryId, pluginIdA, rank: 1);
await SeedConfigurationAsync(libraryId, pluginIdB, rank: 2);
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(
libraryId: libraryId,
pluginIds: [pluginIdB, pluginIdA]
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<LibraryArtworkProviderConfigurationEntity> configurations = await dbContext.LibraryArtworkProviderConfigurations
.Where(config => config.LibraryId == libraryId)
.OrderBy(config => config.Rank)
.ToListAsync();
Assert.Equal(2, configurations.Count);
Assert.Equal(pluginIdB, configurations[0].PluginId);
Assert.Equal(1, configurations[0].Rank);
Assert.Equal(pluginIdA, configurations[1].PluginId);
Assert.Equal(2, configurations[1].Rank);
}
/// <summary>
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> in the database.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <param name="pluginId">The Id of the plugin.</param>
/// <param name="rank">The rank of the provider.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -1,140 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders;
/// <summary>
/// Contains integration tests for the <see cref="ReorderLibraryMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ReorderLibraryMetadataProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task ReorderLibraryMetadataProviders_WhenCalledWithValidData_ShouldReorderTheProviders()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginIdA = Guid.NewGuid();
Guid pluginIdB = Guid.NewGuid();
await SeedConfigurationAsync(libraryId, pluginIdA, rank: 1);
await SeedConfigurationAsync(libraryId, pluginIdB, rank: 2);
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(
libraryId: libraryId,
pluginIds: [pluginIdB, pluginIdA]
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<LibraryMetadataProviderConfigurationEntity> configurations = await dbContext.LibraryMetadataProviderConfigurations
.Where(config => config.LibraryId == libraryId)
.OrderBy(config => config.Rank)
.ToListAsync();
Assert.Equal(2, configurations.Count);
Assert.Equal(pluginIdB, configurations[0].PluginId);
Assert.Equal(1, configurations[0].Rank);
Assert.Equal(pluginIdA, configurations[1].PluginId);
Assert.Equal(2, configurations[1].Rank);
}
/// <summary>
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a <see cref="LibraryMetadataProviderConfigurationEntity"/> in the database.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <param name="pluginId">The Id of the plugin.</param>
/// <param name="rank">The rank of the provider.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -1,156 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
/// <summary>
/// Contains integration tests for the <see cref="SetLibraryArtworkProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryArtworkProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task SetLibraryArtworkProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginId = Guid.NewGuid();
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations
.FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
Assert.NotNull(configuration);
Assert.True(configuration!.IsEnabled);
Assert.Equal(1, configuration.Rank);
}
[Fact]
public async Task SetLibraryArtworkProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginId = Guid.NewGuid();
await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false, rank: 1);
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations
.FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
Assert.NotNull(configuration);
Assert.True(configuration!.IsEnabled);
}
/// <summary>
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> in the database.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <param name="pluginId">The Id of the plugin.</param>
/// <param name="isEnabled">Whether the provider is enabled.</param>
/// <param name="rank">The rank of the provider.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -1,199 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled;
/// <summary>
/// Contains integration tests for the <see cref="SetLibraryBookReaderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new();
private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryBookReaderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task SetLibraryBookReaderEnabled_WhenNoConfigurationExists_ShouldCreateIt()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginId = Guid.NewGuid();
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryBookReaderConfigurationEntity? configuration = await dbContext.LibraryBookReaderConfigurations
.FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
Assert.NotNull(configuration);
Assert.True(configuration!.IsEnabled);
}
[Fact]
public async Task SetLibraryBookReaderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginId = Guid.NewGuid();
await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false);
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryBookReaderConfigurationEntity configuration = await dbContext.LibraryBookReaderConfigurations
.SingleAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
Assert.True(configuration.IsEnabled);
}
[Fact]
public async Task SetLibraryBookReaderEnabled_WhenLibraryIsNotOwned_ShouldReturnForbidden()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, otherUserId);
Guid pluginId = Guid.NewGuid();
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task SetLibraryBookReaderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary.LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a book reader configuration for the library and plugin.
/// </summary>
/// <param name="libraryId">The Id of the library.</param>
/// <param name="pluginId">The Id of the plugin.</param>
/// <param name="isEnabled">Whether the book reader is enabled.</param>
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryBookReaderConfigurations.Add(_libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: isEnabled));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a user that is not the authenticated one and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -1,156 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled;
/// <summary>
/// Contains integration tests for the <see cref="SetLibraryMetadataProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryMetadataProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryMetadataProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task SetLibraryMetadataProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginId = Guid.NewGuid();
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations
.FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
Assert.NotNull(configuration);
Assert.True(configuration!.IsEnabled);
Assert.Equal(1, configuration.Rank);
}
[Fact]
public async Task SetLibraryMetadataProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid pluginId = Guid.NewGuid();
await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false, rank: 1);
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations
.FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
Assert.NotNull(configuration);
Assert.True(configuration!.IsEnabled);
}
/// <summary>
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a <see cref="LibraryMetadataProviderConfigurationEntity"/> in the database.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <param name="pluginId">The Id of the plugin.</param>
/// <param name="isEnabled">Whether the provider is enabled.</param>
/// <param name="rank">The rank of the provider.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}