Hardens test assertions and adds missing test coverage.

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

No files matched your search

@@ -0,0 +1,148 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.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.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.AddLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.AddLibrary;
/// <summary>
/// Contains integration tests for the <see cref="AddLibraryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddLibraryEndpointTests : 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="AddLibraryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddLibraryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
}
[Fact]
public async Task AddLibrary_WhenCalledWithValidData_ShouldCreateLibrary()
{
// Arrange
AddLibraryRequest request = new(
Title: "New Library",
LibraryType: "EBook",
ContentLocations: ["C:/Media"],
CoverImage: null,
IsEnabled: true,
IsLocked: false,
DownloadMetadataFromWeb: true,
ShouldSaveMetadataInMediaDirectories: false,
ShouldSkipUnchangedDirectoriesDuringScan: true
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
Assert.NotNull(library);
Assert.Equal("New Library", library!.Title);
Assert.Equal(LibraryType.EBook, library.LibraryType);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(lib => lib.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.Equal("New Library", storedLibrary!.Title);
}
[Fact]
public async Task AddLibrary_WhenCalledByRegularUser_ShouldReturnForbidden()
{
// Arrange
_client = await _apiFactory.CreateAuthenticatedClientAsync();
AddLibraryRequest request = new(
Title: "New Library",
LibraryType: "EBook",
ContentLocations: ["C:/Media"],
CoverImage: null,
IsEnabled: true,
IsLocked: false,
DownloadMetadataFromWeb: true,
ShouldSaveMetadataInMediaDirectories: false,
ShouldSkipUnchangedDirectoriesDuringScan: true
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/libraries", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// 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
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();
await dbContext.Libraries.ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
_apiFactory.Dispose();
}
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibrariesScan;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.CancelLibrariesScan;
/// <summary>
/// Contains integration tests for the <see cref="CancelLibrariesScanEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CancelLibrariesScanEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="CancelLibrariesScanEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public CancelLibrariesScanEndpointTests(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 CancelLibrariesScan_WhenCalled_ShouldReturnNoContent()
{
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/scans/cancel", new { });
// Assert
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,89 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibraryScan;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.CancelLibraryScan;
/// <summary>
/// Contains integration tests for the <see cref="CancelLibraryScanEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CancelLibraryScanEndpointTests : 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="CancelLibraryScanEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public CancelLibraryScanEndpointTests(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 CancelLibraryScan_WhenScanDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid scanId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans/{scanId}/cancel", new { });
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("LibraryScanNotFound", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/scans/{scanId}/cancel", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,196 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.DeleteLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.DeleteLibrary;
/// <summary>
/// Contains integration tests for the <see cref="DeleteLibraryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteLibraryEndpointTests : 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="DeleteLibraryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteLibraryEndpointTests(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 DeleteLibrary_WhenLibraryExists_ShouldDeleteIt()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(lib => lib.Id == libraryId);
Assert.Null(storedLibrary);
}
[Fact]
public async Task DeleteLibrary_WhenLibraryDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid libraryId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("LibraryNotFound", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task DeleteLibrary_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
{
// Arrange
Guid otherUserId = await SeedUserAsync();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, otherUserId);
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
/// <summary>
/// Seeds a <see cref="UserEntity"/> and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(new UserEntity
{
Id = userId,
Username = $"otheruser_{Guid.NewGuid()}",
Password = "TestPass123!",
Libraries = [],
UserPermissions = [],
UserRole = null,
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow
});
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Seeds a <see cref="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(new LibraryEntity
{
Id = libraryId,
UserId = userId,
Title = "Test Library",
LibraryType = LibraryType.EBook,
ContentLocations = [],
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,139 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetEnabledLibraries;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
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.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.GetEnabledLibraries;
/// <summary>
/// Contains integration tests for the <see cref="GetEnabledLibrariesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetEnabledLibrariesEndpointTests : 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="GetEnabledLibrariesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetEnabledLibrariesEndpointTests(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 GetEnabledLibraries_WhenEnabledLibrariesExist_ShouldReturnThem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid enabledLibraryId = Guid.NewGuid();
await SeedLibraryAsync(enabledLibraryId, userId, "Enabled Library", isEnabled: true);
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/enabled");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
LibraryResponse[]? libraries = await response.Content.ReadFromJsonAsync<LibraryResponse[]>(_jsonOptions);
Assert.NotNull(libraries);
Assert.Contains(libraries!, library => library.Id == enabledLibraryId);
}
[Fact]
public async Task GetEnabledLibraries_WhenOnlyDisabledLibrariesExist_ShouldReturnEmptyList()
{
// Arrange
Guid userId = GetCurrentUserId();
await SeedLibraryAsync(Guid.NewGuid(), userId, "Disabled Library", isEnabled: false);
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/enabled");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
LibraryResponse[]? libraries = await response.Content.ReadFromJsonAsync<LibraryResponse[]>(_jsonOptions);
Assert.NotNull(libraries);
Assert.Empty(libraries!);
}
/// <summary>
/// Seeds a <see cref="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>
/// <param name="title">The title of the library.</param>
/// <param name="isEnabled">Whether the library is enabled.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId, string title, bool isEnabled)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(new LibraryEntity
{
Id = libraryId,
UserId = userId,
Title = title,
LibraryType = LibraryType.EBook,
ContentLocations = [],
IsEnabled = isEnabled,
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,163 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraries;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.GetLibraries;
/// <summary>
/// Contains integration tests for the <see cref="GetLibrariesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibrariesEndpointTests : 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="GetLibrariesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibrariesEndpointTests(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 GetLibraries_WhenLibrariesExist_ShouldReturnOnlyTheOwnedLibraries()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid otherUserId = await SeedUserAsync();
Guid ownedLibraryId = Guid.NewGuid();
Guid otherUserLibraryId = Guid.NewGuid();
await SeedLibraryAsync(ownedLibraryId, userId, "Owned Library");
await SeedLibraryAsync(otherUserLibraryId, otherUserId, "Other User Library");
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
LibraryResponse[]? libraries = await response.Content.ReadFromJsonAsync<LibraryResponse[]>(_jsonOptions);
Assert.NotNull(libraries);
LibraryResponse ownedLibrary = Assert.Single(libraries!, library => library.Id == ownedLibraryId);
Assert.Equal("Owned Library", ownedLibrary.Title);
Assert.DoesNotContain(libraries, library => library.Id == otherUserLibraryId);
}
[Fact]
public async Task GetLibraries_WhenNoLibrariesExist_ShouldReturnEmptyList()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
LibraryResponse[]? libraries = await response.Content.ReadFromJsonAsync<LibraryResponse[]>(_jsonOptions);
Assert.NotNull(libraries);
Assert.Empty(libraries!);
}
/// <summary>
/// Seeds a <see cref="UserEntity"/> and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(new UserEntity
{
Id = userId,
Username = $"otheruser_{Guid.NewGuid()}",
Password = "TestPass123!",
Libraries = [],
UserPermissions = [],
UserRole = null,
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow
});
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Seeds a <see cref="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>
/// <param name="title">The title of the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(new LibraryEntity
{
Id = libraryId,
UserId = userId,
Title = title,
LibraryType = LibraryType.EBook,
ContentLocations = [],
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,146 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.GetLibrary;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryEndpointTests : 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="GetLibraryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryEndpointTests(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 GetLibrary_WhenLibraryExists_ShouldReturnIt()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Test Library");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
Assert.NotNull(library);
Assert.Equal(libraryId, library!.Id);
Assert.Equal("Test Library", library.Title);
}
[Fact]
public async Task GetLibrary_WhenLibraryDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid libraryId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("LibraryNotFound", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
/// <summary>
/// Seeds a <see cref="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>
/// <param name="title">The title of the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(new LibraryEntity
{
Id = libraryId,
UserId = userId,
Title = title,
LibraryType = LibraryType.EBook,
ContentLocations = [],
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,151 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryScanProgress;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryScanProgress;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryScanProgressEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryScanProgressEndpointTests : 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="GetLibraryScanProgressEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryScanProgressEndpointTests(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 GetLibraryScanProgress_WhenLibraryDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid scanId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/scans/{scanId}/progress");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("LibraryNotFound", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/scans/{scanId}/progress", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task GetLibraryScanProgress_WhenScanIsNotTracked_ShouldReturnNotFound()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
Guid scanId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/scans/{scanId}/progress");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("LibraryScanNotFound", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/scans/{scanId}/progress", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
/// <summary>
/// Seeds a <see cref="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(new LibraryEntity
{
Id = libraryId,
UserId = userId,
Title = "Test Library",
LibraryType = LibraryType.EBook,
ContentLocations = [],
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,71 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetRunningLibraryScans;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.GetRunningLibraryScans;
/// <summary>
/// Contains integration tests for the <see cref="GetRunningLibraryScansEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRunningLibraryScansEndpointTests : 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="GetRunningLibraryScansEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetRunningLibraryScansEndpointTests(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 GetRunningLibraryScans_WhenNoScansAreRunning_ShouldReturnEmptyList()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/scans/running");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
IEnumerable<MediaLibraryScanProgressResponse>? progress = await response.Content.ReadFromJsonAsync<IEnumerable<MediaLibraryScanProgressResponse>>(_jsonOptions);
Assert.NotNull(progress);
Assert.Empty(progress!);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,135 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibraries;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.ScanLibraries;
/// <summary>
/// Contains integration tests for the <see cref="ScanLibrariesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScanLibrariesEndpointTests : 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="ScanLibrariesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ScanLibrariesEndpointTests(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 ScanLibraries_WhenEnabledAndUnlockedLibrariesExist_ShouldStartScans()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/scans", new { });
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
IEnumerable<MediaLibraryScanResponse>? scanResponses = await response.Content.ReadFromJsonAsync<IEnumerable<MediaLibraryScanResponse>>(_jsonOptions);
Assert.NotNull(scanResponses);
Assert.Contains(scanResponses!, scanResponse => scanResponse.LibraryId == libraryId);
}
[Fact]
public async Task ScanLibraries_WhenNoLibrariesExist_ShouldReturnEmptyList()
{
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/scans", new { });
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
IEnumerable<MediaLibraryScanResponse>? scanResponses = await response.Content.ReadFromJsonAsync<IEnumerable<MediaLibraryScanResponse>>(_jsonOptions);
Assert.NotNull(scanResponses);
Assert.Empty(scanResponses!);
}
/// <summary>
/// Seeds an enabled and unlocked <see cref="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(new LibraryEntity
{
Id = libraryId,
UserId = userId,
Title = "Test Library",
LibraryType = LibraryType.EBook,
ContentLocations = [],
IsEnabled = true,
IsLocked = false,
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,175 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.ScanLibrary;
/// <summary>
/// Contains integration tests for the <see cref="ScanLibraryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScanLibraryEndpointTests : 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="ScanLibraryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ScanLibraryEndpointTests(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 ScanLibrary_WhenLibraryIsEnabledAndUnlocked_ShouldStartAScan()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, isEnabled: true, isLocked: false);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans", new { });
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
MediaLibraryScanResponse? scanResponse = await response.Content.ReadFromJsonAsync<MediaLibraryScanResponse>(_jsonOptions);
Assert.NotNull(scanResponse);
Assert.Equal(libraryId, scanResponse!.LibraryId);
Assert.NotEqual(Guid.Empty, scanResponse.ScanId);
}
[Fact]
public async Task ScanLibrary_WhenLibraryIsDisabled_ShouldReturnForbidden()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, isEnabled: false, isLocked: false);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans", new { });
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Forbidden", problemDetails["title"].GetString());
Assert.Equal("CannotScanDisabledLibrary", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/scans", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task ScanLibrary_WhenLibraryDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid libraryId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans", new { });
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("LibraryNotFound", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/scans", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
/// <summary>
/// Seeds a <see cref="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>
/// <param name="isEnabled">Whether the library is enabled.</param>
/// <param name="isLocked">Whether the library is locked.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId, bool isEnabled, bool isLocked)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(new LibraryEntity
{
Id = libraryId,
UserId = userId,
Title = "Test Library",
LibraryType = LibraryType.EBook,
ContentLocations = [],
IsEnabled = isEnabled,
IsLocked = isLocked,
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,179 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.UpdateLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.UpdateLibrary;
/// <summary>
/// Contains integration tests for the <see cref="UpdateLibraryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateLibraryEndpointTests : 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="UpdateLibraryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateLibraryEndpointTests(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 UpdateLibrary_WhenLibraryExists_ShouldUpdateIt()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Original Title");
UpdateLibraryRequest request = new(
Id: libraryId,
UserId: userId,
Title: "Updated Title",
LibraryType: "EBook",
ContentLocations: ["C:/Media"],
CoverImage: null,
IsEnabled: true,
IsLocked: false,
DownloadMetadataFromWeb: true,
ShouldSaveMetadataInMediaDirectories: false,
ShouldSkipUnchangedDirectoriesDuringScan: true
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
Assert.NotNull(library);
Assert.Equal("Updated Title", library!.Title);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(lib => lib.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal("Updated Title", storedLibrary!.Title);
}
[Fact]
public async Task UpdateLibrary_WhenLibraryDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid libraryId = Guid.NewGuid();
UpdateLibraryRequest request = new(
Id: libraryId,
UserId: Guid.NewGuid(),
Title: "Updated Title",
LibraryType: "EBook",
ContentLocations: ["C:/Media"],
CoverImage: null,
IsEnabled: true,
IsLocked: false,
DownloadMetadataFromWeb: true,
ShouldSaveMetadataInMediaDirectories: false,
ShouldSkipUnchangedDirectoriesDuringScan: true
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("LibraryNotFound", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
/// <summary>
/// Seeds a <see cref="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>
/// <param name="title">The title of the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(new LibraryEntity
{
Id = libraryId,
UserId = userId,
Title = title,
LibraryType = LibraryType.EBook,
ContentLocations = [],
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook;
/// <summary>
/// Contains integration tests for the <see cref="GetBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="GetBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetBookEndpointTests(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 GetBook_WhenCalled_ShouldReturnOk()
{
// Arrange
Guid bookId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}