mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 06:11:10 +00:00
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:
1 parent
48ad8692af
commit
64e5163229
127 files changed
+5541
-5296
No files matched your search
+22
-14
@@ -1,11 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Seed;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
@@ -33,6 +35,8 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -43,17 +47,18 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
/// <summary>
|
||||
/// Creates an HTTP client with authentication headers and a test user
|
||||
/// </summary>
|
||||
/// <param name="permissions">The permissions granted directly to the test user, if any.</param>
|
||||
/// <returns>An HTTP client configured with auth headers</returns>
|
||||
public async Task<HttpClient> CreateAuthenticatedClientAsync()
|
||||
public async Task<HttpClient> CreateAuthenticatedClientAsync(params AuthorizationPermission[] permissions)
|
||||
{
|
||||
HttpClient client = CreateClient();
|
||||
TestUsername = $"testuser_{Guid.NewGuid()}";
|
||||
|
||||
// add the X-Forwarded-For header
|
||||
// Add the X-Forwarded-For header.
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}");
|
||||
|
||||
// perform authentication
|
||||
await CreateAndAuthenticateUser(client);
|
||||
// Perform authentication.
|
||||
await CreateAndAuthenticateUser(client, permissions);
|
||||
|
||||
return client;
|
||||
}
|
||||
@@ -62,20 +67,23 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
/// Creates and authenticates a test user.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to configure with auth.</param>
|
||||
/// <param name="permissions">The permissions granted directly to the test user.</param>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateAndAuthenticateUser(HttpClient client)
|
||||
private async Task<UserEntity> CreateAndAuthenticateUser(HttpClient client, AuthorizationPermission[] permissions)
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// create test user
|
||||
// Create test user, with the permissions granted directly to it.
|
||||
UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
foreach (AuthorizationPermission permission in permissions)
|
||||
user.UserPermissions.Add(_userPermissionEntityFixture.Create(user, _permissionEntityFixture.Create(permissionName: permission, createdBy: user.Id)));
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// authenticate user
|
||||
// Authenticate user.
|
||||
LoginRequest loginRequest = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!",
|
||||
@@ -86,7 +94,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
// set auth header for subsequent requests
|
||||
// Set auth header for subsequent requests.
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
|
||||
|
||||
return user;
|
||||
@@ -101,11 +109,11 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
HttpClient client = CreateClient();
|
||||
TestUsername = $"testuser_{Guid.NewGuid()}";
|
||||
|
||||
// add the X-Forwarded-For header
|
||||
// Add the X-Forwarded-For header.
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For",
|
||||
$"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}");
|
||||
|
||||
// create and authenticate admin user
|
||||
// Create and authenticate admin user.
|
||||
await CreateAndAuthenticateAdminUser(client);
|
||||
|
||||
return client;
|
||||
@@ -122,20 +130,20 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService<IDataSeedService>();
|
||||
|
||||
// create test user
|
||||
// Create test user.
|
||||
UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// set up admin permissions and roles
|
||||
// Set up admin permissions and roles.
|
||||
await dataSeedService.SetDefaultAuthorizationPermissionsAsync(user.Id, CancellationToken.None);
|
||||
await dataSeedService.SetDefaultAuthorizationRolesAsync(user.Id, CancellationToken.None);
|
||||
await dataSeedService.SetAdminRolePermissionsAsync(user.Id, CancellationToken.None);
|
||||
await dataSeedService.SetAdminRoleToAdministratorAccount(user.Id, CancellationToken.None);
|
||||
|
||||
// authenticate user
|
||||
// Authenticate user.
|
||||
LoginRequest loginRequest = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!",
|
||||
@@ -146,7 +154,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
// set auth header for subsequent requests
|
||||
// Set auth header for subsequent requests.
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
|
||||
|
||||
return user;
|
||||
|
||||
+126
-2
@@ -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();
|
||||
|
||||
+2
-1
@@ -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]
|
||||
|
||||
+66
-9
@@ -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>
|
||||
|
||||
+112
@@ -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();
|
||||
}
|
||||
}
|
||||
+112
@@ -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();
|
||||
}
|
||||
}
|
||||
+112
@@ -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();
|
||||
}
|
||||
}
|
||||
-140
@@ -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();
|
||||
}
|
||||
}
|
||||
-140
@@ -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();
|
||||
}
|
||||
}
|
||||
-156
@@ -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();
|
||||
}
|
||||
}
|
||||
-199
@@ -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();
|
||||
}
|
||||
}
|
||||
-156
@@ -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();
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetLibraryTypeArtworkProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryArtworkProviderDtoFixture _libraryArtworkProviderDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryTypeArtworkProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetLibraryTypeArtworkProvidersEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeArtworkProviders_WhenCalledByAuthenticatedUser_ShouldReturnProvidersJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string libraryType = "Book";
|
||||
LibraryArtworkProviderDto[] expectedProviders =
|
||||
[
|
||||
_libraryArtworkProviderDtoFixture.Create(name: "EPUB Reader", isEnabled: false)
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{libraryType}", expectedProviders);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-artwork-providers/{libraryType}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetArrayLength());
|
||||
Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeArtworkProviders_WhenCalled_ShouldRequestProvidersFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string libraryType = "Book";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{libraryType}", Array.Empty<LibraryArtworkProviderDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-artwork-providers/{libraryType}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains($"libraries/artwork-providers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeArtworkProviders_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-artwork-providers/Book");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetLibraryTypeBookReadersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryTypeBookReadersEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryTypeBookReadersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetLibraryTypeBookReadersEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeBookReaders_WhenCalledByAuthenticatedUser_ShouldReturnBookReadersJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string libraryType = "Book";
|
||||
LibraryBookReaderDto[] expectedReaders =
|
||||
[
|
||||
_libraryBookReaderDtoFixture.Create(name: "EPUB Reader", isEnabled: false)
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{libraryType}", expectedReaders);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-book-readers/{libraryType}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetArrayLength());
|
||||
Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeBookReaders_WhenCalled_ShouldRequestBookReadersFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string libraryType = "Book";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{libraryType}", Array.Empty<LibraryBookReaderDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-book-readers/{libraryType}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains($"libraries/book-readers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeBookReaders_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-book-readers/Book");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetLibraryTypeMetadataProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryMetadataProviderDtoFixture _libraryMetadataProviderDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryTypeMetadataProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetLibraryTypeMetadataProvidersEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeMetadataProviders_WhenCalledByAuthenticatedUser_ShouldReturnProvidersJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string libraryType = "Book";
|
||||
LibraryMetadataProviderDto[] expectedProviders =
|
||||
[
|
||||
_libraryMetadataProviderDtoFixture.Create(name: "EPUB Reader", isEnabled: false)
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{libraryType}", expectedProviders);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-metadata-providers/{libraryType}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetArrayLength());
|
||||
Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeMetadataProviders_WhenCalled_ShouldRequestProvidersFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string libraryType = "Book";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{libraryType}", Array.Empty<LibraryMetadataProviderDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-metadata-providers/{libraryType}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains($"libraries/metadata-providers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeMetadataProviders_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-metadata-providers/Book");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+47
-2
@@ -1,7 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
@@ -17,6 +20,7 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Manage
|
||||
public class LibrariesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibrariesIndexViewEndpointTests"/> class.
|
||||
@@ -44,8 +48,8 @@ public class LibrariesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/en-us/libraries/manage", "%2Fen-us%2Flibraries%2Fmanage")] // plain page
|
||||
[InlineData("/en-us/libraries/manage?tab=scans", "%2Fen-us%2Flibraries%2Fmanage%3Ftab%3Dscans")] // query string is kept
|
||||
[InlineData("/en-us/libraries/manage", "%2Fen-us%2Flibraries%2Fmanage")] // Plain page.
|
||||
[InlineData("/en-us/libraries/manage?tab=scans", "%2Fen-us%2Flibraries%2Fmanage%3Ftab%3Dscans")] // Query string is kept.
|
||||
public async Task LibrariesIndexView_WhenNavigatedToWithoutAuthentication_ShouldRedirectToLoginWithRequestedPageAsReturnUrl(string requestedUrl, string expectedEncodedReturnUrl)
|
||||
{
|
||||
// Arrange
|
||||
@@ -60,4 +64,45 @@ public class LibrariesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal($"http://localhost/en-us/auth/login?returnUrl={expectedEncodedReturnUrl}", response.Headers.Location!.ToString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("User", true, "true")] // The permission lets a user manage the libraries they own.
|
||||
[InlineData("User", false, "false")] // Without the permission, a user cannot change even the libraries they own.
|
||||
[InlineData("Admin", false, "true")] // An administrator can manage every library, with or without the permission.
|
||||
public async Task LibrariesIndexView_WhenRendered_ShouldOfferTheEditAndDeleteActionsOnlyToUsersAllowedToManageLibraries(string role, bool hasManagePermission, string expectedCanManageLibraries)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(
|
||||
userId: Guid.NewGuid(),
|
||||
role: role,
|
||||
permissions: hasManagePermission ? [AuthorizationPermission.CanCreateLibraries] : []);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains($"const canManageLibraries = {expectedCanManageLibraries};", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LibrariesIndexView_WhenRenderedInACultureWithNonAsciiLabels_ShouldInjectTheScriptLabelsAsJson()
|
||||
{
|
||||
// Arrange
|
||||
// Razor would encode the non-ASCII letters of a raw label as HTML entities, which the browser shows literally inside a script, while JSON escapes them
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/ro-ro/libraries/manage");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("\"LibraryDeleted\":\"Biblioteca a fost \\u0219tears\\u0103!\"", content);
|
||||
Assert.DoesNotContain("ștears", content);
|
||||
}
|
||||
}
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderArtworkProviders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ReorderArtworkProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReorderArtworkProvidersEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReorderArtworkProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ReorderArtworkProvidersEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReorderArtworkProviders_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldReorderProvidersAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
Guid secondPluginId = Guid.NewGuid();
|
||||
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
pluginIds: [firstPluginId, secondPluginId]
|
||||
);
|
||||
string expectedEndpoint = $"libraries/{libraryId}/artwork-providers/reorder";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-artwork-providers")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
|
||||
}
|
||||
}
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderMetadataProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ReorderMetadataProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReorderMetadataProvidersEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReorderMetadataProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ReorderMetadataProvidersEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReorderMetadataProviders_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldReorderProvidersAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
Guid secondPluginId = Guid.NewGuid();
|
||||
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
pluginIds: [firstPluginId, secondPluginId]
|
||||
);
|
||||
string expectedEndpoint = $"libraries/{libraryId}/metadata-providers/reorder";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-metadata-providers")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
|
||||
}
|
||||
}
|
||||
+37
@@ -64,6 +64,43 @@ public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveLibrary_WhenAProviderChoiceHasNoEnabledState_ShouldForwardItWithoutAState()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
LibraryDto request = _libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book");
|
||||
request.Id = null;
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
// The choice is sent without its enabled state, the way a caller that only reorders the providers would send it.
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item")
|
||||
{
|
||||
Content = JsonContent.Create(new
|
||||
{
|
||||
request.Title,
|
||||
request.LibraryType,
|
||||
request.ContentLocations,
|
||||
MetadataProviders = new[] { new { PluginId = pluginId } }
|
||||
})
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
(string _, object? data) = Assert.Single(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
|
||||
LibraryDto forwardedLibrary = Assert.IsType<LibraryDto>(data);
|
||||
LibraryProviderSelectionDto forwardedChoice = Assert.Single(forwardedLibrary.MetadataProviders!);
|
||||
Assert.Equal(pluginId, forwardedChoice.PluginId);
|
||||
Assert.Null(forwardedChoice.IsEnabled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldReturnBadRequest()
|
||||
{
|
||||
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetArtworkProviderEnabled;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetArtworkProviderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SetArtworkProviderEnabledEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetArtworkProviderEnabledEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetArtworkProviderEnabledEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SetArtworkProviderEnabledEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetArtworkProviderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableProviderAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
pluginId: pluginId,
|
||||
isEnabled: true
|
||||
);
|
||||
string expectedEndpoint = $"libraries/{libraryId}/artwork-providers/{pluginId}/enabled";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-artwork-provider-enabled")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
|
||||
}
|
||||
}
|
||||
-87
@@ -1,87 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Common;
|
||||
using Lumina.Presentation.Web.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetBookReaderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SetBookReaderEnabledEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetBookReaderEnabledEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetBookReaderEnabledEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SetBookReaderEnabledEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetBookReaderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableReaderAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
|
||||
string expectedEndpoint = $"libraries/{libraryId}/book-readers/{pluginId}/enabled";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new EmptyRequest());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetBookReaderEnabled_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create();
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
}
|
||||
}
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetMetadataProviderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SetMetadataProviderEnabledEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetMetadataProviderEnabledEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetMetadataProviderEnabledEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SetMetadataProviderEnabledEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetMetadataProviderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableProviderAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
pluginId: pluginId,
|
||||
isEnabled: true
|
||||
);
|
||||
string expectedEndpoint = $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-metadata-provider-enabled")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user