mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 07:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+41
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// Custom JSON converter for readonly collections.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReadOnlySetConverter<T> : JsonConverter<IReadOnlySet<T>>
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads and converts JSON to a <see cref="IReadOnlySet{T}"/> object.
|
||||
/// </summary>
|
||||
/// <param name="reader">The JSON reader.</param>
|
||||
/// <param name="typeToConvert">The type of the object to convert.</param>
|
||||
/// <param name="options">The serializer options.</param>
|
||||
/// <returns>The converted readonly collection.</returns>
|
||||
public override IReadOnlySet<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
HashSet<T>? list = JsonSerializer.Deserialize<HashSet<T>>(ref reader, options);
|
||||
return list ?? [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a readonly collection object to JSON. This method is not implemented.
|
||||
/// </summary>
|
||||
/// <param name="writer">The JSON writer.</param>
|
||||
/// <param name="value">The <see cref="IReadOnlySet{T}"/> object to write.</param>
|
||||
/// <param name="options">The serializer options.</param>
|
||||
public override void Write(Utf8JsonWriter writer, IReadOnlySet<T> value, JsonSerializerOptions options)
|
||||
{
|
||||
JsonSerializer.Serialize(writer, value.ToList(), options);
|
||||
}
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Common.Middlewares;
|
||||
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.Common.Middlewares;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="EventualConsistencyMiddleware"/> class through the real HTTP pipeline.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EventualConsistencyMiddlewareTests : IClassFixture<EventualConsistencyApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private const string FAVORITES_PATH = "/api/v1/users/me/favorites";
|
||||
private const string LOGIN_PATH = "/api/v1/auth/login";
|
||||
|
||||
private static readonly TimeSpan s_probeTimeout = TimeSpan.FromSeconds(10);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly EventualConsistencyApiFactory _apiFactory;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EventualConsistencyMiddlewareTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory with observable transactions and domain events.</param>
|
||||
public EventualConsistencyMiddlewareTests(EventualConsistencyApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client, and clears the probes after the login request completed.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_apiFactory.ResetProbes();
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
// The login request runs through the same middleware, so its dequeue of the response completion must finish before the probes observe the test request.
|
||||
await _apiFactory.QueueProbe.WaitForDequeueAsync(LOGIN_PATH, s_probeTimeout);
|
||||
_apiFactory.ResetProbes();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenTheResponseSucceeds_ShouldPublishTheQueuedEventAfterCommittingTheTransaction()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid bookId = await SeedBookAsync(userId);
|
||||
_apiFactory.ResetProbes();
|
||||
_apiFactory.QueueProbe.ShouldBlockOnEnqueue = true;
|
||||
Task<HttpResponseMessage> responseTask;
|
||||
|
||||
try
|
||||
{
|
||||
// Act
|
||||
// The POST runs on a dedicated task, so that a blocking domain event queue can never block the test thread that must release it.
|
||||
responseTask = Task.Run(async () => await _client.PostAsJsonAsync(FAVORITES_PATH, new { mediaKind = "Book", mediaItemId = bookId }));
|
||||
await _apiFactory.QueueProbe.WaitForEnqueueAsync(s_probeTimeout);
|
||||
|
||||
// Assert
|
||||
// The event is queued while the endpoint still runs, so it must not be published yet.
|
||||
Assert.Equal(0, _apiFactory.PublicationProbe.PublicationCount);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_apiFactory.QueueProbe.ReleaseEnqueue();
|
||||
_apiFactory.QueueProbe.ShouldBlockOnEnqueue = false;
|
||||
}
|
||||
|
||||
HttpResponseMessage response = await responseTask;
|
||||
await _apiFactory.PublicationProbe.WaitForPublicationAsync(s_probeTimeout);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.True(_apiFactory.PublicationProbe.WasFavoriteVisible);
|
||||
Assert.Equal(1, _apiFactory.QueueProbe.EnqueueCount);
|
||||
Assert.Equal(1, _apiFactory.QueueProbe.DequeueCount);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == bookId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenTheRequestFailsAfterQueueingTheEvent_ShouldRollBackTheTransactionAndNotPublishTheEvent()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid bookId = await SeedBookAsync(userId);
|
||||
_apiFactory.ResetProbes();
|
||||
_apiFactory.QueueProbe.ShouldThrowOnEnqueue = true;
|
||||
|
||||
try
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(FAVORITES_PATH, new { mediaKind = "Book", mediaItemId = bookId });
|
||||
await _apiFactory.TransactionProbe.WaitForRollbackAsync(FAVORITES_PATH, s_probeTimeout);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
Assert.Equal(1, _apiFactory.QueueProbe.EnqueueCount);
|
||||
Assert.Equal(0, _apiFactory.QueueProbe.DequeueCount);
|
||||
Assert.Equal(0, _apiFactory.QueueProbe.GetDequeueAttemptCount(FAVORITES_PATH));
|
||||
Assert.Equal(0, _apiFactory.PublicationProbe.PublicationCount);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == bookId));
|
||||
}
|
||||
finally
|
||||
{
|
||||
_apiFactory.QueueProbe.ShouldThrowOnEnqueue = false;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenCalled_ShouldRunThroughTheEventualConsistencyMiddleware()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(FAVORITES_PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
// The middleware dequeues the events only after committing a successful request, so a dequeue attempt for this path proves the pipeline ran through it.
|
||||
await _apiFactory.QueueProbe.WaitForDequeueAsync(FAVORITES_PATH, s_probeTimeout);
|
||||
Assert.True(_apiFactory.QueueProbe.GetDequeueAttemptCount(FAVORITES_PATH) > 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of a book library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the seeded library.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.CreateVersion7();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId,
|
||||
userId: userId,
|
||||
title: $"Eventual Consistency Library-{Guid.NewGuid():N}",
|
||||
libraryType: LibraryType.EBook,
|
||||
contentLocations: []));
|
||||
Guid bookId = Guid.CreateVersion7();
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(
|
||||
id: bookId,
|
||||
libraryId: libraryId,
|
||||
title: $"Eventual Consistency Book-{Guid.NewGuid():N}",
|
||||
includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <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(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||
List<Guid> bookIds = await dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)).Select(book => book.Id).ToListAsync();
|
||||
Guid? userId = await dbContext.Users
|
||||
.Where(user => user.Username == _apiFactory.TestUsername)
|
||||
.Select(user => (Guid?)user.Id)
|
||||
.FirstOrDefaultAsync();
|
||||
if (userId is not null)
|
||||
dbContext.Favorites.RemoveRange(dbContext.Favorites.Where(favorite => favorite.UserId == userId.Value));
|
||||
dbContext.Books.RemoveRange(dbContext.Books.Where(book => bookIds.Contains(book.Id)));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
#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;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
// <summary>
|
||||
/// Factory that extends <see cref="LuminaApiFactory"/> to provide authenticated HTTP clients for testing.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
{
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the username of the currently created test user.
|
||||
/// </summary>
|
||||
public string? TestUsername { get; private set; }
|
||||
|
||||
/// <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(params AuthorizationPermission[] permissions)
|
||||
{
|
||||
HttpClient client = CreateClient();
|
||||
TestUsername = $"testuser_{Guid.NewGuid()}";
|
||||
|
||||
// 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, permissions);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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, AuthorizationPermission[] permissions)
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// 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.
|
||||
LoginRequest loginRequest = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!",
|
||||
includeTotpCode: false
|
||||
);
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", loginRequest);
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
// Set auth header for subsequent requests.
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an HTTP client with authentication headers and an admin test user with all permissions.
|
||||
/// </summary>
|
||||
/// <returns>An HTTP client configured with admin auth headers.</returns>
|
||||
public async Task<HttpClient> CreateAuthenticatedAdminClientAsync()
|
||||
{
|
||||
HttpClient client = CreateClient();
|
||||
TestUsername = $"testuser_{Guid.NewGuid()}";
|
||||
|
||||
// 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.
|
||||
await CreateAndAuthenticateAdminUser(client);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates and authenticates an admin test user with all permissions.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to configure with auth.</param>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateAndAuthenticateAdminUser(HttpClient client)
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService<IDataSeedService>();
|
||||
|
||||
// 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.
|
||||
await dataSeedService.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
|
||||
await dataSeedService.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
||||
await dataSeedService.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
await dataSeedService.SetAdminRoleToAdministratorAccount(user.Id, CancellationToken.None);
|
||||
|
||||
// Authenticate user.
|
||||
LoginRequest loginRequest = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!",
|
||||
includeTotpCode: false
|
||||
);
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", loginRequest);
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
// Set auth header for subsequent requests.
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the currently created test user from the database.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Test classes must call this in their per-test <c>DisposeAsync</c> instead of <see cref="Dispose"/>. The
|
||||
/// factory is a shared <see cref="IClassFixture{TFixture}"/>, created once per test class and disposed by
|
||||
/// xUnit only after all tests in the class have run. Calling <see cref="Dispose"/> from a per-test
|
||||
/// <c>DisposeAsync</c> would dispose the web host and its service provider after the first test, making
|
||||
/// every subsequent test in the class fail with an <see cref="ObjectDisposedException"/> when it resolves
|
||||
/// services. <see cref="Dispose"/> is therefore reserved for xUnit's own class-teardown and must never be
|
||||
/// invoked from a test.
|
||||
/// </remarks>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
public async Task RemoveTestUserAsync()
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == TestUsername);
|
||||
if (user is not null)
|
||||
{
|
||||
dbContext.Users.Remove(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Called by xUnit when the test class completes. Do not call from tests; per-test cleanup must use
|
||||
/// <see cref="RemoveTestUserAsync"/>. See that method for the details.
|
||||
/// </remarks>
|
||||
public new void Dispose()
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == TestUsername);
|
||||
if (user is not null)
|
||||
{
|
||||
dbContext.Users.Remove(user);
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Observes the domain events published through the real domain event publisher.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class DomainEventPublicationProbe
|
||||
{
|
||||
private readonly Lock _signalLock = new();
|
||||
private TaskCompletionSource<bool> _publishedSignal = CreateSignal();
|
||||
private int _publicationCount;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of domain events that were published.
|
||||
/// </summary>
|
||||
public int PublicationCount => Volatile.Read(ref _publicationCount);
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the favorite of the last published event was visible from a separate database scope.
|
||||
/// </summary>
|
||||
public bool WasFavoriteVisible { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Clears the recorded observations, so that a test observes only the events published after the reset.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
Interlocked.Exchange(ref _publicationCount, 0);
|
||||
WasFavoriteVisible = false;
|
||||
lock (_signalLock)
|
||||
_publishedSignal = CreateSignal();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that a domain event was published, together with whether its favorite was visible at publication time.
|
||||
/// </summary>
|
||||
/// <param name="wasFavoriteVisible">Whether the favorite was visible from a separate database scope.</param>
|
||||
public void RecordPublication(bool wasFavoriteVisible)
|
||||
{
|
||||
WasFavoriteVisible = wasFavoriteVisible;
|
||||
Interlocked.Increment(ref _publicationCount);
|
||||
TaskCompletionSource<bool> signal;
|
||||
lock (_signalLock)
|
||||
signal = _publishedSignal;
|
||||
signal.TrySetResult(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until a domain event is published.
|
||||
/// </summary>
|
||||
/// <param name="timeout">The maximum time to wait.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task WaitForPublicationAsync(TimeSpan timeout)
|
||||
{
|
||||
Task signal;
|
||||
lock (_signalLock)
|
||||
signal = _publishedSignal.Task;
|
||||
Task completedTask = await Task.WhenAny(signal, Task.Delay(timeout)).ConfigureAwait(false);
|
||||
if (completedTask != signal)
|
||||
throw new TimeoutException($"A domain event was not published within {timeout}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a completion source that resumes its continuations asynchronously.
|
||||
/// </summary>
|
||||
/// <returns>The created completion source.</returns>
|
||||
private static TaskCompletionSource<bool> CreateSignal()
|
||||
{
|
||||
return new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Controls and observes the domain events handled through the <see cref="ProbingDomainEventsQueue"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class DomainEventsQueueProbe
|
||||
{
|
||||
private readonly Lock _signalLock = new();
|
||||
private readonly ConcurrentDictionary<string, int> _dequeueAttemptsByPath = new();
|
||||
private readonly ConcurrentDictionary<string, TaskCompletionSource<bool>> _dequeueSignalsByPath = new();
|
||||
private TaskCompletionSource<bool> _enqueuedSignal = CreateSignal();
|
||||
private TaskCompletionSource<bool> _enqueueReleaseSignal = CreateSignal();
|
||||
private volatile bool _shouldBlockOnEnqueue;
|
||||
private volatile bool _shouldThrowOnEnqueue;
|
||||
private int _enqueueCount;
|
||||
private int _dequeueCount;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether enqueuing a domain event waits until the test releases it.
|
||||
/// </summary>
|
||||
public bool ShouldBlockOnEnqueue
|
||||
{
|
||||
get { return _shouldBlockOnEnqueue; }
|
||||
set { _shouldBlockOnEnqueue = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether enqueuing a domain event fails after the event is queued.
|
||||
/// </summary>
|
||||
public bool ShouldThrowOnEnqueue
|
||||
{
|
||||
get { return _shouldThrowOnEnqueue; }
|
||||
set { _shouldThrowOnEnqueue = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets how long a blocked enqueuing request waits for the test to release it.
|
||||
/// </summary>
|
||||
public TimeSpan BlockTimeout { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of domain events that were enqueued.
|
||||
/// </summary>
|
||||
public int EnqueueCount => Volatile.Read(ref _enqueueCount);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of domain events that were dequeued for publication.
|
||||
/// </summary>
|
||||
public int DequeueCount => Volatile.Read(ref _dequeueCount);
|
||||
|
||||
/// <summary>
|
||||
/// Clears the recorded counts and signals, so that a test observes only the events handled after the reset.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
ShouldBlockOnEnqueue = false;
|
||||
ShouldThrowOnEnqueue = false;
|
||||
Interlocked.Exchange(ref _enqueueCount, 0);
|
||||
Interlocked.Exchange(ref _dequeueCount, 0);
|
||||
_dequeueAttemptsByPath.Clear();
|
||||
_dequeueSignalsByPath.Clear();
|
||||
lock (_signalLock)
|
||||
{
|
||||
_enqueuedSignal = CreateSignal();
|
||||
_enqueueReleaseSignal = CreateSignal();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that a domain event was enqueued, optionally blocking or failing the enqueuing request.
|
||||
/// </summary>
|
||||
public void RecordEnqueue()
|
||||
{
|
||||
Interlocked.Increment(ref _enqueueCount);
|
||||
TaskCompletionSource<bool> enqueuedSignal;
|
||||
TaskCompletionSource<bool> releaseSignal;
|
||||
lock (_signalLock)
|
||||
{
|
||||
enqueuedSignal = _enqueuedSignal;
|
||||
releaseSignal = _enqueueReleaseSignal;
|
||||
}
|
||||
enqueuedSignal.TrySetResult(true);
|
||||
if (ShouldBlockOnEnqueue && !releaseSignal.Task.Wait(BlockTimeout))
|
||||
throw new TimeoutException("The test did not release the queued domain event in time.");
|
||||
if (ShouldThrowOnEnqueue)
|
||||
throw new InvalidOperationException("The test forces the request to fail after its domain event was queued.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that the queue was asked for a domain event on the request of <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request whose middleware dequeued the queue.</param>
|
||||
/// <param name="wasDequeued">Whether the queue actually contained an event.</param>
|
||||
public void RecordDequeue(string path, bool wasDequeued)
|
||||
{
|
||||
_dequeueAttemptsByPath.AddOrUpdate(path, 1, (_, attemptCount) => attemptCount + 1);
|
||||
TaskCompletionSource<bool> signal = _dequeueSignalsByPath.GetOrAdd(path, _ => CreateSignal());
|
||||
signal.TrySetResult(true);
|
||||
if (wasDequeued)
|
||||
Interlocked.Increment(ref _dequeueCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of dequeue attempts made for the request of <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request.</param>
|
||||
/// <returns>The number of dequeue attempts made for the request.</returns>
|
||||
public int GetDequeueAttemptCount(string path)
|
||||
{
|
||||
return _dequeueAttemptsByPath.TryGetValue(path, out int attemptCount) ? attemptCount : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until a dequeue attempt is made for the request of <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request to observe.</param>
|
||||
/// <param name="timeout">The maximum time to wait.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task WaitForDequeueAsync(string path, TimeSpan timeout)
|
||||
{
|
||||
Task signal = _dequeueSignalsByPath.GetOrAdd(path, _ => CreateSignal()).Task;
|
||||
Task completedTask = await Task.WhenAny(signal, Task.Delay(timeout)).ConfigureAwait(false);
|
||||
if (completedTask != signal)
|
||||
throw new TimeoutException($"The domain events queue was not dequeued for '{path}' within {timeout}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until a domain event is enqueued.
|
||||
/// </summary>
|
||||
/// <param name="timeout">The maximum time to wait.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task WaitForEnqueueAsync(TimeSpan timeout)
|
||||
{
|
||||
Task signal;
|
||||
lock (_signalLock)
|
||||
signal = _enqueuedSignal.Task;
|
||||
Task completedTask = await Task.WhenAny(signal, Task.Delay(timeout)).ConfigureAwait(false);
|
||||
if (completedTask != signal)
|
||||
throw new TimeoutException($"A domain event was not enqueued within {timeout}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases an enqueuing request blocked by <see cref="ShouldBlockOnEnqueue"/>.
|
||||
/// </summary>
|
||||
public void ReleaseEnqueue()
|
||||
{
|
||||
TaskCompletionSource<bool> releaseSignal;
|
||||
lock (_signalLock)
|
||||
releaseSignal = _enqueueReleaseSignal;
|
||||
releaseSignal.TrySetResult(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a completion source that resumes its continuations asynchronously.
|
||||
/// </summary>
|
||||
/// <returns>The created completion source.</returns>
|
||||
private static TaskCompletionSource<bool> CreateSignal()
|
||||
{
|
||||
return new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Authenticated API factory whose database transactions and domain events are observable through probes.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class EventualConsistencyApiFactory : AuthenticatedLuminaApiFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the probe that controls and observes the domain events queue.
|
||||
/// </summary>
|
||||
public DomainEventsQueueProbe QueueProbe { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the probe that observes the published domain events.
|
||||
/// </summary>
|
||||
public DomainEventPublicationProbe PublicationProbe { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the probe that observes the database transaction lifecycle.
|
||||
/// </summary>
|
||||
public TransactionProbe TransactionProbe { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Clears every probe, so that a test observes only the activity started after the reset.
|
||||
/// </summary>
|
||||
public void ResetProbes()
|
||||
{
|
||||
QueueProbe.Reset();
|
||||
PublicationProbe.Reset();
|
||||
TransactionProbe.Reset();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the transaction probe to the database context options.
|
||||
/// </summary>
|
||||
/// <param name="serviceProvider">The service provider used to resolve the options of the database context.</param>
|
||||
/// <param name="options">The options builder of the database context being configured.</param>
|
||||
protected override void ConfigureDbContextOptions(IServiceProvider serviceProvider, DbContextOptionsBuilder options)
|
||||
{
|
||||
base.ConfigureDbContextOptions(serviceProvider, options);
|
||||
// The test services are registered before the shared factory configures the database, so the interceptor is available even from the
|
||||
// throwaway provider the shared factory uses to migrate the database, and a missing registration fails host construction loudly.
|
||||
options.AddInterceptors(serviceProvider.GetRequiredService<TransactionProbeInterceptor>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the web host, replacing the domain events queue and registering the recording event handler.
|
||||
/// </summary>
|
||||
/// <param name="builder">The web host builder to configure.</param>
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
// Registering the test services before the shared factory configures the database makes them available to its migration provider too.
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
services.AddHttpContextAccessor();
|
||||
services.AddSingleton(QueueProbe);
|
||||
services.AddSingleton(PublicationProbe);
|
||||
services.AddSingleton(TransactionProbe);
|
||||
services.AddSingleton<TransactionProbeInterceptor>();
|
||||
services.RemoveAll<IDomainEventsQueue>();
|
||||
services.AddScoped<IDomainEventsQueue, ProbingDomainEventsQueue>();
|
||||
services.AddScoped<IDomainEventHandler<FavoriteAddedDomainEvent>, RecordingFavoriteAddedDomainEventHandler>();
|
||||
});
|
||||
base.ConfigureWebHost(builder);
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Factory for creating a web application for integration tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
{
|
||||
private readonly SqliteConnection _connection;
|
||||
private readonly string _sharedInMemoryConnectionString;
|
||||
private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=";
|
||||
private const string SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX = "Data Source=lumina-tests-{0};Mode=Memory;Cache=Shared";
|
||||
private static byte s_IpClass = 25;
|
||||
|
||||
public static byte IpClass => s_IpClass++;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaApiFactory"/> class.
|
||||
/// </summary>
|
||||
public LuminaApiFactory()
|
||||
{
|
||||
// Each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another;
|
||||
// the shared cache allows each DbContext to open its own pooled connection to the same database, instead of sharing a single connection,
|
||||
// which would otherwise serialize every request on one connection and cause nested transaction errors between requests.
|
||||
_sharedInMemoryConnectionString = string.Format(SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX, Guid.NewGuid());
|
||||
// Keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped.
|
||||
_connection = new SqliteConnection(_sharedInMemoryConnectionString);
|
||||
_connection.Open();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the web host for the integration tests.
|
||||
/// </summary>
|
||||
/// <param name="builder">The web host builder to configure.</param>
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureAppConfiguration((context, config) =>
|
||||
{
|
||||
// Clear all existing configuration sources.
|
||||
config.Sources.Clear();
|
||||
|
||||
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
|
||||
config.AddJsonFile($"appsettings.test.json", optional: true, reloadOnChange: true);
|
||||
config.AddJsonFile("appsettings.shared.json", optional: true, reloadOnChange: true);
|
||||
config.AddJsonFile($"appsettings.shared.test.json", optional: true, reloadOnChange: true);
|
||||
// First add the test values directly.
|
||||
config.AddInMemoryCollection(initialData: new Dictionary<string, string?>
|
||||
{
|
||||
["JwtSettings:SecretKey"] = "test-key-thats-at-least-32-chars-long-for-jwt",
|
||||
["JwtSettings:ExpiryMinutes"] = "60",
|
||||
["JwtSettings:Issuer"] = "test-issuer",
|
||||
["JwtSettings:Audience"] = "test-audience",
|
||||
["CorsSettings:AllowedOrigins:0"] = "http://localhost:5012",
|
||||
["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // Base64 encoded test key.
|
||||
});
|
||||
});
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
// Remove existing DbContext configuration.
|
||||
ServiceDescriptor? descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
|
||||
if (descriptor is not null)
|
||||
services.Remove(descriptor);
|
||||
// Add SQLite DbContext configuration.
|
||||
services.AddDbContext<LuminaDbContext>((serviceProvider, options) =>
|
||||
{
|
||||
options.UseSqlite(_sharedInMemoryConnectionString);
|
||||
options.AddInterceptors(serviceProvider.GetRequiredService<UpdateAuditableEntitiesInterceptor>());
|
||||
ConfigureDbContextOptions(serviceProvider, options);
|
||||
});
|
||||
// Configure JWT authentication for testing.
|
||||
services.PostConfigure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = "test-issuer",
|
||||
ValidAudience = "test-audience",
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("test-key-thats-at-least-32-chars-long-for-jwt"))
|
||||
};
|
||||
});
|
||||
// Build service provider and ensure database is created.
|
||||
ServiceProvider servicePreovider = services.BuildServiceProvider();
|
||||
using (IServiceScope scope = servicePreovider.CreateScope())
|
||||
{
|
||||
IServiceProvider scopedServices = scope.ServiceProvider;
|
||||
LuminaDbContext dbContext = scopedServices.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Database.Migrate();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures additional options of the database context used by the tests.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The hook is invoked every time the options of a database context are built, including once for the throwaway provider that migrates the
|
||||
/// database while the host is configured and once for the final provider of the host. Derived factories that resolve test services from the
|
||||
/// provided <paramref name="serviceProvider"/> must register those services before the shared factory configures the database, and must call
|
||||
/// this base implementation so that options added here are never silently skipped.
|
||||
/// </remarks>
|
||||
/// <param name="serviceProvider">The service provider used to resolve the options of the database context.</param>
|
||||
/// <param name="options">The options builder of the database context being configured.</param>
|
||||
protected virtual void ConfigureDbContextOptions(IServiceProvider serviceProvider, DbContextOptionsBuilder options)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the in-memory SQLite database to its original state.
|
||||
/// </summary>
|
||||
public async Task ResetDatabaseAsync()
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext context = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
context.Books.RemoveRange(context.Books);
|
||||
context.Libraries.RemoveRange(context.Libraries);
|
||||
context.RolePermissions.RemoveRange(context.RolePermissions);
|
||||
context.UserRoles.RemoveRange(context.UserRoles);
|
||||
context.Roles.RemoveRange(context.Roles);
|
||||
context.Permissions.RemoveRange(context.Permissions);
|
||||
context.Users.RemoveRange(context.Users);
|
||||
context.UserPermissions.RemoveRange(context.UserPermissions);
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the connection to the database.
|
||||
/// </summary>
|
||||
public new void Dispose()
|
||||
{
|
||||
_connection.Close();
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Domain events queue that exposes its enqueuing and dequeuing to a <see cref="DomainEventsQueueProbe"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class ProbingDomainEventsQueue : IDomainEventsQueue
|
||||
{
|
||||
private readonly ConcurrentQueue<IDomainEvent> _queue = new();
|
||||
private readonly DomainEventsQueueProbe _probe;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ProbingDomainEventsQueue"/> class.
|
||||
/// </summary>
|
||||
/// <param name="probe">The probe that controls and observes the queue.</param>
|
||||
/// <param name="httpContextAccessor">Injected accessor used to identify the request that dequeues the queue.</param>
|
||||
public ProbingDomainEventsQueue(DomainEventsQueueProbe probe, IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_probe = probe;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a domain event to the queue, before reporting it to the probe.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to enqueue.</param>
|
||||
public void Enqueue(IDomainEvent domainEvent)
|
||||
{
|
||||
_queue.Enqueue(domainEvent);
|
||||
_probe.RecordEnqueue();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to remove and return the domain event at the beginning of the queue, reporting the attempt to the probe.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">When this method returns, contains the domain event removed from the queue, or the default value of <see cref="IDomainEvent"/> if the queue is empty.
|
||||
/// </param>
|
||||
/// <returns><see langword="true"/> if a domain event was successfully dequeued, <see langword="false"/> otherwise.</returns>
|
||||
public bool TryDequeue(out IDomainEvent domainEvent)
|
||||
{
|
||||
bool wasDequeued = _queue.TryDequeue(out domainEvent!);
|
||||
string path = _httpContextAccessor.HttpContext?.Request.Path.Value ?? string.Empty;
|
||||
_probe.RecordDequeue(path, wasDequeued);
|
||||
return wasDequeued;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Domain event handler that records the publication of a <see cref="FavoriteAddedDomainEvent"/>, together with the state visible at publication time.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class RecordingFavoriteAddedDomainEventHandler : IDomainEventHandler<FavoriteAddedDomainEvent>
|
||||
{
|
||||
private readonly IServiceScopeFactory _scopeFactory;
|
||||
private readonly DomainEventPublicationProbe _publicationProbe;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecordingFavoriteAddedDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="scopeFactory">Injected factory used to create a database scope independent from the request scope.</param>
|
||||
/// <param name="publicationProbe">Injected probe that records the published event.</param>
|
||||
public RecordingFavoriteAddedDomainEventHandler(IServiceScopeFactory scopeFactory, DomainEventPublicationProbe publicationProbe)
|
||||
{
|
||||
_scopeFactory = scopeFactory;
|
||||
_publicationProbe = publicationProbe;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records the published <paramref name="domainEvent"/>, checking whether its favorite was already committed.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event being published.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async ValueTask HandleAsync(FavoriteAddedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
// A separate scope and context prove that the row is visible to other connections, which is only true after the request transaction was committed.
|
||||
using IServiceScope scope = _scopeFactory.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
bool wasFavoriteVisible = await dbContext.Favorites
|
||||
.AsNoTracking()
|
||||
.AnyAsync(favorite => favorite.Id == domainEvent.FavoriteId.Value, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
_publicationProbe.RecordPublication(wasFavoriteVisible);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Presentation.Api.Fixtures.Core.Endpoints.FileSystemManagement;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using Xunit;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test to be skipped when the file system does not support the <see cref="FileAttributes.Hidden"/> attribute.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class SkipWhenHiddenAttributeNotSupportedFactAttribute : FactAttribute
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the reason to skip the test. If set, the test will be skipped instead of executed.
|
||||
/// </summary>
|
||||
public override string Skip => FileSystemStructureFixture.HiddenAttributeIsSupported
|
||||
? string.Empty
|
||||
: "The file system does not support the hidden file attribute, so the hidden elements scenario cannot be set up.";
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Helpers shared by the theme integration tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class ThemeTestHelpers
|
||||
{
|
||||
/// <summary>
|
||||
/// Waits until the bundled 'lumina-default' theme has been installed and activated by the theme detection job at startup.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">The shared API factory whose database is polled.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
public static async Task WaitForBundledThemeAsync(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
const int MAX_ATTEMPTS = 100;
|
||||
const int DELAY_MILLISECONDS = 100;
|
||||
|
||||
for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++)
|
||||
{
|
||||
using IServiceScope scope = apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
if (await dbContext.Themes.AnyAsync(theme => theme.ThemeId == "lumina-default" && theme.IsCurrent == true))
|
||||
return;
|
||||
|
||||
await Task.Delay(DELAY_MILLISECONDS);
|
||||
}
|
||||
|
||||
Assert.Fail("The bundled theme 'lumina-default' was not installed and activated within the expected time.");
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Observes the database transactions rolled back on each request through the <see cref="TransactionProbeInterceptor"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class TransactionProbe
|
||||
{
|
||||
private readonly Lock _signalLock = new();
|
||||
private readonly Dictionary<string, TaskCompletionSource<bool>> _rollbackSignalsByPath = [];
|
||||
|
||||
/// <summary>
|
||||
/// Clears the recorded signals, so that a test observes only the rollbacks that happen after the reset.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
lock (_signalLock)
|
||||
_rollbackSignalsByPath.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that the transaction of the request of <paramref name="path"/> was rolled back.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request whose transaction was rolled back.</param>
|
||||
public void RecordRolledBack(string path)
|
||||
{
|
||||
TaskCompletionSource<bool> signal;
|
||||
lock (_signalLock)
|
||||
{
|
||||
if (!_rollbackSignalsByPath.TryGetValue(path, out signal!))
|
||||
{
|
||||
signal = CreateSignal();
|
||||
_rollbackSignalsByPath[path] = signal;
|
||||
}
|
||||
}
|
||||
signal.TrySetResult(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until the transaction of the request of <paramref name="path"/> is rolled back.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request to observe.</param>
|
||||
/// <param name="timeout">The maximum time to wait.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task WaitForRollbackAsync(string path, TimeSpan timeout)
|
||||
{
|
||||
Task signal;
|
||||
lock (_signalLock)
|
||||
{
|
||||
if (!_rollbackSignalsByPath.TryGetValue(path, out TaskCompletionSource<bool>? signalSource))
|
||||
{
|
||||
signalSource = CreateSignal();
|
||||
_rollbackSignalsByPath[path] = signalSource;
|
||||
}
|
||||
signal = signalSource.Task;
|
||||
}
|
||||
Task completedTask = await Task.WhenAny(signal, Task.Delay(timeout)).ConfigureAwait(false);
|
||||
if (completedTask != signal)
|
||||
throw new TimeoutException($"The transaction of '{path}' was not rolled back within {timeout}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a completion source that resumes its continuations asynchronously.
|
||||
/// </summary>
|
||||
/// <returns>The created completion source.</returns>
|
||||
private static TaskCompletionSource<bool> CreateSignal()
|
||||
{
|
||||
return new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using System.Data.Common;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Database transaction interceptor that reports the rolled back transactions to a <see cref="TransactionProbe"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class TransactionProbeInterceptor : DbTransactionInterceptor
|
||||
{
|
||||
private readonly TransactionProbe _probe;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TransactionProbeInterceptor"/> class.
|
||||
/// </summary>
|
||||
/// <param name="probe">The probe that records the rolled back transactions.</param>
|
||||
/// <param name="httpContextAccessor">Injected accessor used to identify the request whose transaction was rolled back.</param>
|
||||
public TransactionProbeInterceptor(TransactionProbe probe, IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_probe = probe;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that a transaction was rolled back.
|
||||
/// </summary>
|
||||
/// <param name="transaction">The rolled back transaction.</param>
|
||||
/// <param name="eventData">The data of the transaction event.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A completed task.</returns>
|
||||
public override Task TransactionRolledBackAsync(DbTransaction transaction, TransactionEndEventData eventData, CancellationToken cancellationToken = default)
|
||||
{
|
||||
RecordRolledBack();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that a transaction was rolled back synchronously.
|
||||
/// </summary>
|
||||
/// <param name="transaction">The rolled back transaction.</param>
|
||||
/// <param name="eventData">The data of the transaction event.</param>
|
||||
public override void TransactionRolledBack(DbTransaction transaction, TransactionEndEventData eventData)
|
||||
{
|
||||
RecordRolledBack();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports the rolled back transaction of the current request to the probe.
|
||||
/// </summary>
|
||||
private void RecordRolledBack()
|
||||
{
|
||||
string path = _httpContextAccessor.HttpContext?.Request.Path.Value ?? string.Empty;
|
||||
_probe.RecordRolledBack(path);
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
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.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Admin.Authorization.Permissions;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPermissionsEndpointTests : 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="GetPermissionsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPermissionsEndpointTests(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 GetPermissions_WhenCalledWithValidRequest_ShouldReturnPermissions()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/permissions");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
IEnumerable<PermissionResponse>? result = JsonSerializer.Deserialize<IEnumerable<PermissionResponse>>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.NotEmpty(result);
|
||||
foreach (PermissionResponse permission in result!)
|
||||
{
|
||||
Assert.NotEqual(Guid.Empty, permission.Id);
|
||||
Assert.NotEqual(AuthorizationPermission.None, permission.PermissionName);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPermissions_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Act
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync(); // Authenticated user, but not admin.
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/permissions");
|
||||
|
||||
// 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/auth/permissions", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPermissions_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync("/api/v1/auth/permissions", cts.Token);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// Clear junction tables first.
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// Then clear main tables.
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.DTO.Authentication;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly AddRoleRequestFixture _addRoleRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddRoleEndpointTests(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 AddRole_WhenCalledWithValidRequest_ShouldCreateRole()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
PermissionEntity[] permissions = [.. dbContext.Permissions.Take(2)];
|
||||
|
||||
AddRoleRequest request = _addRoleRequestFixture.Create(
|
||||
roleName: "Editor",
|
||||
permissions: permissions.Select(p => p.Id).ToList()
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/roles", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
RolePermissionsResponse? result = JsonSerializer.Deserialize<RolePermissionsResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Editor", result!.Role.RoleName);
|
||||
Assert.Equal(2, result.Permissions.Length);
|
||||
foreach (PermissionDto permission in result.Permissions)
|
||||
{
|
||||
Assert.NotEqual(Guid.Empty, permission.Id);
|
||||
Assert.NotEqual(AuthorizationPermission.None, permission.PermissionName);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddRole_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
AddRoleRequest request = _addRoleRequestFixture.Create(
|
||||
roleName: "Editor",
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/roles", 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/auth/roles", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddRole_WhenRoleAlreadyExists_ShouldReturnConflict()
|
||||
{
|
||||
// Arrange
|
||||
AddRoleRequest request = _addRoleRequestFixture.Create(
|
||||
roleName: "Admin",
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/roles", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Conflict, 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.Status409Conflict, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.10", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Conflict", problemDetails["title"].GetString());
|
||||
Assert.Equal("RoleAlreadyExists", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/roles", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddRole_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
AddRoleRequest request = _addRoleRequestFixture.Create(
|
||||
roleName: "Editor",
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.PostAsJsonAsync("/api/v1/auth/roles", request, cts.Token);
|
||||
});
|
||||
}
|
||||
|
||||
/// <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<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// Then clear main tables.
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteRoleEndpointTests(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 DeleteRole_WhenCalledWithValidRequest_ShouldDeleteRole()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// Create a test role first.
|
||||
RoleEntity role = _roleEntityFixture.Create(roleName: "TestRole");
|
||||
dbContext.Roles.Add(role);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/auth/roles/{role.Id}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
|
||||
|
||||
// Verify role was deleted.
|
||||
RoleEntity? deletedRole = await dbContext.Roles.FirstOrDefaultAsync(r => r.Id == role.Id);
|
||||
Assert.Null(deletedRole);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteRole_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
Guid roleId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/auth/roles/{roleId}");
|
||||
|
||||
// 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/auth/roles/{roleId}", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteRole_WhenTryingToDeleteAdminRole_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
RoleEntity? adminRole = dbContext.Roles.FirstOrDefault(r => r.RoleName == "Admin");
|
||||
Assert.NotNull(adminRole);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/auth/roles/{adminRole!.Id}");
|
||||
|
||||
// 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("AdminRoleCannotBeDeleted", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/auth/roles/{adminRole!.Id}", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteRole_WhenRoleDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentRoleId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/auth/roles/{nonExistentRoleId}");
|
||||
|
||||
// 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("RoleNotFound", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/auth/roles/{nonExistentRoleId}", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteRole_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
Guid roleId = Guid.NewGuid();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.DeleteAsync($"/api/v1/auth/roles/{roleId}", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <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<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// Then clear main tables.
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.DTO.Authentication;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetRolePermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRolePermissionsEndpointTests : 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="GetRolePermissionsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetRolePermissionsEndpointTests(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 GetRolePermissions_WhenCalledWithValidRequest_ShouldReturnRolePermissions()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
RoleEntity? role = dbContext.Roles.FirstOrDefault();
|
||||
Assert.NotNull(role);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/roles/{role!.Id}/permissions");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
RolePermissionsResponse? result = JsonSerializer.Deserialize<RolePermissionsResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(role.Id, result!.Role.Id);
|
||||
Assert.Equal("Admin", result.Role.RoleName);
|
||||
Assert.NotEmpty(result.Permissions);
|
||||
foreach (PermissionDto permission in result.Permissions)
|
||||
{
|
||||
Assert.NotEqual(Guid.Empty, permission.Id);
|
||||
Assert.NotEqual(AuthorizationPermission.None, permission.PermissionName);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRolePermissions_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync(); // Authenticated user, but not admin.
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
RoleEntity? role = dbContext.Roles.FirstOrDefault();
|
||||
Assert.NotNull(role);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/roles/{role!.Id}/permissions");
|
||||
|
||||
// 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/auth/roles/{role.Id}/permissions", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRolePermissions_WhenCalledWithInvalidRoleId_ShouldReturnNotFound()
|
||||
{
|
||||
// Act
|
||||
Guid invalidRoleId = Guid.NewGuid();
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/roles/{invalidRoleId}/permissions");
|
||||
|
||||
// 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("RoleNotFound", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/auth/roles/{invalidRoleId}/permissions", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRolePermissions_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
RoleEntity? role = dbContext.Roles.FirstOrDefault();
|
||||
Assert.NotNull(role);
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/auth/roles/{role!.Id}/permissions", cts.Token);
|
||||
});
|
||||
}
|
||||
|
||||
/// <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<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// Then clear main tables.
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetRolesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRolesEndpointTests : 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="GetRolesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetRolesEndpointTests(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 GetRoles_WhenCalledWithValidRequest_ShouldReturnRoles()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/roles");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
IEnumerable<RoleResponse>? result = JsonSerializer.Deserialize<IEnumerable<RoleResponse>>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.NotEmpty(result);
|
||||
Assert.Contains(result, role =>
|
||||
role.Id != Guid.Empty &&
|
||||
role.RoleName == "Admin"
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRoles_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/roles");
|
||||
|
||||
// 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/auth/roles", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRoles_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync("/api/v1/auth/roles", cts.Token);
|
||||
});
|
||||
}
|
||||
|
||||
/// <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<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// Then clear main tables.
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Contracts.DTO.Authentication;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly UpdateRoleRequestFixture _updateRoleRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateRoleEndpointTests(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 UpdateRole_WhenCalledWithValidRequest_ShouldUpdateRole()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
RoleEntity role = _roleEntityFixture.Create(roleName: "TestRole");
|
||||
dbContext.Roles.Add(role);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
PermissionEntity[] permissions = [.. dbContext.Permissions.Take(2)];
|
||||
UpdateRoleRequest request = _updateRoleRequestFixture.Create(
|
||||
roleId: role.Id,
|
||||
roleName: "UpdatedRole",
|
||||
permissions: [.. permissions.Select(p => p.Id)]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/roles", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
RolePermissionsResponse? result = JsonSerializer.Deserialize<RolePermissionsResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(role.Id, result!.Role.Id);
|
||||
Assert.Equal("UpdatedRole", result.Role.RoleName);
|
||||
Assert.Equal(2, result.Permissions.Length);
|
||||
foreach (PermissionDto permission in result.Permissions)
|
||||
{
|
||||
Assert.NotEqual(Guid.Empty, permission.Id);
|
||||
Assert.NotEqual(AuthorizationPermission.None, permission.PermissionName);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateRole_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
UpdateRoleRequest request = _updateRoleRequestFixture.Create(
|
||||
roleId: Guid.NewGuid(),
|
||||
roleName: "UpdatedRole",
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/roles", 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/auth/roles", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateRole_WhenRoleDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentRoleId = Guid.NewGuid();
|
||||
UpdateRoleRequest request = _updateRoleRequestFixture.Create(
|
||||
roleId: nonExistentRoleId,
|
||||
roleName: "UpdatedRole",
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/roles", 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("RoleNotFound", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/roles", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateRole_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
UpdateRoleRequest request = _updateRoleRequestFixture.Create(
|
||||
roleId: Guid.NewGuid(),
|
||||
roleName: "UpdatedRole",
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.PutAsJsonAsync($"/api/v1/auth/roles", request, cts.Token);
|
||||
});
|
||||
}
|
||||
|
||||
/// <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<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// Then clear main tables.
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+568
@@ -0,0 +1,568 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.AddFavorite;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Favorites.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private const string PATH = "/api/v1/users/me/favorites";
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededMediaContributorIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddFavoriteEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist)] // A favorite of an artist of a music library.
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum)] // A favorite of an album of a music library.
|
||||
[InlineData(FavoriteMediaKind.MusicTrack)] // A favorite of a track of a music library.
|
||||
[InlineData(FavoriteMediaKind.Book)] // A favorite of a book of a book library.
|
||||
public async Task AddFavorite_WhenMediaItemExists_ShouldReturnTheFavoriteAndStoreOneRowForTheCaller(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Dictionary<FavoriteMediaKind, Guid> mediaItemIds = await SeedCatalogueAsync(userId);
|
||||
Guid mediaItemId = mediaItemIds[mediaKind];
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = mediaKind.ToString(), mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
FavoriteResponse? favorite = await DeserializeAsync<FavoriteResponse>(response);
|
||||
Assert.NotNull(favorite);
|
||||
Assert.NotEqual(Guid.Empty, favorite!.Id);
|
||||
Assert.Equal(mediaKind, favorite.MediaKind);
|
||||
Assert.Equal(mediaItemId, favorite.MediaItemId);
|
||||
Assert.NotEqual(default, favorite.FavoritedOnUtc);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<FavoriteEntity> rows = await dbContext.Favorites
|
||||
.AsNoTracking()
|
||||
.Where(candidate => candidate.UserId == userId && candidate.MediaKind == mediaKind && candidate.MediaItemId == mediaItemId)
|
||||
.ToListAsync();
|
||||
FavoriteEntity row = Assert.Single(rows);
|
||||
Assert.Equal(favorite.Id, row.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenTheSameItemIsAddedTwice_ShouldReturnTheSameFavoriteAndKeepASingleRow()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = await SeedTrackAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = mediaItemId });
|
||||
HttpResponseMessage secondResponse = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
|
||||
FavoriteResponse? firstFavorite = await DeserializeAsync<FavoriteResponse>(firstResponse);
|
||||
FavoriteResponse? secondFavorite = await DeserializeAsync<FavoriteResponse>(secondResponse);
|
||||
Assert.NotNull(firstFavorite);
|
||||
Assert.NotNull(secondFavorite);
|
||||
Assert.Equal(firstFavorite!.Id, secondFavorite!.Id);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.Favorites.CountAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist, "ArtistNotFound")] // A missing artist is reported with the artist detail.
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum, "AlbumNotFound")] // A missing album is reported with the album detail.
|
||||
[InlineData(FavoriteMediaKind.MusicTrack, "TrackNotFound")] // A missing track is reported with the track detail.
|
||||
[InlineData(FavoriteMediaKind.Book, "BookNotFound")] // A missing book is reported with the book detail.
|
||||
public async Task AddFavorite_WhenMediaItemDoesNotExist_ShouldReturnNotFoundWithTheKindSpecificDetail(FavoriteMediaKind mediaKind, string expectedDetail)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = mediaKind.ToString(), mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, PATH);
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.Video)] // Video libraries are not catalogued yet.
|
||||
[InlineData(FavoriteMediaKind.Photo)] // Photo libraries are not catalogued yet.
|
||||
public async Task AddFavorite_WhenMediaKindIsPlanned_ShouldReturnValidationProblem(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = mediaKind.ToString(), mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsNotSupported");
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenMediaKindIsMissing_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = (string?)null, mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = nameof(FavoriteMediaKind.None), mediaItemId });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenMediaItemIdIsEmpty_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = Guid.Empty });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdCannotBeEmpty");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == Guid.Empty));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenTheBodyIsEmpty_ShouldReturnBothValidationProblems()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsInvalid", "FavoriteMediaItemIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenMediaItemBelongsToAnotherUsersLibrary_ShouldReturnTheSameNotFoundAsAMissingItem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherTrackId = await SeedTrackAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = otherTrackId });
|
||||
|
||||
// Assert
|
||||
// The response is indistinguishable from the one of a missing item, so it cannot be used to probe another user's library.
|
||||
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", PATH);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.MediaItemId == otherTrackId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds one artist, one album, one track and one book owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the seeded libraries.</param>
|
||||
/// <returns>The Ids of the seeded media items, keyed by their kind.</returns>
|
||||
private async Task<Dictionary<FavoriteMediaKind, Guid>> SeedCatalogueAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Favorite Artist");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Favorite Album");
|
||||
Guid trackId = await SeedTrackAsync(musicLibraryId, albumId, "Favorite Track");
|
||||
await SeedAlbumCoverAsync(albumId, "favorite-cover.jpg");
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook);
|
||||
Guid bookId = await SeedBookAsync(bookLibraryId, "Favorite Book", "Favorite Author");
|
||||
|
||||
return new Dictionary<FavoriteMediaKind, Guid>
|
||||
{
|
||||
[FavoriteMediaKind.MusicArtist] = artistId,
|
||||
[FavoriteMediaKind.MusicAlbum] = albumId,
|
||||
[FavoriteMediaKind.MusicTrack] = trackId,
|
||||
[FavoriteMediaKind.Book] = bookId
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/> with one track, and returns the Id of that track.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the seeded library.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Single Artist");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Single Album");
|
||||
return await SeedTrackAsync(musicLibraryId, albumId, "Single Track");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library of the given type owned by <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the media library.</param>
|
||||
/// <param name="libraryType">The type of the media library.</param>
|
||||
/// <returns>The Id of the seeded media library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId, userId: userId, title: $"Library-{Guid.NewGuid():N}", libraryType: libraryType, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(
|
||||
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Albums.Add(album);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the cover artwork of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="albumId">The Id of the album that owns the artwork.</param>
|
||||
/// <param name="fileName">The file name of the stored cover.</param>
|
||||
private async Task SeedAlbumCoverAsync(Guid albumId, string fileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album,
|
||||
ownerId: albumId,
|
||||
artworkType: ArtworkType.Cover,
|
||||
ordinal: 0,
|
||||
fileName: fileName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of the library identified by <paramref name="libraryId"/>, with one author.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the book belongs to.</param>
|
||||
/// <param name="title">The title of the book.</param>
|
||||
/// <param name="authorName">The display name of the author of the book.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string title, string authorName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid contributorId = Guid.NewGuid();
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(id: bookId, libraryId: libraryId, title: title, includeMetadata: false));
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId, displayName: authorName));
|
||||
dbContext.BookContributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId, role: MediaContributorRole.Author));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededMediaContributorIds.Add(contributorId);
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </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();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
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(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a problem details document with the expected status, title and detail.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedStatus">The expected HTTP status.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private static async Task AssertProblemAsync(HttpResponseMessage response, HttpStatusCode expectedStatus, string expectedTitle, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(expectedStatus, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)expectedStatus, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a validation problem details document carrying exactly the expected error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present, in order.</param>
|
||||
private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(422, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Equal(expectedErrorCodes, errors!["General.Validation"]);
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||
List<Guid> albumIds = await dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)).Select(album => album.Id).ToListAsync();
|
||||
List<Guid> bookIds = await dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)).Select(book => book.Id).ToListAsync();
|
||||
dbContext.MusicArtwork.RemoveRange(dbContext.MusicArtwork.Where(artwork => albumIds.Contains(artwork.OwnerId)));
|
||||
dbContext.BookContributors.RemoveRange(dbContext.BookContributors.Where(contributor => bookIds.Contains(contributor.BookId)));
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId)));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId)));
|
||||
dbContext.Books.RemoveRange(dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||
dbContext.MediaContributors.RemoveRange(dbContext.MediaContributors.Where(contributor => _seededMediaContributorIds.Contains(contributor.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFavoriteStatusEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private const string PATH = "/api/v1/users/me/favorites/status";
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededFavoriteIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetFavoriteStatusEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenSomeOfTheRequestedItemsAreFavorites_ShouldReturnExactlyThoseIdsOfTheCallerAndKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid favoritedTrackId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid notFavoritedId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, favoritedTrackId);
|
||||
// The book is a favorite of the caller, but of another kind, so it must not be reported for a MusicTrack query.
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.Book, bookId);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserTrackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(otherUserId, FavoriteMediaKind.MusicTrack, otherUserTrackId);
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&mediaItemIds={favoritedTrackId}&mediaItemIds={bookId}&mediaItemIds={otherUserTrackId}&mediaItemIds={notFavoritedId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
FavoriteStatusResponse? status = await DeserializeAsync<FavoriteStatusResponse>(response);
|
||||
Assert.NotNull(status);
|
||||
Guid favoritedId = Assert.Single(status!.FavoritedMediaItemIds);
|
||||
Assert.Equal(favoritedTrackId, favoritedId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTheSameIdIsRequestedTwice_ShouldReturnItOnce()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid favoritedTrackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, favoritedTrackId);
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&mediaItemIds={favoritedTrackId}&mediaItemIds={favoritedTrackId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
FavoriteStatusResponse? status = await DeserializeAsync<FavoriteStatusResponse>(response);
|
||||
Assert.NotNull(status);
|
||||
Guid favoritedId = Assert.Single(status!.FavoritedMediaItemIds);
|
||||
Assert.Equal(favoritedTrackId, favoritedId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenOneHundredIdsAreRequested_ShouldAcceptThem()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> requestedIds = [.. Enumerable.Range(0, 100).Select(_ => Guid.NewGuid())];
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&{string.Join("&", requestedIds.Select(requestedId => $"mediaItemIds={requestedId}"))}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
FavoriteStatusResponse? status = await DeserializeAsync<FavoriteStatusResponse>(response);
|
||||
Assert.NotNull(status);
|
||||
Assert.Empty(status!.FavoritedMediaItemIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenMoreThanOneHundredIdsAreRequested_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> requestedIds = [.. Enumerable.Range(0, 101).Select(_ => Guid.NewGuid())];
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&{string.Join("&", requestedIds.Select(requestedId => $"mediaItemIds={requestedId}"))}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdsExceedMaximumCount");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenNoMediaItemIdsAreProvided_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdsCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTheEmptyGuidIsRequested_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack&mediaItemIds={Guid.Empty}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTheMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid favoritedTrackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, favoritedTrackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind={nameof(FavoriteMediaKind.None)}&mediaItemIds={favoritedTrackId}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsInvalid");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(favoritedTrackId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTheMediaKindIsNotAMemberName_ShouldNotReturnAnyId()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid favoritedTrackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, favoritedTrackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=NotAMediaKind&mediaItemIds={favoritedTrackId}");
|
||||
|
||||
// Assert
|
||||
// The request binds the media kind as an enumeration, so an unparseable value is answered by the generic exception handler
|
||||
// with the sanitized problem before the handler runs, and no favorite status is disclosed.
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(favoritedTrackId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <returns>The Id of the seeded favorite.</returns>
|
||||
private async Task<Guid> SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid favoriteId = Guid.NewGuid();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
id: favoriteId,
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededFavoriteIds.Add(favoriteId);
|
||||
return favoriteId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </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();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
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(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a validation problem details document carrying the expected error code.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCode">The expected validation error code.</param>
|
||||
private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(422, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Favorites.RemoveRange(dbContext.Favorites.Where(favorite => _seededFavoriteIds.Contains(favorite.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+638
@@ -0,0 +1,638 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavorites;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Favorites.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFavoritesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private const string PATH = "/api/v1/users/me/favorites";
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededMediaContributorIds = [];
|
||||
private readonly List<Guid> _seededFavoriteIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetFavoritesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenFavoritesOfSeveralKindsExist_ShouldReturnOnlyTheCallersFavorites()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Caller Artist");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Caller Album");
|
||||
Guid trackId = await SeedTrackAsync(musicLibraryId, albumId, "Caller Track");
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook);
|
||||
Guid bookId = await SeedBookAsync(bookLibraryId, "Caller Book", "Caller Author");
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.Book, bookId);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherTrackId = await SeedTrackAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
Assert.Equal(2, favorites!.Count);
|
||||
Assert.Equal(2, favorites.Data.Count);
|
||||
Assert.Contains(favorites.Data, favorite => favorite.MediaKind == FavoriteMediaKind.MusicTrack && favorite.MediaItemId == trackId);
|
||||
Assert.Contains(favorites.Data, favorite => favorite.MediaKind == FavoriteMediaKind.Book && favorite.MediaItemId == bookId);
|
||||
Assert.DoesNotContain(favorites.Data, favorite => favorite.MediaItemId == otherTrackId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenNoPaginationIsRequested_ShouldReturnEveryFavoriteInOnePageFromTheMostRecent()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstFavoriteId = await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, Guid.NewGuid());
|
||||
Guid secondFavoriteId = await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, Guid.NewGuid());
|
||||
Guid thirdFavoriteId = await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, Guid.NewGuid());
|
||||
DateTime now = DateTime.UtcNow;
|
||||
// The auditing interceptor stamps the creation time of an added row, so the favoriting order is restored after the insert.
|
||||
await SetCreatedOnUtcAsync(firstFavoriteId, now.AddMinutes(-30));
|
||||
await SetCreatedOnUtcAsync(secondFavoriteId, now.AddMinutes(-20));
|
||||
await SetCreatedOnUtcAsync(thirdFavoriteId, now.AddMinutes(-10));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
Assert.Equal(1, favorites!.CurrentPage);
|
||||
Assert.Equal(3, favorites.PerPage);
|
||||
Assert.Equal(3, favorites.Count);
|
||||
Assert.Equal(1, favorites.NumberOfPages);
|
||||
FavoriteEntity thirdFavorite = await GetFavoriteAsync(thirdFavoriteId);
|
||||
FavoriteEntity secondFavorite = await GetFavoriteAsync(secondFavoriteId);
|
||||
FavoriteEntity firstFavorite = await GetFavoriteAsync(firstFavoriteId);
|
||||
Assert.Equal(
|
||||
new[] { thirdFavorite.MediaItemId, secondFavorite.MediaItemId, firstFavorite.MediaItemId },
|
||||
favorites.Data.Select(favorite => favorite.MediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenAPageIsRequested_ShouldReturnDisjointRowsAndThePaginationMetadata()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
for (int index = 0; index < 5; index++)
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, Guid.NewGuid());
|
||||
string firstPageUrl = $"{PATH}?currentPage=1&perPage=2";
|
||||
string secondPageUrl = $"{PATH}?currentPage=2&perPage=2";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstPageResponse = await _client.GetAsync(firstPageUrl);
|
||||
HttpResponseMessage secondPageResponse = await _client.GetAsync(secondPageUrl);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, firstPageResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, secondPageResponse.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? firstPage = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(firstPageResponse);
|
||||
PaginatedResponse<FavoriteItemResponse>? secondPage = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(secondPageResponse);
|
||||
Assert.NotNull(firstPage);
|
||||
Assert.NotNull(secondPage);
|
||||
Assert.Equal(1, firstPage!.CurrentPage);
|
||||
Assert.Equal(2, firstPage.PerPage);
|
||||
Assert.Equal(5, firstPage.Count);
|
||||
Assert.Equal(3, firstPage.NumberOfPages);
|
||||
Assert.Equal(2, firstPage.Data.Count);
|
||||
Assert.Equal(2, secondPage!.CurrentPage);
|
||||
Assert.Equal(2, secondPage.PerPage);
|
||||
Assert.Equal(5, secondPage.Count);
|
||||
Assert.Equal(3, secondPage.NumberOfPages);
|
||||
Assert.Equal(2, secondPage.Data.Count);
|
||||
Assert.Empty(firstPage.Data.Select(favorite => favorite.MediaItemId).Intersect(secondPage.Data.Select(favorite => favorite.MediaItemId)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenAMediaKindIsRequested_ShouldReturnOnlyThatKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.Book, bookId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.Equal(FavoriteMediaKind.MusicTrack, favorite.MediaKind);
|
||||
Assert.Equal(trackId, favorite.MediaItemId);
|
||||
Assert.Equal(1, favorites.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenAFavoritedTrackExists_ShouldReturnTheAlbumAsTheCollectionAndTheArtistAsTheCreator()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "A Night at the Opera");
|
||||
Guid trackId = await SeedTrackAsync(musicLibraryId, albumId, "Bohemian Rhapsody");
|
||||
await SeedAlbumCoverAsync(albumId, "a-night-at-the-opera-cover.jpg");
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.True(favorite.IsAvailable);
|
||||
Assert.Equal(musicLibraryId, favorite.LibraryId);
|
||||
Assert.Equal("Bohemian Rhapsody", favorite.Title);
|
||||
Assert.Equal(albumId, favorite.CollectionId);
|
||||
Assert.Equal("A Night at the Opera", favorite.CollectionTitle);
|
||||
Assert.Equal(artistId, favorite.CreatorId);
|
||||
Assert.Equal("Queen", favorite.CreatorName);
|
||||
Assert.Equal("a-night-at-the-opera-cover.jpg", favorite.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenAFavoritedBookExists_ShouldReturnTheAuthorAsTheCreatorAndNoCollection()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook);
|
||||
Guid bookId = await SeedBookAsync(bookLibraryId, "The Fellowship of the Ring", "J. R. R. Tolkien");
|
||||
Guid authorId = _seededMediaContributorIds[^1];
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.Book, bookId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=Book");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.True(favorite.IsAvailable);
|
||||
Assert.Equal(bookLibraryId, favorite.LibraryId);
|
||||
Assert.Equal("The Fellowship of the Ring", favorite.Title);
|
||||
Assert.Equal(Guid.Empty, favorite.CollectionId);
|
||||
Assert.Equal(string.Empty, favorite.CollectionTitle);
|
||||
Assert.Equal(authorId, favorite.CreatorId);
|
||||
Assert.Equal("J. R. R. Tolkien", favorite.CreatorName);
|
||||
Assert.Null(favorite.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenTheFavoritedItemWasDeleted_ShouldReturnTheRowAsUnavailableWithEmptyDisplayFields()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid deletedItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, deletedItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.Equal(deletedItemId, favorite.MediaItemId);
|
||||
Assert.False(favorite.IsAvailable);
|
||||
Assert.Equal(Guid.Empty, favorite.LibraryId);
|
||||
Assert.Equal(string.Empty, favorite.Title);
|
||||
Assert.Equal(Guid.Empty, favorite.CollectionId);
|
||||
Assert.Equal(string.Empty, favorite.CollectionTitle);
|
||||
Assert.Equal(Guid.Empty, favorite.CreatorId);
|
||||
Assert.Equal(string.Empty, favorite.CreatorName);
|
||||
Assert.Null(favorite.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenTheFavoritedItemBelongsToAnInaccessibleLibrary_ShouldStillReturnTheRowAsUnavailable()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherMusicLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music);
|
||||
Guid otherArtistId = await SeedArtistAsync(otherMusicLibraryId, "Other Artist");
|
||||
Guid otherAlbumId = await SeedAlbumAsync(otherMusicLibraryId, otherArtistId, "Other Album");
|
||||
Guid otherTrackId = await SeedTrackAsync(otherMusicLibraryId, otherAlbumId, "Other Track");
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, otherTrackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.Equal(otherTrackId, favorite.MediaItemId);
|
||||
Assert.False(favorite.IsAvailable);
|
||||
Assert.Equal(Guid.Empty, favorite.LibraryId);
|
||||
Assert.Equal(string.Empty, favorite.Title);
|
||||
Assert.Equal(Guid.Empty, favorite.CollectionId);
|
||||
Assert.Equal(Guid.Empty, favorite.CreatorId);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Other Track", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Other Artist", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Other Album", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenTheMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind={nameof(FavoriteMediaKind.None)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal(422, problemDetails.RootElement.GetProperty("status").GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("FavoriteMediaKindIsInvalid", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(trackId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenTheMediaKindIsNotAMemberName_ShouldNotReturnAnyFavorite()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=NotAMediaKind");
|
||||
|
||||
// Assert
|
||||
// The request binds the media kind as an enumeration, so an unparseable value is answered by the generic exception handler
|
||||
// with the sanitized problem before the handler runs, and no favorite is disclosed.
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(trackId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library of the given type owned by <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the media library.</param>
|
||||
/// <param name="libraryType">The type of the media library.</param>
|
||||
/// <returns>The Id of the seeded media library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId, userId: userId, title: $"Library-{Guid.NewGuid():N}", libraryType: libraryType, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(
|
||||
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Albums.Add(album);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/> with one track, and returns the Id of that track.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the seeded library.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Other Artist");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Other Album");
|
||||
return await SeedTrackAsync(musicLibraryId, albumId, "Other Track");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the cover artwork of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="albumId">The Id of the album that owns the artwork.</param>
|
||||
/// <param name="fileName">The file name of the stored cover.</param>
|
||||
private async Task SeedAlbumCoverAsync(Guid albumId, string fileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album,
|
||||
ownerId: albumId,
|
||||
artworkType: ArtworkType.Cover,
|
||||
ordinal: 0,
|
||||
fileName: fileName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of the library identified by <paramref name="libraryId"/>, with one author.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the book belongs to.</param>
|
||||
/// <param name="title">The title of the book.</param>
|
||||
/// <param name="authorName">The display name of the author of the book.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string title, string authorName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid contributorId = Guid.NewGuid();
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(id: bookId, libraryId: libraryId, title: title, includeMetadata: false));
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId, displayName: authorName));
|
||||
dbContext.BookContributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId, role: MediaContributorRole.Author));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededMediaContributorIds.Add(contributorId);
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <returns>The Id of the seeded favorite.</returns>
|
||||
private async Task<Guid> SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid favoriteId = Guid.NewGuid();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
id: favoriteId,
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededFavoriteIds.Add(favoriteId);
|
||||
return favoriteId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Overrides the creation time of an already stored favorite, so the favoriting order of the test is deterministic.
|
||||
/// </summary>
|
||||
/// <param name="favoriteId">The Id of the favorite to update.</param>
|
||||
/// <param name="createdOnUtc">The creation time to store.</param>
|
||||
private async Task SetCreatedOnUtcAsync(Guid favoriteId, DateTime createdOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
await dbContext.Favorites
|
||||
.Where(favorite => favorite.Id == favoriteId)
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(favorite => favorite.CreatedOnUtc, createdOnUtc));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads an already stored favorite.
|
||||
/// </summary>
|
||||
/// <param name="favoriteId">The Id of the favorite to read.</param>
|
||||
/// <returns>The stored favorite.</returns>
|
||||
private async Task<FavoriteEntity> GetFavoriteAsync(Guid favoriteId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
return await dbContext.Favorites.AsNoTracking().FirstAsync(favorite => favorite.Id == favoriteId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </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();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
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(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||
List<Guid> albumIds = await dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)).Select(album => album.Id).ToListAsync();
|
||||
List<Guid> bookIds = await dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)).Select(book => book.Id).ToListAsync();
|
||||
dbContext.Favorites.RemoveRange(dbContext.Favorites.Where(favorite => _seededFavoriteIds.Contains(favorite.Id)));
|
||||
dbContext.MusicArtwork.RemoveRange(dbContext.MusicArtwork.Where(artwork => albumIds.Contains(artwork.OwnerId)));
|
||||
dbContext.BookContributors.RemoveRange(dbContext.BookContributors.Where(contributor => bookIds.Contains(contributor.BookId)));
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId)));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId)));
|
||||
dbContext.Books.RemoveRange(dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||
dbContext.MediaContributors.RemoveRange(dbContext.MediaContributors.Where(contributor => _seededMediaContributorIds.Contains(contributor.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RemoveFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededFavoriteIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RemoveFavoriteEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheFavoriteExists_ShouldDeleteTheCallersRowAndReturnOk()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/MusicTrack/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheFavoriteDoesNotExist_ShouldReturnOkAndChangeNothing()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid otherMediaItemId = Guid.NewGuid();
|
||||
Guid seededFavoriteId = await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, otherMediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/MusicTrack/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.Favorites.CountAsync(favorite => favorite.UserId == userId));
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.Id == seededFavoriteId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenAnotherUserFavoritedTheSameItem_ShouldRemoveOnlyTheCallersRow()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherFavoriteId = await SeedFavoriteAsync(otherUserId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/MusicTrack/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId));
|
||||
FavoriteEntity otherFavorite = await dbContext.Favorites.AsNoTracking().FirstAsync(favorite => favorite.Id == otherFavoriteId);
|
||||
Assert.Equal(otherUserId, otherFavorite.UserId);
|
||||
Assert.Equal(mediaItemId, otherFavorite.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/{nameof(FavoriteMediaKind.None)}/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "FavoriteMediaKindIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheMediaKindIsNotAName_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/NotAMediaKind/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "FavoriteMediaKindIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheMediaItemIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/favorites/MusicTrack/not-a-guid");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "FavoriteMediaItemIdCannotBeEmpty");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenBothRouteValuesAreInvalid_ShouldReturnBothValidationProblems()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/NotAMediaKind/{Guid.Empty}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "FavoriteMediaKindIsInvalid", "FavoriteMediaItemIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <returns>The Id of the seeded favorite.</returns>
|
||||
private async Task<Guid> SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid favoriteId = Guid.NewGuid();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
id: favoriteId,
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededFavoriteIds.Add(favoriteId);
|
||||
return favoriteId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </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();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
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(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a validation problem details document carrying the expected error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present, in order.</param>
|
||||
private static async Task AssertValidationProblemAsync(HttpResponseMessage response, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(422, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Equal(expectedErrorCodes, errors!["General.Validation"]);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Favorites.RemoveRange(dbContext.Favorites.Where(favorite => _seededFavoriteIds.Contains(favorite.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
|
||||
using Lumina.Presentation.Api.Fixtures.Core.Endpoints.FileSystemManagement;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetDirectoriesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly FileSystemStructureFixture _fileSystemStructureFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDirectoriesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetDirectoriesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[SkipWhenHiddenAttributeNotSupportedFact]
|
||||
public async Task GetDirectories_WhenCalledWithValidPathAndHiddenChildrenAndNotShouldIncludeHiddenElements_ShouldReturnNoDirectories()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // Two levels to get to the element that has a hidden element as child.
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
try
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// Assert
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
List<DirectoryResponse>? directories = JsonSerializer.Deserialize<List<DirectoryResponse>>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(directories);
|
||||
Assert.Empty(directories);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
[SkipWhenHiddenAttributeNotSupportedFact]
|
||||
public async Task GetDirectories_WhenCalledWithValidPathAndWithShouldIncludeHiddenElements_ShouldReturnDirectoriesWithHiddenElements()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // Two levels to get to the element that has a hidden element as child.
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
try
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
List<DirectoryResponse>? directories = JsonSerializer.Deserialize<List<DirectoryResponse>>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(directories);
|
||||
Assert.NotNull(directories);
|
||||
|
||||
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
|
||||
DirectoryResponse firstDirectory = directories!.First();
|
||||
Assert.Equal((s_isUnix ? "." : string.Empty) + "NestedDirectory_2", directories!.First().Name);
|
||||
Assert.Equal(System.IO.Path.Combine(testPath, (s_isUnix ? "." : string.Empty) + "NestedDirectory_2" + System.IO.Path.DirectorySeparatorChar), directories.First().Path);
|
||||
Assert.True(firstDirectory.IsHidden);
|
||||
Assert.Single(directories); // Only directories.
|
||||
}
|
||||
finally
|
||||
{
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDirectories_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = "invalid:path";
|
||||
string encodedPath = Uri.EscapeDataString(invalidPath);
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// 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("General.Failure", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/directories/get-directories", problemDetails["instance"].GetString());
|
||||
Assert.Equal("UnauthorizedAccess", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDirectories_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
string emptyPath = "";
|
||||
string encodedPath = Uri.EscapeDataString(emptyPath);
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/directories/get-directories", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDirectories_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}", cts.Token)
|
||||
);
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDirectories_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}", cts.Token);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Drives;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetDrivesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDrivesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDrivesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetDrivesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDrives_WhenCalled_ShouldReturnDrives()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/drives/get-drives");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
List<FileSystemTreeNodeResponse>? drives = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(drives);
|
||||
Assert.NotEmpty(drives);
|
||||
|
||||
FileSystemTreeNodeResponse firstDrive = drives!.First();
|
||||
Assert.Equal(s_isUnix ? "/" : "C:\\", firstDrive.Name);
|
||||
Assert.Equal(s_isUnix ? "/" : "C:\\", firstDrive.Path);
|
||||
Assert.Equal(FileSystemItemType.Root, firstDrive.ItemType);
|
||||
Assert.True(drives.Count >= 1);
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.FileSystem;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.FileSystem;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTypeEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTypeEndpointTests : 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="GetTypeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetTypeEndpointTests(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 GetType_WhenCalled_ShouldReturnOkResultWithFileSystemTypeResponse()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/file-system/get-type");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
FileSystemTypeResponse? result = JsonSerializer.Deserialize<FileSystemTypeResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result!.PlatformType == PlatformType.Unix || result.PlatformType == PlatformType.Windows);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetType_WhenCalledMultipleTimes_ShouldReturnConsistentResults()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response1 = await _client.GetAsync("/api/v1/file-system/get-type");
|
||||
HttpResponseMessage response2 = await _client.GetAsync("/api/v1/file-system/get-type");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response1.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, response2.StatusCode);
|
||||
|
||||
string content1 = await response1.Content.ReadAsStringAsync();
|
||||
string content2 = await response2.Content.ReadAsStringAsync();
|
||||
|
||||
FileSystemTypeResponse? result1 = JsonSerializer.Deserialize<FileSystemTypeResponse>(content1, _jsonOptions);
|
||||
FileSystemTypeResponse? result2 = JsonSerializer.Deserialize<FileSystemTypeResponse>(content2, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result1);
|
||||
Assert.NotNull(result2);
|
||||
Assert.Equal(result1.PlatformType, result2.PlatformType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetType_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.GetAsync("/api/v1/file-system/get-type", cts.Token)
|
||||
);
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Files;
|
||||
using Lumina.Presentation.Api.Fixtures.Core.Endpoints.FileSystemManagement;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFilesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly FileSystemStructureFixture _fileSystemStructureFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFilesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetFilesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[SkipWhenHiddenAttributeNotSupportedFact]
|
||||
public async Task GetFiles_WhenCalledWithValidPathAndNotShouldIncludeHiddenElements_ShouldReturnFilesWithoutHiddenElements()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
try
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
List<FileResponse>? files = JsonSerializer.Deserialize<List<FileResponse>>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(files);
|
||||
Assert.NotEmpty(files);
|
||||
|
||||
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
|
||||
FileResponse firstDirectory = files!.First();
|
||||
Assert.Equal("TestFile_2.txt", firstDirectory.Name);
|
||||
Assert.Equal(System.IO.Path.Combine(testPath, "TestFile_2.txt"), firstDirectory.Path);
|
||||
Assert.False(firstDirectory.IsHidden);
|
||||
Assert.Single(files); // Only files.
|
||||
}
|
||||
finally
|
||||
{
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
[SkipWhenHiddenAttributeNotSupportedFact]
|
||||
public async Task GetFiles_WhenCalledWithValidPathAndHiddenChildrenAndNotShouldIncludeHiddenElements_ShouldReturnNoFiles()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // Two levels to get to the element that has a hidden element as child.
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
try
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
List<FileResponse>? files = JsonSerializer.Deserialize<List<FileResponse>>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(files);
|
||||
FileResponse firstDirectory = files!.First();
|
||||
Assert.Equal("TestFile_2.txt", firstDirectory.Name);
|
||||
Assert.Equal(System.IO.Path.Combine(testPath, "TestFile_2.txt"), firstDirectory.Path);
|
||||
Assert.False(firstDirectory.IsHidden);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
[SkipWhenHiddenAttributeNotSupportedFact]
|
||||
public async Task GetFiles_WhenCalledWithValidPathAndWithShouldIncludeHiddenElements_ShouldReturnFilesWithHiddenElements()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // Two levels to get to the element that has a hidden element as child.
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
try
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
List<FileResponse>? files = JsonSerializer.Deserialize<List<FileResponse>>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(files);
|
||||
Assert.NotEmpty(files);
|
||||
|
||||
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
FileResponse firstDirectory = files!.First();
|
||||
Assert.Equal((s_isUnix ? "." : string.Empty) + "TestFile_1.txt", firstDirectory.Name);
|
||||
Assert.Equal(System.IO.Path.Combine(testPath, (s_isUnix ? "." : string.Empty) + "TestFile_1.txt"), firstDirectory.Path);
|
||||
Assert.True(firstDirectory.IsHidden);
|
||||
|
||||
FileResponse secondDirectory = files!.Last();
|
||||
Assert.Equal("TestFile_2.txt", secondDirectory.Name);
|
||||
Assert.Equal(System.IO.Path.Combine(testPath, "TestFile_2.txt"), secondDirectory.Path);
|
||||
Assert.False(secondDirectory.IsHidden);
|
||||
Assert.Equal(2, files.Count);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFiles_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = "invalid:path";
|
||||
string encodedPath = Uri.EscapeDataString(invalidPath);
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// 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("General.Failure", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/files/get-files", problemDetails["instance"].GetString());
|
||||
Assert.Equal("UnauthorizedAccess", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFiles_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
string emptyPath = "";
|
||||
string encodedPath = Uri.EscapeDataString(emptyPath);
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/files/get-files", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFiles_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}", cts.Token)
|
||||
);
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFiles_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Presentation.Api.Fixtures.Core.Endpoints.FileSystemManagement;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTreeFilesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly FileSystemStructureFixture _fileSystemStructureFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTreeFilesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetTreeFilesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[SkipWhenHiddenAttributeNotSupportedFact]
|
||||
public async Task GetTreeFiles_WhenCalledWithValidPathAndNotShouldIncludeHiddenElements_ShouldReturnTreeFilesWithoutHiddenElements()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
try
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
List<FileSystemTreeNodeResponse>? files = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(files);
|
||||
Assert.NotEmpty(files);
|
||||
|
||||
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
|
||||
FileSystemTreeNodeResponse firstDirectory = files!.First();
|
||||
Assert.Equal("TestFile_2.txt", firstDirectory.Name);
|
||||
Assert.Equal(System.IO.Path.Combine(testPath, "TestFile_2.txt"), firstDirectory.Path);
|
||||
Assert.Single(files); // Only files.
|
||||
}
|
||||
finally
|
||||
{
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
[SkipWhenHiddenAttributeNotSupportedFact]
|
||||
public async Task GetTreeFiles_WhenCalledWithValidPathAndHiddenChildrenAndNotShouldIncludeHiddenElements_ShouldReturnNoTreeFiles()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // Two levels to get to the element that has a hidden element as child.
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
try
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
List<FileSystemTreeNodeResponse>? files = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(files);
|
||||
|
||||
FileSystemTreeNodeResponse firstDirectory = files!.First();
|
||||
Assert.Equal("TestFile_2.txt", firstDirectory.Name);
|
||||
Assert.Equal(System.IO.Path.Combine(testPath, "TestFile_2.txt"), firstDirectory.Path);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
[SkipWhenHiddenAttributeNotSupportedFact]
|
||||
public async Task GetTreeFiles_WhenCalledWithValidPathAndWithShouldIncludeHiddenElements_ShouldReturnTreeFilesWithHiddenElements()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // Two levels to get to the element that has a hidden element as child.
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
try
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
List<FileSystemTreeNodeResponse>? files = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(files);
|
||||
Assert.NotEmpty(files);
|
||||
|
||||
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
FileSystemTreeNodeResponse firstDirectory = files!.First();
|
||||
Assert.Equal((s_isUnix ? "." : string.Empty) + "TestFile_1.txt", firstDirectory.Name);
|
||||
Assert.Equal(System.IO.Path.Combine(testPath, (s_isUnix ? "." : string.Empty) + "TestFile_1.txt"), firstDirectory.Path);
|
||||
Assert.True(firstDirectory.IsHidden);
|
||||
|
||||
FileSystemTreeNodeResponse secondDirectory = files!.Last();
|
||||
Assert.Equal("TestFile_2.txt", secondDirectory.Name);
|
||||
Assert.Equal(System.IO.Path.Combine(testPath, "TestFile_2.txt"), secondDirectory.Path);
|
||||
Assert.False(secondDirectory.IsHidden);
|
||||
Assert.Equal(2, files.Count);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
[Fact]
|
||||
public async Task GetTreeFiles_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = "invalid:path";
|
||||
string encodedPath = Uri.EscapeDataString(invalidPath);
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// 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("General.Failure", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/files/get-tree-files", problemDetails["instance"].GetString());
|
||||
Assert.Equal("UnauthorizedAccess", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTreeFiles_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
string emptyPath = "";
|
||||
string encodedPath = Uri.EscapeDataString(emptyPath);
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/files/get-tree-files", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTreeFiles_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}", cts.Token)
|
||||
);
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTreeFiles_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="CheckPathExistsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CheckPathExistsEndpointTests : 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="CheckPathExistsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public CheckPathExistsEndpointTests(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 CheckPathExists_WhenCalledWithExistingPath_ShouldReturnOkResultWithExistsTrue()
|
||||
{
|
||||
// Arrange
|
||||
string tempPath = System.IO.Path.GetTempPath();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(tempPath)}&shouldIncludeHiddenElements=false");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PathExistsResponse? result = JsonSerializer.Deserialize<PathExistsResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result!.Exists);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckPathExists_WhenCalledWithNonExistingPath_ShouldReturnOkResultWithExistsFalse()
|
||||
{
|
||||
// Arrange
|
||||
string nonExistingPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(nonExistingPath)}&shouldIncludeHiddenElements=false");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PathExistsResponse? result = JsonSerializer.Deserialize<PathExistsResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.False(result!.Exists);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckPathExists_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
string path = "";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=false");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/path/check-path-exists", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckPathExists_WhenCalledWithInvalidPath_ShouldReturnOkResultWithExistsFalse()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = "invalid:path";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(invalidPath)}&shouldIncludeHiddenElements=false");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PathExistsResponse? result = JsonSerializer.Deserialize<PathExistsResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.False(result!.Exists);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckPathExists_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.GetTempPath();
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/path/check-path-exists?path={encodedPath}&shouldIncludeHiddenElements=false", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="CombinePathEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CombinePathEndpointTests : 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="CombinePathEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public CombinePathEndpointTests(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 CombinePath_WhenCalledWithValidPaths_ShouldReturnOkResultWithCombinedPath()
|
||||
{
|
||||
// Arrange
|
||||
string originalPath = System.IO.Path.GetTempPath();
|
||||
string newPath = "testDirectory";
|
||||
string expectedPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
|
||||
if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar))
|
||||
expectedPath += System.IO.Path.DirectorySeparatorChar;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PathSegmentResponse? result = JsonSerializer.Deserialize<PathSegmentResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(expectedPath, result!.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CombinePath_WhenCalledWithEmptyPaths_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
string originalPath = "";
|
||||
string newPath = "";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/path/combine", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CombinePath_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
string originalPath = "/home/user";
|
||||
string newPath = "documents";
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}", cts.Token)
|
||||
);
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CombinePath_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
string originalPath = System.IO.Path.GetTempPath();
|
||||
string newPath = "testFile.txt";
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPathParentEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathParentEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathParentEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPathParentEndpointTests(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 GetPathParent_WhenCalledWithValidPath_ShouldReturnOkResultWithPathSegmentResponses()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory", "testFile.txt");
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
IEnumerable<PathSegmentResponse>? result = JsonSerializer.Deserialize<IEnumerable<PathSegmentResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.NotEmpty(result);
|
||||
|
||||
List<string> hierarchy = [];
|
||||
string path = System.IO.Path.GetDirectoryName(testPath)!;
|
||||
while (!string.IsNullOrEmpty(path))
|
||||
{
|
||||
string segment = s_isUnix && path == System.IO.Path.DirectorySeparatorChar.ToString() ? path : System.IO.Path.GetFileName(path);
|
||||
if (string.IsNullOrEmpty(segment))
|
||||
{
|
||||
hierarchy.Add(System.IO.Path.GetPathRoot(path)!.TrimEnd(System.IO.Path.DirectorySeparatorChar));
|
||||
break;
|
||||
}
|
||||
hierarchy.Add(segment);
|
||||
path = System.IO.Path.GetDirectoryName(path)!;
|
||||
}
|
||||
hierarchy.Reverse();
|
||||
|
||||
Assert.Equal(hierarchy, result.Select(r => r.Path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathParent_WhenCalledWithRootPath_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
string rootPath = System.IO.Path.GetPathRoot(System.IO.Path.GetTempPath())!;
|
||||
string encodedPath = Uri.EscapeDataString(rootPath);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}");
|
||||
|
||||
// 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("General.Failure", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/path/get-path-parent", problemDetails["instance"].GetString());
|
||||
Assert.Equal("CannotNavigateUp", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathParent_WhenCalledWithInvalidPath_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = "invalid:path";
|
||||
string encodedPath = Uri.EscapeDataString(invalidPath);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/path/get-path-parent", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("InvalidPath", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathParent_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
string emptyPath = "";
|
||||
string encodedPath = Uri.EscapeDataString(emptyPath);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/path/get-path-parent", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathParent_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}", cts.Token)
|
||||
);
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathParent_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPathRootEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathRootEndpointTests : 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="GetPathRootEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPathRootEndpointTests(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 GetPathRoot_WhenCalledWithValidPath_ShouldReturnOkResultWithPathSegmentResponse()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.GetTempPath();
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PathSegmentResponse? result = JsonSerializer.Deserialize<PathSegmentResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.NotNull(result!.Path);
|
||||
Assert.NotEmpty(result.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathRoot_WhenCalledWithInvalidPath_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = "invalid:path";
|
||||
string encodedPath = Uri.EscapeDataString(invalidPath);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/path/get-path-root", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("InvalidPath", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathRoot_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
string emptyPath = "";
|
||||
string encodedPath = Uri.EscapeDataString(emptyPath);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/path/get-path-root", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathRoot_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.GetTempPath();
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}", cts.Token)
|
||||
);
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathRoot_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.GetTempPath();
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPathSeparatorEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathSeparatorEndpointTests : 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="GetPathSeparatorEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPathSeparatorEndpointTests(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 GetPathSeparator_WhenCalled_ShouldReturnOkResultWithPathSeparatorResponse()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/path/get-path-separator");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PathSeparatorResponse? result = JsonSerializer.Deserialize<PathSeparatorResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result!.Separator == "/" || result.Separator == "\\");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathSeparator_WhenCalledMultipleTimes_ShouldReturnConsistentResults()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response1 = await _client.GetAsync("/api/v1/path/get-path-separator");
|
||||
HttpResponseMessage response2 = await _client.GetAsync("/api/v1/path/get-path-separator");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response1.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, response2.StatusCode);
|
||||
|
||||
string content1 = await response1.Content.ReadAsStringAsync();
|
||||
string content2 = await response2.Content.ReadAsStringAsync();
|
||||
|
||||
PathSeparatorResponse? result1 = JsonSerializer.Deserialize<PathSeparatorResponse>(content1, _jsonOptions);
|
||||
PathSeparatorResponse? result2 = JsonSerializer.Deserialize<PathSeparatorResponse>(content2, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result1);
|
||||
Assert.NotNull(result2);
|
||||
Assert.Equal(result1, result2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathSeparator_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.GetAsync("/api/v1/path/get-path-separator", cts.Token)
|
||||
);
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathSeparator_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync("/api/v1/path/get-path-separator", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SplitPathEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SplitPathEndpointTests : 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="SplitPathEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public SplitPathEndpointTests(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 SplitPath_WhenCalledWithValidPath_ShouldReturnOkResultWithSplitSegments()
|
||||
{
|
||||
// Arrange
|
||||
string tempPath = System.IO.Path.GetTempPath();
|
||||
string testPath = System.IO.Path.Combine(tempPath, "testFolder", "testFile.txt");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/split?path={Uri.EscapeDataString(testPath)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
IEnumerable<PathSegmentResponse>? result = JsonSerializer.Deserialize<IEnumerable<PathSegmentResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result!.Count() >= 3);
|
||||
|
||||
IEnumerable<string> paths = result.Select(r => r.Path);
|
||||
Assert.Contains("testFolder", paths);
|
||||
Assert.Contains("testFile.txt", paths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SplitPath_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
string path = "";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/split?path={Uri.EscapeDataString(path)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/path/split", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SplitPath_WhenCalledWithInvalidPath_ShouldReturnProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
string path = "invalid:path";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/split?path={Uri.EscapeDataString(path)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/path/split", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("InvalidPath", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SplitPath_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/path/split?path={encodedPath}", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ValidatePathEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ValidatePathEndpointTests : 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="ValidatePathEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ValidatePathEndpointTests(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 ValidatePath_WhenCalledWithValidPath_ShouldReturnOkResultWithIsValidTrue()
|
||||
{
|
||||
// Arrange
|
||||
string tempPath = System.IO.Path.GetTempPath();
|
||||
string testPath = System.IO.Path.Combine(tempPath, "testFolder", "testFile.txt");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/validate?path={Uri.EscapeDataString(testPath)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PathValidResponse? result = JsonSerializer.Deserialize<PathValidResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result!.IsValid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidatePath_WhenCalledWithInvalidPath_ShouldReturnOkResultWithIsValidFalse()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = "invalid:path";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/validate?path={Uri.EscapeDataString(invalidPath)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PathValidResponse? result = JsonSerializer.Deserialize<PathValidResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.False(result!.IsValid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidatePath_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
string path = "";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/validate?path={Uri.EscapeDataString(path)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/path/validate", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidatePath_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/path/validate?path={encodedPath}", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Api.Fixtures.Core.Endpoints.FileSystemManagement;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Thumbnails;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetThumbnailEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetThumbnailEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IClassFixture<TestImageFixture>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly string _testImagePath;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetThumbnailEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
/// <param name="imageFixture">Fixture for creating and managing test images.</param>
|
||||
public GetThumbnailEndpointTests(AuthenticatedLuminaApiFactory apiFactory, TestImageFixture imageFixture)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
_testImagePath = imageFixture.ImagePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThumbnail_WhenCalledWithValidPathAndQuality_ShouldReturnOkResultWithThumbnail()
|
||||
{
|
||||
// Arrange
|
||||
int quality = 80;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={quality}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("image/jpeg", response.Content.Headers.ContentType!.MediaType);
|
||||
byte[] content = await response.Content.ReadAsByteArrayAsync();
|
||||
Assert.NotEmpty(content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThumbnail_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
string invalidImagePath = "/path/to/nonexistent/image.jpg";
|
||||
int quality = 80;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(invalidImagePath)}&quality={quality}");
|
||||
|
||||
// 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("General.Failure", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/thumbnails/get-thumbnail", problemDetails["instance"].GetString());
|
||||
Assert.Equal("UnauthorizedAccess", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThumbnail_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
string invalidImagePath = "";
|
||||
int quality = 80;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(invalidImagePath)}&quality={quality}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/thumbnails/get-thumbnail", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThumbnail_WhenCalledWithInvalidQuality_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
int invalidQuality = -1;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={invalidQuality}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/thumbnails/get-thumbnail", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("ImageQualityMustBeBetweenZeroAndOneHundred", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThumbnail_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
int quality = 80;
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={quality}", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
|
||||
private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddAlbumEndpointTests(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 AddAlbum_WhenCalledWithValidData_ShouldAddAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(
|
||||
metadata: _musicAlbumMetadataDtoFixture.Create(title: "News of the World"),
|
||||
contributors: [],
|
||||
ratings: [],
|
||||
tracks: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AlbumResponse? albumResponse = JsonSerializer.Deserialize<AlbumResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(albumResponse);
|
||||
Assert.Equal(artistId, albumResponse!.ArtistId);
|
||||
Assert.Equal(libraryId, albumResponse.LibraryId);
|
||||
Assert.Equal("News of the World", albumResponse.Metadata.Title);
|
||||
|
||||
Assert.NotNull(response.Headers.Location);
|
||||
Assert.EndsWith($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumResponse.Id}", response.Headers.Location!.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenMetadataIsMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(includeMetadata: false, contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Metadata.MetadataCannotBeNull.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenTitleIsMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(
|
||||
metadata: _musicAlbumMetadataDtoFixture.Create(includeTitle: false),
|
||||
contributors: [],
|
||||
ratings: [],
|
||||
tracks: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Music.AlbumTitleCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutDisclosingIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
Guid otherLibraryId = Guid.NewGuid();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{artistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(otherLibraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{artistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Library.LibraryIdCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Music.ArtistIdCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request, cts.Token));
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist that owns a single album, both belonging to <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistWithAlbumAsync(Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+489
@@ -0,0 +1,489 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteAlbumEndpointTests(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 DeleteAlbum_WhenAlbumBelongsToAnOwnedArtist_ShouldSoftDeleteTheAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid otherAlbumId) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
|
||||
Assert.NotNull(album);
|
||||
Assert.True(album!.IsDeleted);
|
||||
Assert.NotNull(album.DeletedOnUtc);
|
||||
// The sibling album of the artist is untouched.
|
||||
AlbumEntity? otherAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == otherAlbumId);
|
||||
Assert.NotNull(otherAlbum);
|
||||
Assert.False(otherAlbum!.IsDeleted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumHasStoredArtwork_ShouldKeepTheArtworkOfTheAlbumAndOfItsTracks()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId);
|
||||
await SeedArtworkAsync(MusicArtworkOwnerType.Album, albumId, "media/music/queen/album.jpg");
|
||||
await SeedArtworkAsync(MusicArtworkOwnerType.Track, trackId, "media/music/queen/track.jpg");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
// The album is soft deleted, so its artwork and the artwork of its tracks stay available until the user restores it.
|
||||
AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
|
||||
Assert.NotNull(album);
|
||||
Assert.True(album!.IsDeleted);
|
||||
Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId));
|
||||
Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumIsTheOnlyAlbumOfTheArtist_ShouldReturnForbiddenWithoutDeletingTheAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistWithSingleAlbumAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Forbidden", "ArtistMustHaveAtLeastOneAlbum", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
|
||||
Assert.NotNull(album);
|
||||
Assert.False(album!.IsDeleted);
|
||||
Assert.Null(album.DeletedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _, _) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumRequestedThroughDifferentArtist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId, _) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId, Guid albumId, _) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, _) = await SeedLibraryArtistWithTwoAlbumsAsync(otherUserId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: "A Night at the Opera",
|
||||
tracks: [track],
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
// An artist must keep at least one album, so a sibling album is seeded alongside the deleted one.
|
||||
AlbumEntity otherAlbum = _albumEntityFixture.Create(
|
||||
id: Guid.NewGuid(),
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: "News of the World",
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album, otherAlbum], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a piece of stored artwork owned by the music library item identified by <paramref name="ownerId"/>.
|
||||
/// </summary>
|
||||
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
|
||||
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
|
||||
/// <param name="fileName">The relative file name of the stored artwork.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist that owns a single album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistWithSingleAlbumAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: "A Night at the Opera",
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist that owns two albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and the two albums.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid otherAlbumId)> SeedLibraryArtistWithTwoAlbumsAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid otherAlbumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
AlbumEntity otherAlbum = _albumEntityFixture.Create(id: otherAlbumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album, otherAlbum], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, otherAlbumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+335
@@ -0,0 +1,335 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAlbumEndpointTests(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 GetAlbum_WhenAlbumBelongsToAnOwnedLibrary_ShouldReturnAlbumDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AlbumResponse? album = JsonSerializer.Deserialize<AlbumResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(album);
|
||||
Assert.Equal(albumId, album!.Id);
|
||||
Assert.Equal(artistId, album.ArtistId);
|
||||
Assert.Equal(libraryId, album.LibraryId);
|
||||
Assert.Equal("A Night at the Opera", album.Metadata.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumRequestedThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
// The route artist id is enforced, so an album of another artist is reported as not found, without disclosing that it exists.
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumRequestedThroughDifferentLibrary_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId, "News of the World");
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="albumTitle">The title of the seeded album.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
|
||||
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.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAlbumTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAlbumTracksEndpointTests(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 GetAlbumTracks_WhenAlbumHasTracks_ShouldReturnTrackDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TrackResponse>? tracks = await response.Content.ReadFromJsonAsync<List<TrackResponse>>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
TrackResponse track = Assert.Single(tracks!);
|
||||
Assert.Equal("Bohemian Rhapsody", track.Metadata.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumHasNoTracks_ShouldReturnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TrackResponse>? tracks = await response.Content.ReadFromJsonAsync<List<TrackResponse>>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Empty(tracks!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumRequestedThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="albumTitle">The title of the seeded album.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist, one of its albums and one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/bohemian-rhapsody-{Guid.NewGuid():N}.flac", title: "Bohemian Rhapsody", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
|
||||
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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAlbumTracksLiteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksLiteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAlbumTracksLiteEndpointTests(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 GetAlbumTracksLite_WhenAlbumHasTracks_ShouldReturnTrackLiteDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<TrackLiteResponse>? tracks = await response.Content.ReadFromJsonAsync<PaginatedResponse<TrackLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Equal(1, tracks!.Count);
|
||||
TrackLiteResponse track = Assert.Single(tracks.Data);
|
||||
Assert.Equal("Bohemian Rhapsody", track.Title);
|
||||
Assert.True(track.DurationInSeconds > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumHasNoTracks_ShouldReturnEmptyPaginatedResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<TrackLiteResponse>? tracks = await response.Content.ReadFromJsonAsync<PaginatedResponse<TrackLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Empty(tracks!.Data);
|
||||
Assert.Equal(0, tracks.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid/tracks/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="albumTitle">The title of the seeded album.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist, one of its albums and one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/bohemian-rhapsody-{Guid.NewGuid():N}.flac", title: "Bohemian Rhapsody", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetDeletedAlbumsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDeletedAlbumsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDeletedAlbumsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetDeletedAlbumsEndpointTests(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 GetDeletedAlbums_WhenLibraryHasDeletedAlbums_ShouldReturnOnlyTheDeletedAlbums()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistAsync(libraryId, name: "Queen");
|
||||
AlbumEntity deletedAlbum = await SeedAlbumAsync(libraryId, artistId, title: "A Night at the Opera", isDeleted: true);
|
||||
await SeedAlbumAsync(libraryId, artistId, title: "News of the World", isDeleted: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/albums/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
DeletedAlbumResponse[]? albums = await response.Content.ReadFromJsonAsync<DeletedAlbumResponse[]>(_jsonOptions);
|
||||
Assert.NotNull(albums);
|
||||
Assert.Single(albums);
|
||||
Assert.Equal(deletedAlbum.Id, albums![0].Id);
|
||||
Assert.Equal(libraryId, albums[0].LibraryId);
|
||||
Assert.Equal(artistId, albums[0].ArtistId);
|
||||
Assert.Equal("Queen", albums[0].ArtistName);
|
||||
Assert.Equal("A Night at the Opera", albums[0].Title);
|
||||
Assert.NotEqual(default, albums[0].DeletedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedAlbums_WhenAlbumBelongsToDeletedArtist_ShouldNotReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistAsync(libraryId, name: "Queen");
|
||||
await SeedAlbumAsync(libraryId, artistId, title: "A Night at the Opera", isDeleted: true);
|
||||
await SoftDeleteArtistAsync(artistId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/albums/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
DeletedAlbumResponse[]? albums = await response.Content.ReadFromJsonAsync<DeletedAlbumResponse[]>(_jsonOptions);
|
||||
Assert.NotNull(albums);
|
||||
Assert.Empty(albums);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedAlbums_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{otherLibraryId}/albums/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedAlbums_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/albums/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedAlbums_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/albums/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist in the provided library.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the artist.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false);
|
||||
dbContext.Artists.Add(artist);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artist.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of the provided artist, in the requested deletion state.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the album.</param>
|
||||
/// <param name="artistId">The Id of the artist that owns the album.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <param name="isDeleted">Whether the album is soft deleted.</param>
|
||||
/// <returns>The seeded album.</returns>
|
||||
private async Task<AlbumEntity> SeedAlbumAsync(Guid libraryId, Guid artistId, string title, bool isDeleted)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
album.IsDeleted = isDeleted;
|
||||
album.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null;
|
||||
dbContext.Albums.Add(album);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return album;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Soft deletes the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The Id of the artist to soft delete.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SoftDeleteArtistAsync(Guid artistId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
ArtistEntity artist = await dbContext.Artists.FirstAsync(artist => artist.Id == artistId);
|
||||
artist.IsDeleted = true;
|
||||
artist.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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();
|
||||
}
|
||||
}
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum;
|
||||
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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RestoreAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RestoreAlbumEndpointTests(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 RestoreAlbum_WhenDeletedAlbumBelongsToAnOwnedArtist_ShouldRestoreTheAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, isDeleted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
|
||||
Assert.NotNull(album);
|
||||
Assert.False(album!.IsDeleted);
|
||||
Assert.Null(album.DeletedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreAlbum_WhenAlbumIsNotDeleted_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, isDeleted: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreAlbum_WhenAlbumIsRestoredThroughDifferentLibrary_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, isDeleted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreAlbum_WhenAlbumIsRestoredThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, isDeleted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId, isDeleted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreAlbum_WhenIdsAreNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync("/api/v1/libraries/not-a-guid/artists/not-a-guid/albums/not-a-guid/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, an artist of it and an album of the artist, in the requested deletion state.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="isDeleted">Whether the seeded album is soft deleted.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, bool isDeleted)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: "A Night at the Opera",
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
album.IsDeleted = isDeleted;
|
||||
album.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null;
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, album.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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();
|
||||
}
|
||||
}
|
||||
+344
@@ -0,0 +1,344 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
|
||||
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.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly UpdateAlbumRequestFixture _updateAlbumRequestFixture = new();
|
||||
private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateAlbumEndpointTests(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 UpdateAlbum_WhenCalledByOwnerWithValidData_ShouldUpdateAlbumAndPersistChanges()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(
|
||||
metadata: _musicAlbumMetadataDtoFixture.Create(title: "Updated Album"),
|
||||
contributors: [],
|
||||
ratings: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AlbumResponse? albumResponse = JsonSerializer.Deserialize<AlbumResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(albumResponse);
|
||||
Assert.Equal(albumId, albumResponse!.Id);
|
||||
Assert.Equal("Updated Album", albumResponse.Metadata.Title);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
AlbumEntity storedAlbum = dbContext.Albums.Single(album => album.Id == albumId);
|
||||
Assert.Equal("Updated Album", storedAlbum.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId, "News of the World");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenMetadataIsMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(includeMetadata: false, contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "MetadataCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="albumTitle">The title of the seeded album.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
|
||||
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.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateAlbumCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumCoverEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateAlbumCoverEndpointTests(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 UpdateAlbumCover_WhenCalledByOwnerWithValidImage_ShouldReplaceTheStoredCover()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumWithCoverAsync(userId, "/media/music/old-cover.jpg");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
string storedPath = JsonSerializer.Deserialize<UpdateAlbumCoverResponse>(content, _jsonOptions)!.CoverPath;
|
||||
Assert.False(string.IsNullOrWhiteSpace(storedPath));
|
||||
Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MusicArtworkEntity coverArtwork = dbContext.MusicArtwork
|
||||
.Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId && artwork.ArtworkType == ArtworkType.Cover);
|
||||
Assert.Equal(storedPath, coverArtwork.FileName);
|
||||
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenAlbumHasNoExistingCover_ShouldCreateACoverArtwork()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
string storedPath = JsonSerializer.Deserialize<UpdateAlbumCoverResponse>(content, _jsonOptions)!.CoverPath;
|
||||
Assert.False(string.IsNullOrWhiteSpace(storedPath));
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MusicArtworkEntity coverArtwork = dbContext.MusicArtwork
|
||||
.Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId && artwork.ArtworkType == ArtworkType.Cover);
|
||||
Assert.Equal(storedPath, coverArtwork.FileName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/cover";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
|
||||
Guid otherLibraryId = Guid.NewGuid();
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{artistId}/albums/{albumId}/cover";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/cover";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PutAsync(url, CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenNoFileIsUploaded_ShouldReturnUnprocessableEntityWithCoverCannotBeNull()
|
||||
{
|
||||
// Arrange
|
||||
MultipartFormDataContent form = [];
|
||||
form.Add(new StringContent("unrelated-field"), "unrelated-field");
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync(url, form);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "CoverCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{Guid.NewGuid()}/albums/not-a-guid/cover";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a multipart form carrying a minimal PNG-like payload.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>A configured <see cref="MultipartFormDataContent"/> instance.</returns>
|
||||
private static MultipartFormDataContent CreateCoverForm(string fileName)
|
||||
{
|
||||
// The payload only needs to carry the PNG signature in its first bytes and exceed the header detection buffer.
|
||||
byte[] payload = new byte[100];
|
||||
payload[0] = 137;
|
||||
payload[1] = 80;
|
||||
payload[2] = 78;
|
||||
payload[3] = 71;
|
||||
payload[4] = 13;
|
||||
payload[5] = 10;
|
||||
payload[6] = 26;
|
||||
payload[7] = 10;
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(payload);
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "cover", fileName);
|
||||
return form;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums that has no cover yet.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums that already has a cover.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="existingCoverFileName">The relative path of the existing cover of the album.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumWithCoverAsync(Guid userId, string existingCoverFileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Cover, ordinal: 0, fileName: existingCoverFileName, status: ArtworkStatus.Enriched));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+350
@@ -0,0 +1,350 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
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.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly AddArtistRequestFixture _addArtistRequestFixture = new();
|
||||
private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
|
||||
private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new();
|
||||
private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddArtistEndpointTests(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 AddArtist_WhenCalledWithValidData_ShouldAddArtist()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
AddAlbumRequest album = _addAlbumRequestFixture.Create(
|
||||
metadata: _musicAlbumMetadataDtoFixture.Create(title: "A Night at the Opera"),
|
||||
contributors: [],
|
||||
ratings: [],
|
||||
tracks: []);
|
||||
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: [album]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ArtistResponse? artistResponse = JsonSerializer.Deserialize<ArtistResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(artistResponse);
|
||||
Assert.Equal(libraryId, artistResponse!.LibraryId);
|
||||
Assert.Equal("Queen", artistResponse.Metadata.Name);
|
||||
Assert.NotNull(artistResponse.Albums);
|
||||
AlbumResponse albumResponse = Assert.Single(artistResponse.Albums!);
|
||||
Assert.Equal("A Night at the Opera", albumResponse.Metadata.Title);
|
||||
|
||||
Assert.NotNull(response.Headers.Location);
|
||||
Assert.EndsWith($"/api/v1/libraries/{libraryId}/artists/{artistResponse.Id}", response.Headers.Location!.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddArtist_WhenNameIsMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(includeName: false), contributors: [], albums: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, $"/api/v1/libraries/{libraryId}/artists", Errors.Music.ArtistNameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddArtist_WhenAlbumsAreMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], includeAlbums: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, $"/api/v1/libraries/{libraryId}/artists", Errors.Music.AlbumsListCannotBeNull.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddArtist_WhenAlbumMetadataIsMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
AddAlbumRequest album = _addAlbumRequestFixture.Create(includeMetadata: false, contributors: [], ratings: [], tracks: []);
|
||||
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: [album]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, $"/api/v1/libraries/{libraryId}/artists", Errors.Metadata.MetadataCannotBeNull.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddArtist_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
|
||||
AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: [album]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{otherLibraryId}/artists", request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", $"/api/v1/libraries/{otherLibraryId}/artists", "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddArtist_WhenLibraryDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
// Only an admin reaches the library lookup of a library that does not exist, because a regular user is rejected by the ownership policy before it.
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
Guid missingLibraryId = Guid.NewGuid();
|
||||
AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: [album]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.PostAsJsonAsync($"/api/v1/libraries/{missingLibraryId}/artists", request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", Errors.Library.LibraryNotFound.Description, $"/api/v1/libraries/{missingLibraryId}/artists", "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: [album]);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddArtist_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: [album]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/not-a-guid/artists", request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, "/api/v1/libraries/not-a-guid/artists", Errors.Library.LibraryIdCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddArtist_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: [album]);
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request, cts.Token));
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library of type music, owned by <paramref name="userId"/>, whose single content location is the temp path.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+403
@@ -0,0 +1,403 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteArtistEndpointTests(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 DeleteArtist_WhenArtistBelongsToAnOwnedLibrary_ShouldSoftDeleteTheArtist()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId);
|
||||
Assert.NotNull(artist);
|
||||
Assert.True(artist!.IsDeleted);
|
||||
Assert.NotNull(artist.DeletedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteArtist_WhenArtistHasStoredArtwork_ShouldKeepTheArtworkOfTheArtistAndOfItsChildren()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId);
|
||||
await SeedArtworkAsync(MusicArtworkOwnerType.Artist, artistId, "media/music/queen/artist.jpg");
|
||||
await SeedArtworkAsync(MusicArtworkOwnerType.Album, albumId, "media/music/queen/album.jpg");
|
||||
await SeedArtworkAsync(MusicArtworkOwnerType.Track, trackId, "media/music/queen/track.jpg");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
// The artist is soft deleted, so its albums, tracks and artwork stay available until the user restores it.
|
||||
ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId);
|
||||
Assert.NotNull(artist);
|
||||
Assert.True(artist!.IsDeleted);
|
||||
Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId));
|
||||
Assert.NotNull(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId));
|
||||
Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId));
|
||||
Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId));
|
||||
Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteArtist_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteArtist_WhenArtistRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId) = await SeedLibraryAndArtistAsync(userId);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId) = await SeedLibraryAndArtistAsync(otherUserId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteArtist_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteArtist_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: "A Night at the Opera",
|
||||
tracks: [track],
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a piece of stored artwork owned by the music library item identified by <paramref name="ownerId"/>.
|
||||
/// </summary>
|
||||
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
|
||||
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
|
||||
/// <param name="fileName">The relative file name of the stored artwork.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist of that library.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library and artist.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetArtistEndpointTests(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 GetArtist_WhenArtistBelongsToAnOwnedLibrary_ShouldReturnArtistDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId, "Queen");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ArtistResponse? artist = JsonSerializer.Deserialize<ArtistResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(artist);
|
||||
Assert.Equal(artistId, artist!.Id);
|
||||
Assert.Equal(libraryId, artist.LibraryId);
|
||||
Assert.Equal("Queen", artist.Metadata.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtist_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtist_WhenArtistRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId) = await SeedLibraryAndArtistAsync(userId, "Queen");
|
||||
// The route library id is enforced, so an artist of another library is reported as not found, without disclosing that it exists.
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId) = await SeedLibraryAndArtistAsync(otherUserId, "Queen");
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtist_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtist_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist of that library.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="artistName">The name of the seeded artist.</param>
|
||||
/// <returns>The Ids of the seeded library and artist.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId, string artistName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+353
@@ -0,0 +1,353 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums;
|
||||
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.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetArtistAlbumsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetArtistAlbumsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetArtistAlbumsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetArtistAlbumsEndpointTests(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 GetArtistAlbums_WhenArtistHasAlbums_ShouldReturnAlbumDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistAsync(libraryId);
|
||||
await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
await SeedAlbumAsync(libraryId, artistId, "News of the World");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<AlbumResponse>? albums = await response.Content.ReadFromJsonAsync<List<AlbumResponse>>(_jsonOptions);
|
||||
Assert.NotNull(albums);
|
||||
Assert.Equal(2, albums!.Count);
|
||||
Assert.Contains(albums, album => album.Metadata.Title == "A Night at the Opera");
|
||||
Assert.Contains(albums, album => album.Metadata.Title == "News of the World");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbums_WhenArtistHasNoAlbums_ShouldReturnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistAsync(libraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<AlbumResponse>? albums = await response.Content.ReadFromJsonAsync<List<AlbumResponse>>(_jsonOptions);
|
||||
Assert.NotNull(albums);
|
||||
Assert.Empty(albums!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbums_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbums_WhenArtistRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistAsync(libraryId);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbums_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
|
||||
Guid otherArtistId = await SeedArtistAsync(otherLibraryId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbums_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbums_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbums_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist belonging to the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album belonging to the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, title: title, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite;
|
||||
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.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetArtistAlbumsLiteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetArtistAlbumsLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetArtistAlbumsLiteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetArtistAlbumsLiteEndpointTests(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 GetArtistAlbumsLite_WhenArtistHasAlbums_ShouldReturnAlbumLiteDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistAsync(libraryId);
|
||||
await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
await SeedAlbumAsync(libraryId, artistId, "News of the World");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<AlbumLiteResponse>? albums = await response.Content.ReadFromJsonAsync<PaginatedResponse<AlbumLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(albums);
|
||||
Assert.Equal(2, albums!.Count);
|
||||
Assert.Equal(2, albums.Data.Count);
|
||||
Assert.Contains(albums.Data, album => album.Title == "A Night at the Opera");
|
||||
Assert.Contains(albums.Data, album => album.Title == "News of the World");
|
||||
// The release types and the release year are exposed by the read model, so the lite listing can group and order the releases of an artist.
|
||||
Assert.All(albums.Data, album => Assert.NotEmpty(album.ReleaseTypes!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbumsLite_WhenArtistHasNoAlbums_ShouldReturnEmptyPaginatedResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistAsync(libraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<AlbumLiteResponse>? albums = await response.Content.ReadFromJsonAsync<PaginatedResponse<AlbumLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(albums);
|
||||
Assert.Empty(albums!.Data);
|
||||
Assert.Equal(0, albums.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbumsLite_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbumsLite_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
|
||||
Guid otherArtistId = await SeedArtistAsync(otherLibraryId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbumsLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbumsLite_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbumsLite_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist belonging to the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album belonging to the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, title: title, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtists;
|
||||
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.AudioLibrary.MusicLibrary.Artists.GetArtists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetArtistsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetArtistsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetArtistsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetArtistsEndpointTests(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 GetArtists_WhenCalledWithoutPaginationData_ShouldReturnAllArtists()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedArtistAsync(libraryId, "Artist A");
|
||||
await SeedArtistAsync(libraryId, "Artist B");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ArtistResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedArtists);
|
||||
Assert.Equal(2, paginatedArtists!.Count);
|
||||
Assert.Equal(2, paginatedArtists.Data.Count);
|
||||
Assert.Equal(1, paginatedArtists.CurrentPage);
|
||||
Assert.Contains(paginatedArtists.Data, artist => artist.Metadata.Name == "Artist A");
|
||||
Assert.Contains(paginatedArtists.Data, artist => artist.Metadata.Name == "Artist B");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtists_WhenCalledWithSearchTerm_ShouldReturnOnlyMatchingArtists()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedArtistAsync(libraryId, "Fellowship");
|
||||
await SeedArtistAsync(libraryId, "The Two Towers");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists?searchTerm={Uri.EscapeDataString("Fellowship")}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<ArtistResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedArtists);
|
||||
ArtistResponse artist = Assert.Single(paginatedArtists!.Data);
|
||||
Assert.Equal("Fellowship", artist.Metadata.Name);
|
||||
Assert.Equal(1, paginatedArtists.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtists_WhenCalledWithPaginationData_ShouldReturnRequestedPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedArtistAsync(libraryId, "Artist A");
|
||||
await SeedArtistAsync(libraryId, "Artist B");
|
||||
await SeedArtistAsync(libraryId, "Artist C");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists?currentPage=2&perPage=2");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<ArtistResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedArtists);
|
||||
Assert.Equal(3, paginatedArtists!.Count);
|
||||
Assert.Equal(2, paginatedArtists.NumberOfPages);
|
||||
Assert.Equal(2, paginatedArtists.CurrentPage);
|
||||
Assert.Equal(2, paginatedArtists.PerPage);
|
||||
ArtistResponse artist = Assert.Single(paginatedArtists.Data);
|
||||
Assert.Equal("Artist C", artist.Metadata.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtists_WhenNoArtistsExist_ShouldReturnEmptyPaginatedResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<ArtistResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedArtists);
|
||||
Assert.Empty(paginatedArtists!.Data);
|
||||
Assert.Equal(0, paginatedArtists.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtists_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid libraryId = await SeedLibraryAsync(otherUserId);
|
||||
await SeedArtistAsync(libraryId, "Artist A");
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtists_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtists_WhenRouteIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/libraries/not-a-guid/artists";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist belonging to the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+428
@@ -0,0 +1,428 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite;
|
||||
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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetArtistsLiteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetArtistsLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetArtistsLiteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetArtistsLiteEndpointTests(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 GetArtistsLite_WhenCalledWithoutPaginationData_ShouldReturnAllArtists()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedArtistAsync(libraryId, "Artist A");
|
||||
await SeedArtistAsync(libraryId, "Artist B");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedArtists);
|
||||
Assert.Equal(2, paginatedArtists!.Count);
|
||||
Assert.Equal(2, paginatedArtists.Data.Count);
|
||||
Assert.Contains(paginatedArtists.Data, artist => artist.Name == "Artist A");
|
||||
Assert.Contains(paginatedArtists.Data, artist => artist.Name == "Artist B");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistsLite_WhenNoArtistsExist_ShouldReturnEmptyPaginatedResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedArtists);
|
||||
Assert.Empty(paginatedArtists!.Data);
|
||||
Assert.Equal(0, paginatedArtists.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistsLite_WhenCalledWithFilterAlphaKeyLetter_ShouldReturnOnlyArtistsStartingWithThatLetter()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedArtistAsync(libraryId, "Queen");
|
||||
await SeedArtistAsync(libraryId, "The Queen");
|
||||
await SeedArtistAsync(libraryId, "Radiohead");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?filterAlphaKey=q");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedArtists);
|
||||
ArtistLiteResponse artist = Assert.Single(paginatedArtists!.Data);
|
||||
Assert.Equal("Queen", artist.Name);
|
||||
Assert.Equal(1, paginatedArtists.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistsLite_WhenCalledWithFilterAlphaKeyLetterAndIgnoreThePrefix_ShouldIncludeThePrefixedNames()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedArtistAsync(libraryId, "Queen");
|
||||
await SeedArtistAsync(libraryId, "The Queen");
|
||||
await SeedArtistAsync(libraryId, "Radiohead");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?filterAlphaKey=q&shouldIgnoreThePrefixForAlphaPicker=true");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedArtists);
|
||||
Assert.Equal(2, paginatedArtists!.Count);
|
||||
Assert.Contains(paginatedArtists.Data, artist => artist.Name == "Queen");
|
||||
Assert.Contains(paginatedArtists.Data, artist => artist.Name == "The Queen");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistsLite_WhenCalledWithFilterAlphaKeyNumber_ShouldReturnOnlyArtistsStartingWithADigit()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedArtistAsync(libraryId, "1984");
|
||||
await SeedArtistAsync(libraryId, "7th Sense");
|
||||
await SeedArtistAsync(libraryId, "Adele");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?filterAlphaKey=%23");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedArtists);
|
||||
Assert.Equal(2, paginatedArtists!.Count);
|
||||
Assert.Contains(paginatedArtists.Data, artist => artist.Name == "1984");
|
||||
Assert.Contains(paginatedArtists.Data, artist => artist.Name == "7th Sense");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistsLite_WhenCalledWithFilterAlphaKeySymbol_ShouldReturnOnlyArtistsStartingWithASymbol()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedArtistAsync(libraryId, "!Important");
|
||||
await SeedArtistAsync(libraryId, "1984");
|
||||
await SeedArtistAsync(libraryId, "Adele");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?filterAlphaKey=%2A");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedArtists);
|
||||
ArtistLiteResponse artist = Assert.Single(paginatedArtists!.Data);
|
||||
Assert.Equal("!Important", artist.Name);
|
||||
Assert.Equal(1, paginatedArtists.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistsLite_WhenCalledWithSearchTermAndFilterAlphaKey_ShouldReturnOnlyArtistsSatisfyingBothFilters()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
// The search term matches only one artist, while the alpha key matches only the other, so no artist satisfies both filters at once.
|
||||
await SeedArtistAsync(libraryId, "The Fellowship Band");
|
||||
await SeedArtistAsync(libraryId, "Zoo");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?searchTerm={Uri.EscapeDataString("Fellowship")}&filterAlphaKey=z");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedArtists);
|
||||
Assert.Empty(paginatedArtists!.Data);
|
||||
Assert.Equal(0, paginatedArtists.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistsLite_WhenSortedByNameAscending_ShouldReturnArtistsInAscendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedArtistAsync(libraryId, "Zulu");
|
||||
await SeedArtistAsync(libraryId, "Mike");
|
||||
await SeedArtistAsync(libraryId, "Alpha");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?sortBy=name&sortOrder=Ascending");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedArtists);
|
||||
Assert.Equal(new[] { "Alpha", "Mike", "Zulu" }, paginatedArtists!.Data.Select(artist => artist.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistsLite_WhenSortedByNameDescending_ShouldReturnArtistsInDescendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedArtistAsync(libraryId, "Zulu");
|
||||
await SeedArtistAsync(libraryId, "Mike");
|
||||
await SeedArtistAsync(libraryId, "Alpha");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?sortBy=name&sortOrder=Descending");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedArtists);
|
||||
Assert.Equal(new[] { "Zulu", "Mike", "Alpha" }, paginatedArtists!.Data.Select(artist => artist.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistsLite_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid libraryId = await SeedLibraryAsync(otherUserId);
|
||||
await SeedArtistAsync(libraryId, "Artist A");
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistsLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistsLite_WhenRouteIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/libraries/not-a-guid/artists/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist belonging to the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists;
|
||||
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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetDeletedArtistsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDeletedArtistsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDeletedArtistsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetDeletedArtistsEndpointTests(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 GetDeletedArtists_WhenLibraryHasDeletedArtists_ShouldReturnOnlyTheDeletedArtists()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
ArtistEntity deletedArtist = await SeedArtistAsync(libraryId, name: "Queen", isDeleted: true);
|
||||
await SeedArtistAsync(libraryId, name: "David Bowie", isDeleted: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
DeletedArtistResponse[]? artists = await response.Content.ReadFromJsonAsync<DeletedArtistResponse[]>(_jsonOptions);
|
||||
Assert.NotNull(artists);
|
||||
Assert.Single(artists);
|
||||
Assert.Equal(deletedArtist.Id, artists![0].Id);
|
||||
Assert.Equal(libraryId, artists[0].LibraryId);
|
||||
Assert.Equal("Queen", artists[0].Name);
|
||||
Assert.NotEqual(default, artists[0].DeletedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedArtists_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{otherLibraryId}/artists/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedArtists_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedArtists_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/artists/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist in the provided library, in the requested deletion state.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the artist.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <param name="isDeleted">Whether the artist is soft deleted.</param>
|
||||
/// <returns>The seeded artist.</returns>
|
||||
private async Task<ArtistEntity> SeedArtistAsync(Guid libraryId, string name, bool isDeleted)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false);
|
||||
artist.IsDeleted = isDeleted;
|
||||
artist.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null;
|
||||
dbContext.Artists.Add(artist);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artist;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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();
|
||||
}
|
||||
}
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist;
|
||||
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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RestoreArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RestoreArtistEndpointTests(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 RestoreArtist_WhenDeletedArtistBelongsToAnOwnedLibrary_ShouldRestoreTheArtist()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId, isDeleted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId);
|
||||
Assert.NotNull(artist);
|
||||
Assert.False(artist!.IsDeleted);
|
||||
Assert.Null(artist.DeletedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreArtist_WhenArtistIsNotDeleted_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId, isDeleted: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreArtist_WhenArtistIsRestoredThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId) = await SeedLibraryAndArtistAsync(userId, isDeleted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId) = await SeedLibraryAndArtistAsync(otherUserId, isDeleted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreArtist_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreArtist_WhenIdsAreNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync("/api/v1/libraries/not-a-guid/artists/not-a-guid/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/> and an artist of it, in the requested deletion state.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="isDeleted">Whether the seeded artist is soft deleted.</param>
|
||||
/// <returns>The Ids of the seeded library and artist.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId, bool isDeleted)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
|
||||
artist.IsDeleted = isDeleted;
|
||||
artist.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null;
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(artist);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artist.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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();
|
||||
}
|
||||
}
|
||||
+350
@@ -0,0 +1,350 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtist;
|
||||
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.AudioLibrary.MusicLibrary.Artists.UpdateArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly UpdateArtistRequestFixture _updateArtistRequestFixture = new();
|
||||
private readonly UpdateArtistAlbumRequestFixture _updateArtistAlbumRequestFixture = new();
|
||||
private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new();
|
||||
private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateArtistEndpointTests(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 UpdateArtist_WhenCalledByOwnerWithValidData_ShouldUpdateArtistAndPersistChanges()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
(Guid artistId, Guid albumId) = await SeedArtistWithAlbumAsync(libraryId);
|
||||
UpdateArtistAlbumRequest album = _updateArtistAlbumRequestFixture.Create(
|
||||
albumId: albumId,
|
||||
metadata: _musicAlbumMetadataDtoFixture.Create(title: "Updated Album"),
|
||||
contributors: [],
|
||||
ratings: [],
|
||||
tracks: []);
|
||||
UpdateArtistRequest request = _updateArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen Updated"), contributors: [], albums: [album]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ArtistResponse? artistResponse = JsonSerializer.Deserialize<ArtistResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(artistResponse);
|
||||
Assert.Equal(artistId, artistResponse!.Id);
|
||||
Assert.Equal("Queen Updated", artistResponse.Metadata.Name);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
ArtistEntity storedArtist = dbContext.Artists.Single(artist => artist.Id == artistId);
|
||||
Assert.Equal("Queen Updated", storedArtist.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtist_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
UpdateArtistRequest request = _updateArtistRequestFixture.Create();
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtist_WhenArtistRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
(Guid artistId, _) = await SeedArtistWithAlbumAsync(libraryId);
|
||||
UpdateArtistRequest request = _updateArtistRequestFixture.Create();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid libraryId = await SeedLibraryAsync(otherUserId);
|
||||
(Guid artistId, _) = await SeedArtistWithAlbumAsync(libraryId);
|
||||
UpdateArtistRequest request = _updateArtistRequestFixture.Create();
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
UpdateArtistRequest request = _updateArtistRequestFixture.Create();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtist_WhenNameIsMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
(Guid artistId, _) = await SeedArtistWithAlbumAsync(libraryId);
|
||||
UpdateArtistRequest request = _updateArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: string.Empty), contributors: [], albums: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistNameCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtist_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
UpdateArtistRequest request = _updateArtistRequestFixture.Create();
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist that owns a single album, both belonging to <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <returns>The Ids of the seeded artist and album.</returns>
|
||||
private async Task<(Guid artistId, Guid albumId)> SeedArtistWithAlbumAsync(Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+391
@@ -0,0 +1,391 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
|
||||
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.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateArtistCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateArtistCoverEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateArtistCoverEndpointTests(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 UpdateArtistCover_WhenCalledByOwnerWithValidImage_ShouldReplaceTheStoredCover()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistWithCoverAsync(userId, "/media/music/old-artist-cover.jpg");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
string storedPath = JsonSerializer.Deserialize<UpdateArtistCoverResponse>(content, _jsonOptions)!.CoverPath;
|
||||
Assert.False(string.IsNullOrWhiteSpace(storedPath));
|
||||
Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MusicArtworkEntity coverArtwork = dbContext.MusicArtwork
|
||||
.Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId && artwork.ArtworkType == ArtworkType.Cover);
|
||||
Assert.Equal(storedPath, coverArtwork.FileName);
|
||||
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenArtistHasNoExistingCover_ShouldCreateACoverArtwork()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
string storedPath = JsonSerializer.Deserialize<UpdateArtistCoverResponse>(content, _jsonOptions)!.CoverPath;
|
||||
Assert.False(string.IsNullOrWhiteSpace(storedPath));
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MusicArtworkEntity coverArtwork = dbContext.MusicArtwork
|
||||
.Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId && artwork.ArtworkType == ArtworkType.Cover);
|
||||
Assert.Equal(storedPath, coverArtwork.FileName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/cover";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenArtistRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId) = await SeedLibraryAndArtistAsync(userId);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/cover";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId) = await SeedLibraryAndArtistAsync(otherUserId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/cover";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PutAsync(url, CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenNoFileIsUploaded_ShouldReturnUnprocessableEntityWithCoverCannotBeNull()
|
||||
{
|
||||
// Arrange
|
||||
MultipartFormDataContent form = [];
|
||||
form.Add(new StringContent("unrelated-field"), "unrelated-field");
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync(url, form);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "CoverCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/not-a-guid/cover";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a multipart form carrying a minimal PNG-like payload.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>A configured <see cref="MultipartFormDataContent"/> instance.</returns>
|
||||
private static MultipartFormDataContent CreateCoverForm(string fileName)
|
||||
{
|
||||
// The payload only needs to carry the PNG signature in its first bytes and exceed the header detection buffer.
|
||||
byte[] payload = new byte[100];
|
||||
payload[0] = 137;
|
||||
payload[1] = 80;
|
||||
payload[2] = 78;
|
||||
payload[3] = 71;
|
||||
payload[4] = 13;
|
||||
payload[5] = 10;
|
||||
payload[6] = 26;
|
||||
payload[7] = 10;
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(payload);
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "cover", fileName);
|
||||
return form;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist that has no cover yet.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library and artist.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist that already has a cover.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="existingCoverFileName">The relative path of the existing cover of the artist.</param>
|
||||
/// <returns>The Ids of the seeded library and artist.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistWithCoverAsync(Guid userId, string existingCoverFileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistId, artworkType: ArtworkType.Cover, ordinal: 0, fileName: existingCoverFileName, status: ArtworkStatus.Enriched));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+1357
File diff suppressed because it is too large.
Load diff
+499
@@ -0,0 +1,499 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteTrackEndpointTests(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 DeleteTrack_WhenTrackBelongsToAnOwnedLibrary_ShouldSoftDeleteTheTrack()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Bohemian Rhapsody", "/music/queen/bohemian-rhapsody.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
TrackEntity? track = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId);
|
||||
Assert.NotNull(track);
|
||||
Assert.True(track!.IsDeleted);
|
||||
Assert.NotNull(track.DeletedOnUtc);
|
||||
// The album and the artist that contained the track are untouched.
|
||||
AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
|
||||
ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId);
|
||||
Assert.NotNull(album);
|
||||
Assert.False(album!.IsDeleted);
|
||||
Assert.NotNull(artist);
|
||||
Assert.False(artist!.IsDeleted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackHasStoredArtwork_ShouldKeepItsArtworkRecords()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Bohemian Rhapsody", "/music/queen/bohemian-rhapsody.flac");
|
||||
await SeedArtworkAsync(MusicArtworkOwnerType.Track, trackId, "media/music/queen/bohemian-rhapsody.jpg");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
// The track is soft deleted, so its artwork stays available until the user restores it.
|
||||
TrackEntity? track = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId);
|
||||
Assert.NotNull(track);
|
||||
Assert.True(track!.IsDeleted);
|
||||
Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("ArtistNotFound", problemDetails.Detail);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("AlbumNotFound", problemDetails.Detail);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackDoesNotExist_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackNotFound", problemDetails.Detail);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackRequestedThroughDifferentAlbum_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
Guid otherAlbumId = await SeedAlbumAsync(libraryId, artistId, "News of the World");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{otherAlbumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
// The route album id is enforced, so a track of another album is reported as not found, without disclosing that the track exists.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackRequestedThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
Guid otherArtistId = await SeedArtistAsync(libraryId, "Freddie Mercury");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{otherArtistId}/albums/{albumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
// The route artist id is enforced, so an album of another artist is reported as not found, without disclosing that it exists.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("AlbumNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
// The route library id is enforced, so an artist of another library is reported as not found, without disclosing that it exists.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("ArtistNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, Guid otherTrackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, "We Are the Champions", "/music/queen/news-of-the-world/we-are-the-champions.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks/{otherTrackId}");
|
||||
|
||||
// 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("General.Unauthorized", problemDetails!["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id reaches the command validator, which reports a clean validation error instead of failing the request binding.
|
||||
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("General.Validation", problemDetails!["title"].GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// 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("General.Validation", problemDetails!["title"].GetString());
|
||||
Assert.Contains("ArtistIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// 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("General.Validation", problemDetails!["title"].GetString());
|
||||
Assert.Contains("AlbumIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/not-a-guid");
|
||||
|
||||
// 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("General.Validation", problemDetails!["title"].GetString());
|
||||
Assert.Contains("TrackIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a piece of stored artwork owned by the music library item identified by <paramref name="ownerId"/>.
|
||||
/// </summary>
|
||||
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
|
||||
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
|
||||
/// <param name="fileName">The relative file name of the stored artwork.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="trackTitle">The title of the seeded track.</param>
|
||||
/// <param name="path">The file system path of the seeded track.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackTitle, string path)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
|
||||
dbContext.Albums.Add(CreateSeededAlbum(libraryId, artistId, albumId, "A Night at the Opera"));
|
||||
dbContext.Tracks.Add(CreateSeededTrack(libraryId, albumId, trackId, path, trackTitle));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an additional album belonging to the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the seeded album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
dbContext.Albums.Add(CreateSeededAlbum(libraryId, artistId, albumId, title));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an album to be seeded into the database.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The created album entity.</returns>
|
||||
private AlbumEntity CreateSeededAlbum(Guid libraryId, Guid artistId, Guid albumId, string title)
|
||||
{
|
||||
return _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a track to be seeded into the database.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <param name="path">The file system path of the track.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <returns>The created track entity.</returns>
|
||||
private TrackEntity CreateSeededTrack(Guid libraryId, Guid albumId, Guid trackId, string path, string title)
|
||||
{
|
||||
return _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
path: path,
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an additional artist belonging to the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the seeded artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: name));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user and its username.</returns>
|
||||
private async Task<(Guid userId, string username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetDeletedTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDeletedTracksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDeletedTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetDeletedTracksEndpointTests(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 GetDeletedTracks_WhenLibraryHasDeletedTracks_ShouldReturnOnlyTheDeletedTracks()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
|
||||
TrackEntity deletedTrack = await SeedTrackAsync(libraryId, albumId, title: "Bohemian Rhapsody", path: $"/music/queen/{Guid.NewGuid():N}.flac", isDeleted: true);
|
||||
await SeedTrackAsync(libraryId, albumId, title: "Love of My Life", path: $"/music/queen/{Guid.NewGuid():N}.flac", isDeleted: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/tracks/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
DeletedTrackResponse[]? tracks = await response.Content.ReadFromJsonAsync<DeletedTrackResponse[]>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Single(tracks);
|
||||
Assert.Equal(deletedTrack.Id, tracks![0].Id);
|
||||
Assert.Equal(libraryId, tracks[0].LibraryId);
|
||||
Assert.Equal(artistId, tracks[0].ArtistId);
|
||||
Assert.Equal("Queen", tracks[0].ArtistName);
|
||||
Assert.Equal(albumId, tracks[0].AlbumId);
|
||||
Assert.Equal("A Night at the Opera", tracks[0].AlbumTitle);
|
||||
Assert.Equal("Bohemian Rhapsody", tracks[0].Title);
|
||||
Assert.Equal(deletedTrack.Path, tracks[0].Path);
|
||||
Assert.NotEqual(default, tracks[0].DeletedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedTracks_WhenTrackBelongsToDeletedAlbum_ShouldNotReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
|
||||
await SeedTrackAsync(libraryId, albumId, title: "Bohemian Rhapsody", path: $"/music/queen/{Guid.NewGuid():N}.flac", isDeleted: true);
|
||||
await SoftDeleteAlbumAsync(albumId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/tracks/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
DeletedTrackResponse[]? tracks = await response.Content.ReadFromJsonAsync<DeletedTrackResponse[]>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Empty(tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedTracks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{otherLibraryId}/tracks/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/tracks/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedTracks_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/tracks/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, an artist of it and an album of the artist.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: "A Night at the Opera",
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, album.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of the provided album, in the requested deletion state.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the track.</param>
|
||||
/// <param name="albumId">The Id of the album that owns the track.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <param name="path">The file system path of the track.</param>
|
||||
/// <param name="isDeleted">Whether the track is soft deleted.</param>
|
||||
/// <returns>The seeded track.</returns>
|
||||
private async Task<TrackEntity> SeedTrackAsync(Guid libraryId, Guid albumId, string title, string path, bool isDeleted)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
path: path,
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
track.IsDeleted = isDeleted;
|
||||
track.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null;
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return track;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Soft deletes the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="albumId">The Id of the album to soft delete.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SoftDeleteAlbumAsync(Guid albumId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
AlbumEntity album = await dbContext.Albums.FirstAsync(album => album.Id == albumId);
|
||||
album.IsDeleted = true;
|
||||
album.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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();
|
||||
}
|
||||
}
|
||||
+347
@@ -0,0 +1,347 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
|
||||
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPlaybackManifestEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaybackManifestEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter() }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackManifestEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPlaybackManifestEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client of the test.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenTrackBelongsToAnOwnedLibrary_ShouldReturnDirectPlayManifest()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(
|
||||
userId,
|
||||
container: "FLAC",
|
||||
audioCodec: "FLAC",
|
||||
replayGainTrackGain: -7.5m,
|
||||
replayGainTrackPeak: 0.9877m,
|
||||
replayGainAlbumGain: -6.8m,
|
||||
replayGainAlbumPeak: 0.9999m);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PlaybackManifestResponse? manifest = await ReadManifestAsync(response);
|
||||
Assert.NotNull(manifest);
|
||||
Assert.Equal(trackId, manifest!.TrackId);
|
||||
Assert.True(manifest.IsDirectPlay);
|
||||
Assert.Equal("FLAC", manifest.SourceContainer);
|
||||
Assert.Equal("FLAC", manifest.SourceCodec);
|
||||
Assert.Equal(-7.5m, manifest.ReplayGainTrackGain);
|
||||
Assert.Equal(0.9877m, manifest.ReplayGainTrackPeak);
|
||||
Assert.Equal(-6.8m, manifest.ReplayGainAlbumGain);
|
||||
Assert.Equal(0.9999m, manifest.ReplayGainAlbumPeak);
|
||||
Assert.Null(manifest.DeliveryContainer);
|
||||
Assert.Null(manifest.DeliveryCodec);
|
||||
Assert.Null(manifest.DeliveryShape);
|
||||
Assert.Null(manifest.SegmentDurationSeconds);
|
||||
Assert.True(manifest.IsSeekable);
|
||||
Assert.Equal($"/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream", manifest.StreamPath);
|
||||
Assert.DoesNotContain("http", manifest.StreamPath, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Null(manifest.DeliveryId);
|
||||
Assert.Null(manifest.SegmentStreamPathTemplate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenPlayerCannotDecodeTheStoredCodec_ShouldReturnTranscodedDelivery()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, container: "OGG", audioCodec: "OPUS");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PlaybackManifestResponse? manifest = await ReadManifestAsync(response);
|
||||
Assert.NotNull(manifest);
|
||||
Assert.Equal(trackId, manifest!.TrackId);
|
||||
Assert.False(manifest.IsDirectPlay);
|
||||
Assert.Equal("MP3", manifest.DeliveryContainer);
|
||||
Assert.Equal("MP3", manifest.DeliveryCodec);
|
||||
Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, manifest.DeliveryShape);
|
||||
Assert.Equal(6, manifest.SegmentDurationSeconds);
|
||||
Assert.True(manifest.IsSeekable);
|
||||
Assert.NotNull(manifest.DeliveryId);
|
||||
Assert.Matches("^[0-9a-f]{32}$", manifest.DeliveryId);
|
||||
Assert.Equal(BuildExpectedSegmentStreamPathTemplate(libraryId, artistId, albumId, trackId), manifest.SegmentStreamPathTemplate);
|
||||
Assert.DoesNotContain("http", manifest.SegmentStreamPathTemplate, StringComparison.OrdinalIgnoreCase);
|
||||
string cacheControl = string.Join(", ", response.Headers.GetValues("Cache-Control"));
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.Contains("Authorization", response.Headers.Vary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenTheSameTrackIsRequestedTwice_ShouldReuseTheSameDeliveryId()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, container: "OGG", audioCodec: "OPUS");
|
||||
string requestPath = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await _client.GetAsync(requestPath);
|
||||
HttpResponseMessage secondResponse = await _client.GetAsync(requestPath);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
|
||||
PlaybackManifestResponse? firstManifest = await ReadManifestAsync(firstResponse);
|
||||
PlaybackManifestResponse? secondManifest = await ReadManifestAsync(secondResponse);
|
||||
Assert.NotNull(firstManifest);
|
||||
Assert.NotNull(secondManifest);
|
||||
Assert.NotNull(firstManifest!.DeliveryId);
|
||||
Assert.Equal(firstManifest.DeliveryId, secondManifest!.DeliveryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenTheTranscodedResponseIsReread_ShouldKeepAWellFormedDeliveryId()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, container: "OGG", audioCodec: "OPUS");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Act
|
||||
using JsonDocument firstRead = JsonDocument.Parse(content);
|
||||
string? deliveryIdFromFirstRead = firstRead.RootElement.GetProperty("deliveryId").GetString();
|
||||
PlaybackManifestResponse? secondRead = JsonSerializer.Deserialize<PlaybackManifestResponse>(content, _jsonOptions);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(deliveryIdFromFirstRead);
|
||||
Assert.Matches("^[0-9a-f]{32}$", deliveryIdFromFirstRead);
|
||||
Assert.NotNull(secondRead);
|
||||
Assert.Equal(deliveryIdFromFirstRead, secondRead!.DeliveryId);
|
||||
Assert.Matches("^[0-9a-f]{32}$", secondRead.DeliveryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenTrackIsRequestedThroughDifferentAlbum_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, container: "FLAC", audioCodec: "FLAC");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/{trackId}/playback-manifest");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = await ReadProblemDetailsAsync(response);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, container: "FLAC", audioCodec: "FLAC");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(await response.Content.ReadAsStringAsync(), _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="container">The container of the audio file of the seeded track.</param>
|
||||
/// <param name="audioCodec">The codec of the audio of the seeded track.</param>
|
||||
/// <param name="replayGainTrackGain">Optional. The ReplayGain track gain of the seeded track, in decibels.</param>
|
||||
/// <param name="replayGainTrackPeak">Optional. The ReplayGain track peak of the seeded track.</param>
|
||||
/// <param name="replayGainAlbumGain">Optional. The ReplayGain album gain of the seeded track, in decibels.</param>
|
||||
/// <param name="replayGainAlbumPeak">Optional. The ReplayGain album peak of the seeded track.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(
|
||||
Guid userId,
|
||||
string container,
|
||||
string audioCodec,
|
||||
decimal? replayGainTrackGain = null,
|
||||
decimal? replayGainTrackPeak = null,
|
||||
decimal? replayGainAlbumGain = null,
|
||||
decimal? replayGainAlbumPeak = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera"));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
container: container,
|
||||
audioCodec: audioCodec,
|
||||
title: "A Track",
|
||||
includeMetadata: false,
|
||||
replayGainTrackGain: replayGainTrackGain,
|
||||
replayGainTrackPeak: replayGainTrackPeak,
|
||||
replayGainAlbumGain: replayGainAlbumGain,
|
||||
replayGainAlbumPeak: replayGainAlbumPeak));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user and its username.</returns>
|
||||
private async Task<(Guid userId, string username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the segment stream path template the manifest is expected to report for a track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <returns>The expected segment stream path template, with its placeholders preserved.</returns>
|
||||
private static string BuildExpectedSegmentStreamPathTemplate(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return ApiRoutes.Tracks.STREAM_TRACK_SEGMENT
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the playback manifest of a response.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized playback manifest.</returns>
|
||||
private async Task<PlaybackManifestResponse?> ReadManifestAsync(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<PlaybackManifestResponse>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the problem details of a response.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized problem details.</returns>
|
||||
private async Task<Microsoft.AspNetCore.Mvc.ProblemDetails?> ReadProblemDetailsAsync(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test user created for the tests.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+363
@@ -0,0 +1,363 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrack;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetTrackEndpointTests(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 GetTrack_WhenTrackBelongsToAnOwnedLibrary_ShouldReturnTrackDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Bohemian Rhapsody", "/music/queen/bohemian-rhapsody.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
TrackResponse? track = JsonSerializer.Deserialize<TrackResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(track);
|
||||
Assert.Equal(trackId, track!.Id);
|
||||
Assert.Equal(albumId, track.AlbumId);
|
||||
Assert.Equal(libraryId, track.LibraryId);
|
||||
Assert.Equal("/music/queen/bohemian-rhapsody.flac", track.Path);
|
||||
Assert.Equal("Bohemian Rhapsody", track.Metadata.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenTrackDoesNotExist_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackNotFound", problemDetails.Detail);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("AlbumNotFound", problemDetails.Detail);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenTrackRequestedThroughDifferentAlbum_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
Guid otherAlbumId = await SeedAlbumAsync(libraryId, artistId, "News of the World");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{otherAlbumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
// The route album id is enforced, so a track of another album is reported as not found, without disclosing that the track exists.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenTrackRequestedThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
// The route artist id is enforced, so an album of another artist is reported as not found, without disclosing that it exists.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("AlbumNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenTrackRequestedThroughDifferentLibrary_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Love of My Life", "/music/queen/a-night-at-the-opera/love-of-my-life.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
|
||||
// Assert
|
||||
// The route library id is enforced, so an album of another library is reported as not found, without disclosing that it exists.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("AlbumNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, Guid otherTrackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, "We Are the Champions", "/music/queen/news-of-the-world/we-are-the-champions.flac");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks/{otherTrackId}");
|
||||
|
||||
// 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("General.Unauthorized", problemDetails!["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding.
|
||||
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("General.Validation", problemDetails!["title"].GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// 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("General.Validation", problemDetails!["title"].GetString());
|
||||
Assert.Contains("ArtistIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid/tracks/{Guid.NewGuid()}");
|
||||
|
||||
// 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("General.Validation", problemDetails!["title"].GetString());
|
||||
Assert.Contains("AlbumIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrack_WhenTrackIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/not-a-guid");
|
||||
|
||||
// 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("General.Validation", problemDetails!["title"].GetString());
|
||||
Assert.Contains("TrackIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="trackTitle">The title of the seeded track.</param>
|
||||
/// <param name="path">The file system path of the seeded track.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackTitle, string path)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera"));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: path, title: trackTitle, includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an additional album belonging to the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the seeded album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: title));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user and its username.</returns>
|
||||
private async Task<(Guid userId, string username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
+368
@@ -0,0 +1,368 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
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.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTrackSegmentEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The successful production path of a segment is not exercised here, because it requires ffmpeg, which is not part of the test environment. Every
|
||||
/// covered case is rejected before the normalization pipeline is entered, so these tests are deterministic and environment independent.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTrackSegmentEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly string _contentRootPath = Path.Combine(Path.GetTempPath(), $"lumina-track-segment-tests-{Guid.NewGuid():N}");
|
||||
private readonly List<string> _temporaryFiles = [];
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededArtistIds = [];
|
||||
private readonly List<Guid> _seededAlbumIds = [];
|
||||
private readonly List<Guid> _seededTrackIds = [];
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter() }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackSegmentEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetTrackSegmentEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client and the temporary content root of the test.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
Directory.CreateDirectory(_contentRootPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrackSegment_WhenUnauthorized_ShouldReturnUnauthorizedResultWithoutLeakingTheDeliveryHandle()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string trackPath = WriteContentFile("bohemian-rhapsody.ogg", CreateAudioBytes());
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
|
||||
string deliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, deliveryId, 0));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
// The request path is echoed by the problem details, so the handle the caller sent appears there; no other handle may be disclosed.
|
||||
string[] disclosedHandleCandidates = [.. System.Text.RegularExpressions.Regex.Matches(content, "[0-9a-f]{32}").Select(match => match.Value)];
|
||||
Assert.All(disclosedHandleCandidates, candidate => Assert.Equal(deliveryId, candidate));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("uppercase")] // The handle format only accepts lowercase hexadecimal characters.
|
||||
[InlineData("dashed")] // The handle format is the N format of a GUID, without dashes.
|
||||
public async Task GetTrackSegment_WhenDeliveryIdFormatIsInvalid_ShouldReturnValidationProblem(string malformedHandleKind)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string trackPath = WriteContentFile("love-of-my-life.ogg", CreateAudioBytes());
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
|
||||
string validDeliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
|
||||
string malformedDeliveryId = malformedHandleKind switch
|
||||
{
|
||||
"uppercase" => validDeliveryId.ToUpperInvariant(),
|
||||
_ => Guid.Parse(validDeliveryId).ToString("D"),
|
||||
};
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, malformedDeliveryId, 0));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
Assert.Contains(
|
||||
"DeliveryIdIsInvalid",
|
||||
problemDetails.RootElement.GetProperty("errors").GetProperty("General.Validation").EnumerateArray().Select(error => error.GetString()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrackSegment_WhenDeliveryIdIsUnknown_ShouldReturnPlaybackDeliveryNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string trackPath = WriteContentFile("you-re-my-best-friend.ogg", CreateAudioBytes());
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
|
||||
string unknownDeliveryId = Guid.NewGuid().ToString("N");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, unknownDeliveryId, 0));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = await ReadProblemDetailsAsync(response);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("PlaybackDeliveryNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("library")] // The handle was issued for the library of another delivery.
|
||||
[InlineData("artist")] // The handle was issued for the artist of another delivery.
|
||||
[InlineData("album")] // The handle was issued for the album of another delivery.
|
||||
public async Task GetTrackSegment_WhenDeliveryWasIssuedForAnotherScope_ShouldReturnPlaybackDeliveryNotFound(string mismatchedScope)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string trackPath = WriteContentFile("news-of-the-world.ogg", CreateAudioBytes());
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
|
||||
string deliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
|
||||
// A second library owned by the same user keeps the ownership check passing, so the delivery scope is what rejects the request.
|
||||
Guid otherLibraryId = await SeedLibraryAsync(userId);
|
||||
Guid requestedLibraryId = mismatchedScope == "library" ? otherLibraryId : libraryId;
|
||||
Guid requestedArtistId = mismatchedScope == "artist" ? Guid.NewGuid() : artistId;
|
||||
Guid requestedAlbumId = mismatchedScope == "album" ? Guid.NewGuid() : albumId;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(requestedLibraryId, requestedArtistId, requestedAlbumId, trackId, deliveryId, 0));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = await ReadProblemDetailsAsync(response);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("PlaybackDeliveryNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrackSegment_WhenTrackFileIsOutsideTheLibraryContentLocations_ShouldReturnTrackFileNotFoundWithoutLeakingThePath()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string outsideFilePath = Path.Combine(Path.GetTempPath(), $"lumina-track-segment-outside-{Guid.NewGuid():N}.ogg");
|
||||
await File.WriteAllBytesAsync(outsideFilePath, CreateAudioBytes());
|
||||
_temporaryFiles.Add(outsideFilePath);
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, outsideFilePath);
|
||||
string deliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, deliveryId, 0));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(outsideFilePath, content, StringComparison.OrdinalIgnoreCase);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackFileNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="trackPath">The file system path of the audio file of the track.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackPath)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [_contentRootPath]));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera"));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
path: trackPath,
|
||||
container: "OGG",
|
||||
audioCodec: "OPUS",
|
||||
title: "A Track",
|
||||
includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
_seededArtistIds.Add(artistId);
|
||||
_seededAlbumIds.Add(albumId);
|
||||
_seededTrackIds.Add(trackId);
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an additional music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [_contentRootPath]));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Requests a transcoded playback manifest for the seeded track and returns the delivery handle it reports.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <returns>The delivery handle of the normalized delivery.</returns>
|
||||
private async Task<string> GetDeliveryIdAsync(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3");
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PlaybackManifestResponse? manifest = JsonSerializer.Deserialize<PlaybackManifestResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(manifest);
|
||||
Assert.NotNull(manifest!.DeliveryId);
|
||||
return manifest.DeliveryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the route of a single segment of the normalized audio of a track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <param name="deliveryId">The opaque handle of the normalized delivery.</param>
|
||||
/// <param name="segmentIndex">The zero based index of the segment.</param>
|
||||
/// <returns>The route of the requested segment.</returns>
|
||||
private static string BuildSegmentPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId, string deliveryId, int segmentIndex)
|
||||
{
|
||||
return $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes an audio file with the provided <paramref name="audioBytes"/> inside the content root of the test, and returns its full path.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the audio file to write.</param>
|
||||
/// <param name="audioBytes">The bytes of the audio file to write.</param>
|
||||
/// <returns>The full path of the written audio file.</returns>
|
||||
private string WriteContentFile(string fileName, byte[] audioBytes)
|
||||
{
|
||||
string filePath = Path.Combine(_contentRootPath, fileName);
|
||||
File.WriteAllBytes(filePath, audioBytes);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic byte array that stands in for the content of an audio file.
|
||||
/// </summary>
|
||||
/// <returns>The created bytes.</returns>
|
||||
private static byte[] CreateAudioBytes()
|
||||
{
|
||||
return [.. Enumerable.Range(0, 4096).Select(index => (byte)(index % 256))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the problem details of a response.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized problem details.</returns>
|
||||
private async Task<Microsoft.AspNetCore.Mvc.ProblemDetails?> ReadProblemDetailsAsync(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Cleans up the seeded database rows, the temporary files and the test user of the test.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
foreach (Guid trackId in _seededTrackIds)
|
||||
{
|
||||
TrackEntity? track = dbContext.Tracks.Find(trackId);
|
||||
if (track is not null)
|
||||
dbContext.Tracks.Remove(track);
|
||||
}
|
||||
foreach (Guid albumId in _seededAlbumIds)
|
||||
{
|
||||
AlbumEntity? album = dbContext.Albums.Find(albumId);
|
||||
if (album is not null)
|
||||
dbContext.Albums.Remove(album);
|
||||
}
|
||||
foreach (Guid artistId in _seededArtistIds)
|
||||
{
|
||||
ArtistEntity? artist = dbContext.Artists.Find(artistId);
|
||||
if (artist is not null)
|
||||
dbContext.Artists.Remove(artist);
|
||||
}
|
||||
foreach (Guid libraryId in _seededLibraryIds)
|
||||
{
|
||||
LibraryEntity? library = dbContext.Libraries.Find(libraryId);
|
||||
if (library is not null)
|
||||
dbContext.Libraries.Remove(library);
|
||||
}
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
if (Directory.Exists(_contentRootPath))
|
||||
Directory.Delete(_contentRootPath, recursive: true);
|
||||
foreach (string temporaryFile in _temporaryFiles)
|
||||
if (File.Exists(temporaryFile))
|
||||
File.Delete(temporaryFile);
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTrackStreamEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTrackStreamEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly string _contentRootPath = Path.Combine(Path.GetTempPath(), $"lumina-track-stream-tests-{Guid.NewGuid():N}");
|
||||
private readonly List<string> _temporaryFiles = [];
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackStreamEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetTrackStreamEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client and the temporary content root of the test.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
Directory.CreateDirectory(_contentRootPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrackStream_WhenTrackBelongsToAnOwnedLibrary_ShouldStreamTheWholeAudioFile()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
byte[] audioBytes = CreateAudioBytes();
|
||||
string trackPath = WriteContentFile("bohemian-rhapsody.mp3", audioBytes);
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("audio/mpeg", response.Content.Headers.ContentType?.MediaType);
|
||||
Assert.Equal(audioBytes.Length, response.Content.Headers.ContentLength!.Value);
|
||||
Assert.Contains("bytes", response.Headers.AcceptRanges);
|
||||
Assert.NotNull(response.Headers.ETag);
|
||||
Assert.NotNull(response.Content.Headers.LastModified);
|
||||
Assert.Contains("nosniff", response.Headers.GetValues("X-Content-Type-Options"));
|
||||
Assert.Contains("private", response.Headers.CacheControl?.ToString());
|
||||
Assert.Contains("Authorization", response.Headers.Vary);
|
||||
Assert.Equal(audioBytes, await response.Content.ReadAsByteArrayAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrackStream_WhenARangeIsRequested_ShouldStreamOnlyTheRequestedRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
byte[] audioBytes = CreateAudioBytes();
|
||||
string trackPath = WriteContentFile("love-of-my-life.mp3", audioBytes);
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream");
|
||||
request.Headers.Range = new RangeHeaderValue(100, 199);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.SendAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode);
|
||||
Assert.Equal("audio/mpeg", response.Content.Headers.ContentType?.MediaType);
|
||||
Assert.Equal(100L, response.Content.Headers.ContentLength!.Value);
|
||||
Assert.Contains("bytes", response.Headers.AcceptRanges);
|
||||
Assert.Equal(100L, response.Content.Headers.ContentRange!.From!.Value);
|
||||
Assert.Equal(199L, response.Content.Headers.ContentRange!.To!.Value);
|
||||
Assert.Equal((long)audioBytes.Length, response.Content.Headers.ContentRange!.Length!.Value);
|
||||
Assert.Equal(audioBytes[100..200], await response.Content.ReadAsByteArrayAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrackStream_WhenTrackIsRequestedThroughDifferentAlbum_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string trackPath = WriteContentFile("you-re-my-best-friend.mp3", CreateAudioBytes());
|
||||
(Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/{trackId}/stream");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = await ReadProblemDetailsAsync(response);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrackStream_WhenAudioFileIsMissing_ShouldReturnTrackFileNotFoundProblemWithoutLeakingThePath()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string trackPath = Path.Combine(_contentRootPath, "missing-file.mp3");
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(trackPath, content, StringComparison.OrdinalIgnoreCase);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackFileNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrackStream_WhenAudioFileIsOutsideTheLibraryContentLocations_ShouldReturnTrackFileNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
byte[] audioBytes = CreateAudioBytes();
|
||||
string outsideFilePath = Path.Combine(Path.GetTempPath(), $"lumina-track-stream-outside-{Guid.NewGuid():N}.mp3");
|
||||
await File.WriteAllBytesAsync(outsideFilePath, audioBytes);
|
||||
_temporaryFiles.Add(outsideFilePath);
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, outsideFilePath);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(outsideFilePath, content, StringComparison.OrdinalIgnoreCase);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackFileNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrackStream_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
string trackPath = WriteContentFile("news-of-the-world.mp3", CreateAudioBytes());
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, trackPath);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(await response.Content.ReadAsStringAsync(), _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrackStream_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="trackPath">The file system path of the seeded track.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackPath)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [_contentRootPath]));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera"));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: trackPath, title: "A Track", includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user and its username.</returns>
|
||||
private async Task<(Guid userId, string username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes an audio file with the provided <paramref name="audioBytes"/> inside the content root of the test, and returns its full path.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the audio file to write.</param>
|
||||
/// <param name="audioBytes">The bytes of the audio file to write.</param>
|
||||
/// <returns>The full path of the written audio file.</returns>
|
||||
private string WriteContentFile(string fileName, byte[] audioBytes)
|
||||
{
|
||||
string filePath = Path.Combine(_contentRootPath, fileName);
|
||||
File.WriteAllBytes(filePath, audioBytes);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic byte array that stands in for the content of an audio file.
|
||||
/// </summary>
|
||||
/// <returns>The created bytes.</returns>
|
||||
private static byte[] CreateAudioBytes()
|
||||
{
|
||||
return [.. Enumerable.Range(0, 4096).Select(index => (byte)(index % 256))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the problem details of a response.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized problem details.</returns>
|
||||
private async Task<Microsoft.AspNetCore.Mvc.ProblemDetails?> ReadProblemDetailsAsync(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <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 and the temporary files of the test.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
if (Directory.Exists(_contentRootPath))
|
||||
Directory.Delete(_contentRootPath, recursive: true);
|
||||
foreach (string temporaryFile in _temporaryFiles)
|
||||
{
|
||||
if (File.Exists(temporaryFile))
|
||||
File.Delete(temporaryFile);
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack;
|
||||
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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RestoreTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RestoreTrackEndpointTests(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 RestoreTrack_WhenDeletedTrackBelongsToAnOwnedAlbum_ShouldRestoreTheTrack()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, isDeleted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
TrackEntity? track = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId);
|
||||
Assert.NotNull(track);
|
||||
Assert.False(track!.IsDeleted);
|
||||
Assert.Null(track.DeletedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTrack_WhenTrackIsNotDeleted_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, isDeleted: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTrack_WhenTrackIsRestoredThroughDifferentLibrary_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, isDeleted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTrack_WhenTrackIsRestoredThroughDifferentAlbum_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, isDeleted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/{trackId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTrack_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, Guid otherTrackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, isDeleted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks/{otherTrackId}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTrack_WhenTrackDoesNotExist_ShouldReturnTrackNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTrack_WhenIdsAreNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync("/api/v1/libraries/not-a-guid/artists/not-a-guid/albums/not-a-guid/tracks/not-a-guid/restore", null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, an artist of it, an album of the artist and a track of the album, in the requested deletion state.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="isDeleted">Whether the seeded track is soft deleted.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, bool isDeleted)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
path: $"/music/queen/{Guid.NewGuid():N}.flac",
|
||||
title: "Bohemian Rhapsody",
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
track.IsDeleted = isDeleted;
|
||||
track.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null;
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: "A Night at the Opera",
|
||||
tracks: [track],
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, album.Id, track.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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();
|
||||
}
|
||||
}
|
||||
+483
@@ -0,0 +1,483 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
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.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ShuffleTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ShuffleTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ShuffleTracksEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenLibraryHasTracks_ShouldReturnTheTracksWithAllTheirFields()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Queen Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
Guid trackId = await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
|
||||
Guid otherTrackId = await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219);
|
||||
await SeedAlbumCoverAsync(albumId, "a-night-at-the-opera-cover.jpg");
|
||||
// A second library proves that the response is scoped to the library in the route.
|
||||
Guid otherLibraryId = await SeedLibraryAsync(userId, "Other Library");
|
||||
Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "ABBA");
|
||||
Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Arrival");
|
||||
Guid otherLibraryTrackId = await SeedTrackAsync(otherLibraryId, otherAlbumId, "Dancing Queen", 231);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, 10);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<ShuffleTrackResponse>? tracks = JsonSerializer.Deserialize<List<ShuffleTrackResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Equal(2, tracks!.Count);
|
||||
Assert.All(tracks, track => Assert.Contains(track.TrackId, new[] { trackId, otherTrackId }));
|
||||
Assert.DoesNotContain(tracks, track => track.TrackId == otherLibraryTrackId);
|
||||
ShuffleTrackResponse foundTrack = Assert.Single(tracks, track => track.TrackId == trackId);
|
||||
Assert.Equal("Bohemian Rhapsody", foundTrack.Title);
|
||||
Assert.Equal(355, foundTrack.DurationInSeconds);
|
||||
Assert.Equal(albumId, foundTrack.AlbumId);
|
||||
Assert.Equal("A Night at the Opera", foundTrack.AlbumTitle);
|
||||
Assert.Equal(artistId, foundTrack.ArtistId);
|
||||
Assert.Equal("a-night-at-the-opera-cover.jpg", foundTrack.CoverPath);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenArtistIdIsProvided_ShouldReturnOnlyTracksOfAlbumsOfThatArtist()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Two Artists Library");
|
||||
Guid firstArtistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid firstAlbumId = await SeedAlbumAsync(libraryId, firstArtistId, "A Night at the Opera");
|
||||
await SeedTrackAsync(libraryId, firstAlbumId, "Bohemian Rhapsody", 355);
|
||||
await SeedTrackAsync(libraryId, firstAlbumId, "Love of My Life", 219);
|
||||
Guid secondArtistId = await SeedArtistAsync(libraryId, "David Bowie");
|
||||
Guid secondAlbumId = await SeedAlbumAsync(libraryId, secondArtistId, "Heroes");
|
||||
await SeedTrackAsync(libraryId, secondAlbumId, "Heroes", 371);
|
||||
await SeedTrackAsync(libraryId, secondAlbumId, "Beauty and the Beast", 212);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, 10, artistId: firstArtistId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<ShuffleTrackResponse>? tracks = JsonSerializer.Deserialize<List<ShuffleTrackResponse>>(
|
||||
await response.Content.ReadAsStringAsync(), _jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Equal(2, tracks!.Count);
|
||||
Assert.All(tracks, track => Assert.Equal(firstArtistId, track.ArtistId));
|
||||
Assert.All(tracks, track => Assert.Equal(firstAlbumId, track.AlbumId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenAlbumIdIsProvided_ShouldReturnOnlyTracksOfThatAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Two Albums Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
|
||||
await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219);
|
||||
Guid otherAlbumId = await SeedAlbumAsync(libraryId, artistId, "News of the World");
|
||||
await SeedTrackAsync(libraryId, otherAlbumId, "We Are the Champions", 179);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, 10, albumId: albumId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<ShuffleTrackResponse>? tracks = JsonSerializer.Deserialize<List<ShuffleTrackResponse>>(
|
||||
await response.Content.ReadAsStringAsync(), _jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Equal(2, tracks!.Count);
|
||||
Assert.All(tracks, track => Assert.Equal(albumId, track.AlbumId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenExcludedTrackIdsAreProvided_ShouldNeverReturnThem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Exclusion Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
Guid firstTrackId = await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
|
||||
Guid secondTrackId = await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219);
|
||||
Guid thirdTrackId = await SeedTrackAsync(libraryId, albumId, "The Prophet Song", 367);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(
|
||||
libraryId, 10, excludedTrackIds: [firstTrackId, secondTrackId]);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<ShuffleTrackResponse>? tracks = JsonSerializer.Deserialize<List<ShuffleTrackResponse>>(
|
||||
await response.Content.ReadAsStringAsync(), _jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
ShuffleTrackResponse track = Assert.Single(tracks!);
|
||||
Assert.Equal(thirdTrackId, track.TrackId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenCountIsLowerThanTheAvailableTracks_ShouldReturnAtMostCountTracks()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Count Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
for (int index = 0; index < 5; index++)
|
||||
await SeedTrackAsync(libraryId, albumId, $"Track {index}", 200 + index);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, 2);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<ShuffleTrackResponse>? tracks = JsonSerializer.Deserialize<List<ShuffleTrackResponse>>(
|
||||
await response.Content.ReadAsStringAsync(), _jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Equal(2, tracks!.Count);
|
||||
Assert.Equal(tracks.Count, tracks.Select(track => track.TrackId).Distinct().Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenCountIsLargerThanTheAvailableTracks_ShouldReturnEveryAvailableTrack()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Small Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
Guid firstTrackId = await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
|
||||
Guid secondTrackId = await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, 50);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<ShuffleTrackResponse>? tracks = JsonSerializer.Deserialize<List<ShuffleTrackResponse>>(
|
||||
await response.Content.ReadAsStringAsync(), _jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Equal(2, tracks!.Count);
|
||||
Assert.Contains(tracks, track => track.TrackId == firstTrackId);
|
||||
Assert.Contains(tracks, track => track.TrackId == secondTrackId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, "ShuffleTrackCountMustBeGreaterThanZero")] // No track is requested.
|
||||
[InlineData(-1, "ShuffleTrackCountMustBeGreaterThanZero")] // A negative selection size.
|
||||
[InlineData(501, "ShuffleTrackCountMustBeAtMost500")] // One more than the documented maximum.
|
||||
public async Task ShuffleTracks_WhenCountIsInvalid_ShouldReturnUnprocessableEntityWithTheValidationError(int count, string expectedError)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Validation Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, count);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.Validation", problemDetails!["title"].GetString());
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails["status"].GetInt32());
|
||||
JsonElement errors = problemDetails["errors"];
|
||||
Assert.True(errors.TryGetProperty("General.Validation", out JsonElement validationErrors));
|
||||
Assert.Contains(validationErrors.EnumerateArray(), error => error.GetString() == expectedError);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenWithoutTrackData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, string otherUsername) = await SeedOtherUserAsync();
|
||||
Guid libraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
await SeedTrackAsync(libraryId, albumId, "Secret Song", 300);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, 10);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Secret Song", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.False(string.IsNullOrWhiteSpace(otherUsername));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Posts a shuffle request for the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library whose tracks are shuffled.</param>
|
||||
/// <param name="count">The maximum number of tracks to return.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist whose tracks are sampled.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album whose tracks are sampled.</param>
|
||||
/// <param name="excludedTrackIds">Optional. The tracks that must not be returned.</param>
|
||||
/// <returns>The response of the API.</returns>
|
||||
private async Task<HttpResponseMessage> PostShuffleAsync(
|
||||
Guid libraryId,
|
||||
int count,
|
||||
Guid? artistId = null,
|
||||
Guid? albumId = null,
|
||||
IReadOnlyCollection<Guid>? excludedTrackIds = null)
|
||||
{
|
||||
return await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{libraryId}/tracks/shuffle",
|
||||
new { count, artistId, albumId, excludedTrackIds });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(
|
||||
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Albums.Add(album);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <param name="durationInSeconds">The duration of the track in seconds.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title, int durationInSeconds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
path: $"/music/shuffle-{Guid.NewGuid():N}.flac",
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
track.DurationInSeconds = durationInSeconds;
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the cover artwork of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="albumId">The Id of the album that owns the artwork.</param>
|
||||
/// <param name="fileName">The file name of the stored cover.</param>
|
||||
private async Task SeedAlbumCoverAsync(Guid albumId, string fileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album,
|
||||
ownerId: albumId,
|
||||
artworkType: ArtworkType.Cover,
|
||||
ordinal: 0,
|
||||
fileName: fileName,
|
||||
status: ArtworkStatus.Enriched));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id and the username of the seeded user.</returns>
|
||||
private async Task<(Guid userId, string username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
foreach (Guid libraryId in _seededLibraryIds)
|
||||
{
|
||||
List<Guid> albumIds = await dbContext.Albums
|
||||
.Where(album => album.LibraryId == libraryId)
|
||||
.Select(album => album.Id)
|
||||
.ToListAsync();
|
||||
dbContext.MusicArtwork.RemoveRange(dbContext.MusicArtwork.Where(artwork => albumIds.Contains(artwork.OwnerId)));
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => track.LibraryId == libraryId));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => album.LibraryId == libraryId));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => artist.LibraryId == libraryId));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => library.Id == libraryId));
|
||||
}
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+1244
File diff suppressed because it is too large.
Load diff
+540
@@ -0,0 +1,540 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
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.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;
|
||||
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 AddLibraryRequestFixture _addLibraryRequestFixture = new();
|
||||
private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new();
|
||||
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 = _addLibraryRequestFixture.Create(
|
||||
title: "New Library",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldSkipHiddenFilesAndDirectoriesDuringScan: 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);
|
||||
Assert.True(library.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
|
||||
|
||||
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);
|
||||
Assert.True(storedLibrary.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddLibrary_WhenCalledByRegularUser_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: "New Library",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: 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()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddLibrary_WhenConsumptionSettingsAreSupplied_ShouldPersistAndReturnThem()
|
||||
{
|
||||
// Arrange
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: "Tracked Library",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 90
|
||||
);
|
||||
|
||||
// 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.True(library!.ShouldTrackConsumptionProgress);
|
||||
Assert.Equal(90, library.CompletionThresholdPercentage);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
|
||||
Assert.NotNull(storedLibrary);
|
||||
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
|
||||
Assert.Equal(90, storedLibrary.CompletionThresholdPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddLibrary_WhenConsumptionSettingsAreOmitted_ShouldUseTheLibraryTypeDefaults()
|
||||
{
|
||||
// Arrange
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: "Default Consumption Library",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldTrackConsumptionProgress: null,
|
||||
completionThresholdPercentage: null
|
||||
);
|
||||
|
||||
// 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.True(library!.ShouldTrackConsumptionProgress);
|
||||
Assert.Equal(100, library.CompletionThresholdPercentage);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
|
||||
Assert.NotNull(storedLibrary);
|
||||
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
|
||||
Assert.Equal(100, storedLibrary.CompletionThresholdPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddLibrary_WhenLibraryTypeDoesNotTrackConsumptionByDefault_ShouldStoreTrackingOffWithoutThreshold()
|
||||
{
|
||||
// Arrange
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: "Music Library",
|
||||
libraryType: "Music",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldTrackConsumptionProgress: null,
|
||||
completionThresholdPercentage: null
|
||||
);
|
||||
|
||||
// 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(LibraryType.Music, library!.LibraryType);
|
||||
Assert.False(library.ShouldTrackConsumptionProgress);
|
||||
Assert.Null(library.CompletionThresholdPercentage);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
|
||||
Assert.NotNull(storedLibrary);
|
||||
Assert.False(storedLibrary!.ShouldTrackConsumptionProgress);
|
||||
Assert.Null(storedLibrary.CompletionThresholdPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddLibrary_WhenProgressTrackingIsExplicitlyDisabled_ShouldStoreTrackingOffWithoutThreshold()
|
||||
{
|
||||
// Arrange
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: "Untracked Library",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldTrackConsumptionProgress: false,
|
||||
completionThresholdPercentage: null
|
||||
);
|
||||
|
||||
// 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.False(library!.ShouldTrackConsumptionProgress);
|
||||
Assert.Null(library.CompletionThresholdPercentage);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
|
||||
Assert.NotNull(storedLibrary);
|
||||
Assert.False(storedLibrary!.ShouldTrackConsumptionProgress);
|
||||
Assert.Null(storedLibrary.CompletionThresholdPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddLibrary_WhenThresholdIsAboveOneHundred_ShouldReturnValidationProblemAndNotPersist()
|
||||
{
|
||||
// Arrange
|
||||
string title = "Above Range Library";
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: title,
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 101
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred");
|
||||
|
||||
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_WhenThresholdIsBelowZero_ShouldReturnValidationProblemAndNotPersist()
|
||||
{
|
||||
// Arrange
|
||||
string title = "Below Range Library";
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: title,
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: -1
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred");
|
||||
|
||||
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_WhenThresholdIsSuppliedWhileProgressTrackingIsDisabled_ShouldReturnValidationProblemAndNotPersist()
|
||||
{
|
||||
// Arrange
|
||||
string title = "Disabled Tracking Library";
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: title,
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldTrackConsumptionProgress: false,
|
||||
completionThresholdPercentage: 50
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff");
|
||||
|
||||
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_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>
|
||||
/// <param name="response">The response to assert.</param>
|
||||
/// <param name="expectedErrorDescription">The error description expected under the validation errors.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedErrorDescription)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
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());
|
||||
Assert.Equal("/api/v1/libraries", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorDescription, errors["General.Validation"]);
|
||||
}
|
||||
|
||||
/// <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();
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
#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 async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
#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 async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
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.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;
|
||||
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) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
|
||||
private readonly LibraryScanResultEntityFixture _libraryScanResultEntityFixture = new();
|
||||
private readonly LibraryScanStagingResultsEntityFixture _libraryScanStagingResultsEntityFixture = new();
|
||||
private readonly LibraryScanSnapshotEntityFixture _libraryScanSnapshotEntityFixture = new();
|
||||
private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new();
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
|
||||
private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new();
|
||||
|
||||
/// <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(AuthorizationPermission.CanCreateLibraries);
|
||||
}
|
||||
|
||||
[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_WhenTheLibraryHasRelatedData_ShouldDeleteTheRelatedData()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid scanId = Guid.NewGuid();
|
||||
await SeedLibraryWithRelatedDataAsync(libraryId, userId, scanId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Null(await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId));
|
||||
Assert.False(await dbContext.LibraryScans.AnyAsync(scan => scan.LibraryId == libraryId));
|
||||
Assert.False(await dbContext.LibraryScanResults.AnyAsync(result => result.LibraryScanId == scanId));
|
||||
Assert.False(await dbContext.LibraryScanStagingResults.AnyAsync(result => result.LibraryScanId == scanId));
|
||||
Assert.False(await dbContext.LibraryScanSnapshots.AnyAsync(snapshot => snapshot.LibraryId == libraryId));
|
||||
Assert.False(await dbContext.DirectoryScanFingerprints.AnyAsync(fingerprint => fingerprint.LibraryId == libraryId));
|
||||
Assert.False(await dbContext.LibraryMetadataProviderConfigurations.AnyAsync(configuration => configuration.LibraryId == libraryId));
|
||||
Assert.False(await dbContext.LibraryArtworkProviderConfigurations.AnyAsync(configuration => configuration.LibraryId == libraryId));
|
||||
Assert.False(await dbContext.LibraryBookReaderConfigurations.AnyAsync(configuration => configuration.LibraryId == libraryId));
|
||||
}
|
||||
|
||||
[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="LibraryEntity"/> together with the data that belongs to it.
|
||||
/// </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="scanId">The Id of the library scan to seed.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryWithRelatedDataAsync(Guid libraryId, Guid userId, Guid scanId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []);
|
||||
dbContext.Libraries.Add(library);
|
||||
dbContext.LibraryScans.Add(_libraryScanEntityFixture.Create(id: scanId, libraryId: libraryId, userId: userId, libraryEntity: library));
|
||||
dbContext.LibraryScanResults.Add(_libraryScanResultEntityFixture.Create(libraryScanId: scanId));
|
||||
dbContext.LibraryScanStagingResults.Add(_libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId));
|
||||
dbContext.LibraryScanSnapshots.Add(_libraryScanSnapshotEntityFixture.Create(libraryId: libraryId));
|
||||
dbContext.DirectoryScanFingerprints.Add(_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId));
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 0));
|
||||
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 0));
|
||||
dbContext.LibraryBookReaderConfigurations.Add(_libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <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(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
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(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
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();
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.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.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) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <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(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.EBook, contentLocations: [], 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();
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.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.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) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <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(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
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(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.EBook, contentLocations: []));
|
||||
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();
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.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.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) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <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(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.EBook, contentLocations: []));
|
||||
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();
|
||||
}
|
||||
}
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetLibraryPathTemplatePartsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryPathTemplatePartsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly LibraryPathPartDefinitionResponseFixture _libraryPathPartDefinitionResponseFixture = new();
|
||||
private readonly LibraryPathTemplatePartResponseFixture _libraryPathTemplatePartResponseFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryPathTemplatePartsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetLibraryPathTemplatePartsEndpointTests(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 GetLibraryPathTemplateParts_WhenLibraryTypeIsMusic_ShouldReturnMusicCatalog()
|
||||
{
|
||||
// Arrange
|
||||
List<LibraryPathPartDefinitionResponse> expectedParts = GetExpectedMusicParts();
|
||||
List<LibraryPathTemplatePartResponse> expectedDefaultTemplateParts = GetExpectedMusicDefaultTemplateParts();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/path-template-parts/Music");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
LibraryPathTemplateCatalogResponse? catalog = await response.Content.ReadFromJsonAsync<LibraryPathTemplateCatalogResponse>(_jsonOptions);
|
||||
Assert.NotNull(catalog);
|
||||
Assert.Equal(10, catalog!.Parts.Count);
|
||||
Assert.Equal(16, catalog.DefaultTemplateParts.Count);
|
||||
Assert.Equal(expectedParts, catalog.Parts);
|
||||
Assert.Equal(expectedDefaultTemplateParts, catalog.DefaultTemplateParts);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryPathTemplateParts_WhenLibraryTypeIsBook_ShouldReturnBookCatalog()
|
||||
{
|
||||
// Arrange
|
||||
List<LibraryPathPartDefinitionResponse> expectedParts = GetExpectedBookParts();
|
||||
List<LibraryPathTemplatePartResponse> expectedDefaultTemplateParts = GetExpectedBookDefaultTemplateParts();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/path-template-parts/Book");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
LibraryPathTemplateCatalogResponse? catalog = await response.Content.ReadFromJsonAsync<LibraryPathTemplateCatalogResponse>(_jsonOptions);
|
||||
Assert.NotNull(catalog);
|
||||
Assert.Equal(8, catalog!.Parts.Count);
|
||||
Assert.Equal(12, catalog.DefaultTemplateParts.Count);
|
||||
Assert.Equal(expectedParts, catalog.Parts);
|
||||
Assert.Equal(expectedDefaultTemplateParts, catalog.DefaultTemplateParts);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryPathTemplateParts_WhenLibraryTypeHasNoCatalog_ShouldReturnEmptyCatalog()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/path-template-parts/Movie");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
LibraryPathTemplateCatalogResponse? catalog = await response.Content.ReadFromJsonAsync<LibraryPathTemplateCatalogResponse>(_jsonOptions);
|
||||
Assert.NotNull(catalog);
|
||||
Assert.Empty(catalog!.Parts);
|
||||
Assert.Empty(catalog.DefaultTemplateParts);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryPathTemplateParts_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
string libraryType = "NotARealLibraryType";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/path-template-parts/{libraryType}");
|
||||
|
||||
// Assert
|
||||
// An unrecognized library type is a value that is not accepted, so it is reported as forbidden.
|
||||
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(6, problemDetails!.Count);
|
||||
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("UnknownLibraryType", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/libraries/path-template-parts/{libraryType}", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the exact path parts expected for a music library, as defined by <c>MusicLibraryPathPartCatalog</c>.
|
||||
/// </summary>
|
||||
/// <returns>The expected path parts, in catalog order.</returns>
|
||||
private List<LibraryPathPartDefinitionResponse> GetExpectedMusicParts()
|
||||
{
|
||||
return
|
||||
[
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "Literal", valueType: "None", defaultRepresentation: string.Empty, isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "Separator", valueType: "None", defaultRepresentation: string.Empty, isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "Artist", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "ReleaseType", valueType: "Enum", defaultRepresentation: "{0}", isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "ReleaseYear", valueType: "Year", defaultRepresentation: "{0}", isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "ReleaseName", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "TrackNumber", valueType: "Integer", defaultRepresentation: "{0:00}", isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "TrackName", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "Extension", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "DiscNumber", valueType: "Integer", defaultRepresentation: "{0:00}", isOptionalByDefault: true)
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the exact default template parts expected for a music library, as defined by <c>MusicLibraryPathPartCatalog</c>.
|
||||
/// </summary>
|
||||
/// <returns>The expected default template parts, in template order.</returns>
|
||||
private List<LibraryPathTemplatePartResponse> GetExpectedMusicDefaultTemplateParts()
|
||||
{
|
||||
return
|
||||
[
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Artist", representation: "{0}", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "ReleaseType", representation: "{0}", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "ReleaseYear", representation: "{0}", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: " - ", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "ReleaseName", representation: "{0}", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: true),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: "Disk ", isOptional: true),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "DiscNumber", representation: "{0:00}", isOptional: true),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "TrackNumber", representation: "{0:00}", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: " - ", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "TrackName", representation: "{0}", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: ".", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Extension", representation: "{0}", isOptional: false)
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the exact path parts expected for a book library, as defined by <c>BookLibraryPathPartCatalog</c>.
|
||||
/// </summary>
|
||||
/// <returns>The expected path parts, in catalog order.</returns>
|
||||
private List<LibraryPathPartDefinitionResponse> GetExpectedBookParts()
|
||||
{
|
||||
return
|
||||
[
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "Literal", valueType: "None", defaultRepresentation: string.Empty, isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "Separator", valueType: "None", defaultRepresentation: string.Empty, isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "Author", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "Title", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "Series", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: true),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "SeriesNumber", valueType: "Integer", defaultRepresentation: "{0}", isOptionalByDefault: true),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "BookId", valueType: "Integer", defaultRepresentation: "{0}", isOptionalByDefault: false),
|
||||
_libraryPathPartDefinitionResponseFixture.Create(kind: "Extension", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false)
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the exact default template parts expected for a book library, as defined by <c>BookLibraryPathPartCatalog</c>.
|
||||
/// </summary>
|
||||
/// <returns>The expected default template parts, in template order.</returns>
|
||||
private List<LibraryPathTemplatePartResponse> GetExpectedBookDefaultTemplateParts()
|
||||
{
|
||||
return
|
||||
[
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Author", representation: "{0}", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Title", representation: "{0}", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: " (", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "BookId", representation: "{0}", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: ")", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Title", representation: "{0}", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: " - ", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Author", representation: "{0}", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: ".", isOptional: false),
|
||||
_libraryPathTemplatePartResponseFixture.Create(kind: "Extension", representation: "{0}", isOptional: false)
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
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) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <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(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
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();
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#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 async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.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.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) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <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(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
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();
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.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.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) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <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(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [], isEnabled: isEnabled, isLocked: isLocked));
|
||||
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();
|
||||
}
|
||||
}
|
||||
+574
@@ -0,0 +1,574 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
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;
|
||||
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) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new();
|
||||
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
|
||||
private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new();
|
||||
|
||||
/// <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(AuthorizationPermission.CanCreateLibraries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateLibrary_WhenLibraryExists_ShouldUpdateIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId, "Original Title");
|
||||
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
seedDbContext.DirectoryScanFingerprints.Add(_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/fingerprint"));
|
||||
await seedDbContext.SaveChangesAsync();
|
||||
}
|
||||
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
|
||||
id: libraryId,
|
||||
title: "Updated Title",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldSkipHiddenFilesAndDirectoriesDuringScan: 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);
|
||||
Assert.True(library.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
|
||||
|
||||
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);
|
||||
Assert.True(storedLibrary.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
|
||||
Assert.False(await dbContext.DirectoryScanFingerprints.AnyAsync(fingerprint => fingerprint.LibraryId == libraryId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateLibrary_WhenHiddenFilesSettingIsAbsent_ShouldKeepTheStoredValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldSkipHiddenFilesAndDirectoriesDuringScan: true);
|
||||
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
seedDbContext.DirectoryScanFingerprints.Add(_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/fingerprint"));
|
||||
await seedDbContext.SaveChangesAsync();
|
||||
}
|
||||
Dictionary<string, object?> request = new()
|
||||
{
|
||||
["id"] = libraryId,
|
||||
["title"] = "Updated Title",
|
||||
["libraryType"] = "EBook",
|
||||
["contentLocations"] = new[] { "C:/Media" },
|
||||
["coverImage"] = null,
|
||||
["isEnabled"] = true,
|
||||
["isLocked"] = false,
|
||||
["canDownloadMetadataFromWeb"] = true,
|
||||
["shouldSaveMetadataInMediaDirectories"] = false,
|
||||
["shouldSkipUnchangedDirectoriesDuringScan"] = false,
|
||||
["isContentOnSsd"] = false,
|
||||
["shouldTrackConsumptionProgress"] = null,
|
||||
["completionThresholdPercentage"] = null,
|
||||
["pathTemplateParts"] = null,
|
||||
["metadataProviders"] = null,
|
||||
["artworkProviders"] = null,
|
||||
["bookReaders"] = null
|
||||
};
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
|
||||
Assert.NotNull(library);
|
||||
Assert.True(library!.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
|
||||
|
||||
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.True(storedLibrary!.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
|
||||
Assert.True(await dbContext.DirectoryScanFingerprints.AnyAsync(fingerprint => fingerprint.LibraryId == libraryId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateLibrary_WhenLibraryDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
|
||||
id: libraryId,
|
||||
title: "Updated Title",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: 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()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateLibrary_WhenConsumptionSettingsAreSupplied_ShouldPersistAndReturnThem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: false, completionThresholdPercentage: null);
|
||||
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
|
||||
id: libraryId,
|
||||
title: "Updated Title",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 70
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
|
||||
Assert.NotNull(library);
|
||||
Assert.True(library!.ShouldTrackConsumptionProgress);
|
||||
Assert.Equal(70, library.CompletionThresholdPercentage);
|
||||
|
||||
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.True(storedLibrary!.ShouldTrackConsumptionProgress);
|
||||
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateLibrary_WhenConsumptionSettingsAreOmitted_ShouldKeepTheStoredSettings()
|
||||
{
|
||||
// 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,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldTrackConsumptionProgress: null,
|
||||
completionThresholdPercentage: null
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
|
||||
Assert.NotNull(library);
|
||||
Assert.True(library!.ShouldTrackConsumptionProgress);
|
||||
Assert.Equal(70, library.CompletionThresholdPercentage);
|
||||
|
||||
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.True(storedLibrary!.ShouldTrackConsumptionProgress);
|
||||
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateLibrary_WhenProgressTrackingIsDisabled_ShouldClearTheStoredThreshold()
|
||||
{
|
||||
// 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,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldTrackConsumptionProgress: false,
|
||||
completionThresholdPercentage: null
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
|
||||
Assert.NotNull(library);
|
||||
Assert.False(library!.ShouldTrackConsumptionProgress);
|
||||
Assert.Null(library.CompletionThresholdPercentage);
|
||||
|
||||
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.False(storedLibrary!.ShouldTrackConsumptionProgress);
|
||||
Assert.Null(storedLibrary.CompletionThresholdPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateLibrary_WhenTrackingIsEnabledWithoutThreshold_ShouldUseTheLibraryTypeDefault()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: false, completionThresholdPercentage: null);
|
||||
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
|
||||
id: libraryId,
|
||||
title: "Updated Title",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: null
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
|
||||
Assert.NotNull(library);
|
||||
Assert.True(library!.ShouldTrackConsumptionProgress);
|
||||
Assert.Equal(100, library.CompletionThresholdPercentage);
|
||||
|
||||
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.True(storedLibrary!.ShouldTrackConsumptionProgress);
|
||||
Assert.Equal(100, storedLibrary.CompletionThresholdPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateLibrary_WhenThresholdIsAboveOneHundred_ShouldReturnValidationProblemAndKeepTheStoredSettings()
|
||||
{
|
||||
// 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,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 101
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, $"/api/v1/libraries/{libraryId}", "CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred");
|
||||
|
||||
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.True(storedLibrary!.ShouldTrackConsumptionProgress);
|
||||
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateLibrary_WhenThresholdIsSuppliedWhileProgressTrackingIsDisabled_ShouldReturnValidationProblemAndKeepTheStoredSettings()
|
||||
{
|
||||
// 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,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldTrackConsumptionProgress: false,
|
||||
completionThresholdPercentage: 50
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, $"/api/v1/libraries/{libraryId}", "CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff");
|
||||
|
||||
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.True(storedLibrary!.ShouldTrackConsumptionProgress);
|
||||
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>
|
||||
/// <param name="response">The response to assert.</param>
|
||||
/// <param name="expectedInstance">The expected instance path of the problem.</param>
|
||||
/// <param name="expectedErrorDescription">The error description expected under the validation errors.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorDescription)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
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());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorDescription, errors["General.Validation"]);
|
||||
}
|
||||
|
||||
/// <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="shouldTrackConsumptionProgress">Whether the seeded library tracks the consumption progress of its items.</param>
|
||||
/// <param name="completionThresholdPercentage">The completion threshold percentage of the seeded library, if any.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(
|
||||
Guid libraryId,
|
||||
Guid userId,
|
||||
string title,
|
||||
bool shouldTrackConsumptionProgress = false,
|
||||
int? completionThresholdPercentage = null,
|
||||
bool shouldSkipHiddenFilesAndDirectoriesDuringScan = false)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId,
|
||||
userId: userId,
|
||||
title: title,
|
||||
libraryType: LibraryType.EBook,
|
||||
contentLocations: [],
|
||||
shouldSkipHiddenFilesAndDirectoriesDuringScan: shouldSkipHiddenFilesAndDirectoriesDuringScan,
|
||||
shouldTrackConsumptionProgress: shouldTrackConsumptionProgress,
|
||||
completionThresholdPercentage: completionThresholdPercentage));
|
||||
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();
|
||||
}
|
||||
}
|
||||
+357
@@ -0,0 +1,357 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
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.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearConsumptionHistoryEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 5, 8, 20, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 5, 9, 5, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearConsumptionHistoryEndpointTests(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 ClearConsumptionHistory_WhenUserHasHistory_ShouldDeleteEveryRecordOfTheCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(15));
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/consumption-history");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(firstRecordId, secondRecordId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenCalled_ShouldPreserveTheCurrentUsersResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, firstLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId, Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/consumption-history");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(recordId);
|
||||
await AssertResumePointsArePreservedAsync(firstResumePointId, secondResumePointId, otherUserResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenUserHasNoHistory_ShouldSucceedWithoutSideEffects()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/consumption-history");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertConsumptionRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
if (storedRecords.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedRecords);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
|
||||
// that completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
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.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearUserConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearUserConsumptionHistoryEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 6, 12, 10, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 6, 12, 55, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearUserConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearUserConsumptionHistoryEndpointTests(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 ClearUserConsumptionHistory_WhenCurrentUserNamesThemselves_ShouldDeleteEveryRecordOfTheCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(20));
|
||||
string url = $"/api/v1/users/{userId}/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(firstRecordId, secondRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecords()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(20));
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(firstRecordId, secondRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenAdminNamesAnotherUser_ShouldDeleteEveryRecordOfThatUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(targetUserId, targetLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(targetUserId, targetLibraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(20));
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
string url = $"/api/v1/users/{targetUserId}/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(firstRecordId, secondRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenUserIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertConsumptionRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
if (storedRecords.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedRecords);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, 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(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+389
@@ -0,0 +1,389 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
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.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 7, 21, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 7, 21, 35, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearResumePointsEndpointTests(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 ClearResumePoints_WhenLibraryIdIsSupplied_ShouldDeleteOnlyTheCurrentUsersResumePointsInThatLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, firstLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId, Guid.NewGuid());
|
||||
string url = $"/api/v1/users/me/media-resume-points?libraryId={firstLibraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(firstResumePointId);
|
||||
await AssertResumePointsArePreservedAsync(secondResumePointId, otherUserResumePointId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenLibraryIdIsOmitted_ShouldDeleteEveryResumePointOfTheCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, firstLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId, Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/media-resume-points");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(firstResumePointId, secondResumePointId);
|
||||
await AssertResumePointsArePreservedAsync(otherUserResumePointId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenLibraryIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/media-resume-points";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be deleted.</param>
|
||||
private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
if (storedResumePoints.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedResumePoints);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
|
||||
// that completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+458
@@ -0,0 +1,458 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
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.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearUserResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearUserResumePointsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 8, 10, 30, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 8, 11, 10, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearUserResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearUserResumePointsEndpointTests(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 ClearUserResumePoints_WhenCurrentUserNamesThemselves_ShouldDeleteEveryResumePoint()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, firstLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/{userId}/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(firstResumePointId, secondResumePointId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenLibraryIdIsSupplied_ShouldDeleteOnlyThatLibrarysResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, firstLibraryId, Guid.NewGuid());
|
||||
string url = $"/api/v1/users/{userId}/media-resume-points?libraryId={firstLibraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(firstResumePointId);
|
||||
await AssertResumePointsArePreservedAsync(secondResumePointId, otherUserResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId, Guid.NewGuid());
|
||||
string url = $"/api/v1/users/{otherUserId}/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsArePreservedAsync(otherUserResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid targetResumePointId = await SeedResumePointAsync(targetUserId, targetLibraryId, Guid.NewGuid());
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
string url = $"/api/v1/users/{targetUserId}/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(targetResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenUserIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenLibraryIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/media-resume-points";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be deleted.</param>
|
||||
private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
if (storedResumePoints.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedResumePoints);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
|
||||
// that completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, 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(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+425
@@ -0,0 +1,425 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
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.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteConsumptionItemHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionItemHistoryEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 2, 20, 15, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 2, 20, 45, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteConsumptionItemHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
_seededUsernames.Add(_apiFactory.TestUsername!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenItemHasRecords_ShouldDeleteOnlyTheMatchingRecords()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Other User Library");
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 90_000);
|
||||
Guid otherItemRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, Guid.NewGuid(), 60_000);
|
||||
Guid movedLibraryRecordId = await SeedConsumptionRecordAsync(userId, otherLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
|
||||
Guid otherKindRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.Book, mediaItemId, 60_000);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other Owner Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
|
||||
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertRecordsAreDeletedAsync(firstRecordId, secondRecordId);
|
||||
await AssertRecordsArePreservedAsync(otherItemRecordId, movedLibraryRecordId, otherKindRecordId, otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenCalled_ShouldReturnEmptyDeletedBody()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
|
||||
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument document = JsonDocument.Parse(content);
|
||||
Assert.Equal(JsonValueKind.Object, document.RootElement.ValueKind);
|
||||
Assert.Empty(document.RootElement.EnumerateObject());
|
||||
await AssertRecordsAreDeletedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenItemHasNoRecords_ShouldSucceedWithoutSideEffects()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
|
||||
Guid existingRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, Guid.NewGuid(), 60_000);
|
||||
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{libraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertRecordsArePreservedAsync(existingRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenCalledTwice_ShouldSucceedAndStayDeleted()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
|
||||
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await _client.DeleteAsync(url);
|
||||
await AssertRecordsAreDeletedAsync(recordId);
|
||||
HttpResponseMessage secondResponse = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
|
||||
AssertCacheHeaders(secondResponse);
|
||||
await AssertRecordsAreDeletedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.None)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(path);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenMediaItemIdIsEmpty_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.Empty}/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(path);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "MediaItemIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenLibraryIdIsEmpty_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.Empty}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(path);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
long consumedDurationMilliseconds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 45_000,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: mediaKind == MediaKind.Book ? 10 : 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
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>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
if (storedRecords.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedRecords);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes every user created by the test, together with the libraries it owns.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
foreach (string username in _seededUsernames)
|
||||
{
|
||||
UserEntity? user = dbContext.Users
|
||||
.Include(candidate => candidate.Libraries)
|
||||
.FirstOrDefault(candidate => candidate.Username == username);
|
||||
if (user is null)
|
||||
continue;
|
||||
dbContext.Libraries.RemoveRange(user.Libraries);
|
||||
dbContext.Users.Remove(user);
|
||||
}
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+456
@@ -0,0 +1,456 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
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.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteUserConsumptionItemHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteUserConsumptionItemHistoryEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 3, 18, 5, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 3, 18, 40, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteUserConsumptionItemHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteUserConsumptionItemHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
_seededUsernames.Add(_apiFactory.TestUsername!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionItemHistory_WhenCurrentUserNamesThemselves_ShouldDeleteTheItemRecords()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 90_000);
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertRecordsAreDeletedAsync(firstRecordId, secondRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionItemHistory_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecords()
|
||||
{
|
||||
// Arrange
|
||||
_ = GetCurrentUserId();
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other User Library");
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{otherUserLibraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionItemHistory_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersItemRecords()
|
||||
{
|
||||
// Arrange
|
||||
_ = GetCurrentUserId();
|
||||
Guid targetUserId = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.Music, "Target User Library");
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid targetRecordId = await SeedConsumptionRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
|
||||
string url = $"/api/v1/users/{targetUserId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{targetLibraryId}";
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
_seededUsernames.Add(_apiFactory.TestUsername!);
|
||||
|
||||
try
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertRecordsAreDeletedAsync(targetRecordId);
|
||||
}
|
||||
finally
|
||||
{
|
||||
adminClient.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionItemHistory_WhenTargetUserDoesNotOwnTheItem_ShouldSucceedAndPreserveThatUsersRecords()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
|
||||
Guid ownRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, Guid.NewGuid(), 60_000);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other User Library");
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{otherUserLibraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertRecordsArePreservedAsync(ownRecordId, otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionItemHistory_WhenCalledTwice_ShouldSucceedAndStayDeleted()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await _client.DeleteAsync(url);
|
||||
await AssertRecordsAreDeletedAsync(recordId);
|
||||
HttpResponseMessage secondResponse = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
|
||||
AssertCacheHeaders(secondResponse);
|
||||
await AssertRecordsAreDeletedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionItemHistory_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = $"/api/v1/users/not-a-guid/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(path);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "TargetUserIdIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionItemHistory_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/media-items/{nameof(MediaKind.None)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(path);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionItemHistory_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
long consumedDurationMilliseconds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 45_000,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: mediaKind == MediaKind.Book ? 10 : 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
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>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
if (storedRecords.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedRecords);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, 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(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes every user created by the test, together with the libraries it owns.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
foreach (string username in _seededUsernames)
|
||||
{
|
||||
UserEntity? user = dbContext.Users
|
||||
.Include(candidate => candidate.Libraries)
|
||||
.FirstOrDefault(candidate => candidate.Username == username);
|
||||
if (user is null)
|
||||
continue;
|
||||
dbContext.Libraries.RemoveRange(user.Libraries);
|
||||
dbContext.Users.Remove(user);
|
||||
}
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+418
@@ -0,0 +1,418 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
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.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteConsumptionRecordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionRecordEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 2, 20, 15, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 2, 20, 45, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionRecordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteConsumptionRecordEndpointTests(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 DeleteConsumptionRecord_WhenRecordBelongsToCurrentUser_ShouldDeleteOnlyThatRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid otherRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(10));
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/me/consumption-history/{recordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(recordId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherRecordId, otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenRecordBelongsToAnotherUser_ShouldSucceedAndPreserveThatUsersRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/me/consumption-history/{otherUserRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenRecordDoesNotExist_ShouldSucceedWithoutSideEffects()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid existingRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/me/consumption-history/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(existingRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenRecordIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/me/consumption-history/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenCalled_ShouldPreserveTheUsersResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId, Guid.NewGuid());
|
||||
string url = $"/api/v1/users/me/consumption-history/{recordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(recordId);
|
||||
await AssertResumePointsArePreservedAsync(resumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/me/consumption-history/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertConsumptionRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
if (storedRecords.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedRecords);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
|
||||
// that completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+401
@@ -0,0 +1,401 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
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.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteUserConsumptionRecordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteUserConsumptionRecordEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 3, 18, 5, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 3, 18, 40, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteUserConsumptionRecordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteUserConsumptionRecordEndpointTests(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 DeleteUserConsumptionRecord_WhenCurrentUserNamesThemselves_ShouldDeleteTheRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/{recordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-history/{otherUserRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid targetRecordId = await SeedConsumptionRecordAsync(targetUserId, targetLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
string url = $"/api/v1/users/{targetUserId}/consumption-history/{targetRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(targetRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenRecordBelongsToAnotherUser_ShouldSucceedAndPreserveThatUsersRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid ownRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/{otherUserRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(ownRecordId, otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenUserIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/not-a-guid/consumption-history/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenRecordIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertConsumptionRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
if (storedRecords.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedRecords);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, 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(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+567
@@ -0,0 +1,567 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAllUsersConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAllUsersConsumptionStatisticsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_musicStartedOnUtc = new(2026, 3, 10, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookStartedOnUtc = new(2026, 2, 10, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAllUsersConsumptionStatisticsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated admin API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenCalledByAdmin_ShouldReturnPerUserSummariesAndCombinedTotals()
|
||||
{
|
||||
// Arrange
|
||||
(Guid firstUserId, Guid firstUserLibraryId) = await SeedMusicOnlyUserAsync();
|
||||
(Guid secondUserId, Guid secondUserLibraryId) = await SeedBookOnlyUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
|
||||
ConsumptionSummaryResponse firstUser = Assert.Single(statistics!.Users, summary => summary.UserId == firstUserId);
|
||||
Assert.Equal(100d, firstUser.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, firstUser.CountedSessionCount);
|
||||
Assert.Equal(1, firstUser.CompletedSessionCount);
|
||||
Assert.Equal(1, firstUser.StoppedSessionCount);
|
||||
Assert.Equal(0.5, firstUser.CompletionRate, 6);
|
||||
MediaKindConsumptionSummaryResponse firstUserMusic = Assert.Single(firstUser.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, firstUserMusic.MediaKind);
|
||||
Assert.Equal(100d, firstUserMusic.TotalConsumedDurationInSeconds, 3);
|
||||
|
||||
ConsumptionSummaryResponse secondUser = Assert.Single(statistics.Users, summary => summary.UserId == secondUserId);
|
||||
Assert.Equal(400d, secondUser.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, secondUser.CountedSessionCount);
|
||||
Assert.Equal(1, secondUser.CompletedSessionCount);
|
||||
Assert.Equal(0, secondUser.StoppedSessionCount);
|
||||
Assert.Equal(1d, secondUser.CompletionRate, 6);
|
||||
MediaKindConsumptionSummaryResponse secondUserBook = Assert.Single(secondUser.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.Book, secondUserBook.MediaKind);
|
||||
Assert.Equal(400d, secondUserBook.TotalConsumedDurationInSeconds, 3);
|
||||
|
||||
Assert.Equal(statistics.Users.Select(summary => summary.UserId).Order().ToArray(), statistics.Users.Select(summary => summary.UserId).ToArray());
|
||||
Assert.NotEqual(firstUserLibraryId, secondUserLibraryId);
|
||||
AssertTotalsMatchUsers(statistics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenCalledByRegularUser_ShouldReturnForbiddenWithExactShape()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient regularClient = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
string url = "/api/v1/users/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await regularClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.False(problemDetails!.ContainsKey("users"));
|
||||
Assert.False(problemDetails.ContainsKey("total"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenRestrictedToOneLibrary_ShouldReturnOnlyTheUsersOfThatLibrary()
|
||||
{
|
||||
// Arrange
|
||||
(Guid firstUserId, Guid firstUserLibraryId) = await SeedMusicOnlyUserAsync();
|
||||
await SeedBookOnlyUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/consumption-statistics?libraryId={firstUserLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
ConsumptionSummaryResponse user = Assert.Single(statistics!.Users);
|
||||
Assert.Equal(firstUserId, user.UserId);
|
||||
Assert.Equal(100d, user.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(100d, statistics.Total.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, statistics.Total.CountedSessionCount);
|
||||
Assert.Equal(1, statistics.Total.CompletedSessionCount);
|
||||
Assert.Equal(1, statistics.Total.StoppedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse totalMusic = Assert.Single(statistics.Total.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, totalMusic.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKindStatistics()
|
||||
{
|
||||
// Arrange
|
||||
await SeedMusicOnlyUserAsync();
|
||||
(Guid secondUserId, _) = await SeedBookOnlyUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/consumption-statistics?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
Assert.NotEmpty(statistics!.Users);
|
||||
Assert.All(statistics.Users, summary => Assert.All(summary.MediaKindSummaries, kind => Assert.Equal(MediaKind.MusicTrack, kind.MediaKind)));
|
||||
Assert.All(statistics.Total.MediaKindSummaries, kind => Assert.Equal(MediaKind.MusicTrack, kind.MediaKind));
|
||||
Assert.DoesNotContain(statistics.Users, summary => summary.UserId == secondUserId);
|
||||
AssertTotalsMatchUsers(statistics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenRestrictedToStartDate_ShouldExcludeEarlierSessions()
|
||||
{
|
||||
// Arrange
|
||||
await SeedMusicOnlyUserAsync();
|
||||
(Guid secondUserId, _) = await SeedBookOnlyUserAsync();
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/consumption-statistics?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
// Every book record of this class starts in February, so a March start date can only leave music sessions in the summary.
|
||||
Assert.All(statistics!.Users, summary => Assert.All(summary.MediaKindSummaries, kind => Assert.Equal(MediaKind.MusicTrack, kind.MediaKind)));
|
||||
Assert.All(statistics.Total.MediaKindSummaries, kind => Assert.Equal(MediaKind.MusicTrack, kind.MediaKind));
|
||||
Assert.DoesNotContain(statistics.Users, summary => summary.UserId == secondUserId);
|
||||
AssertTotalsMatchUsers(statistics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenRestrictedToEndDate_ShouldExcludeLaterSessions()
|
||||
{
|
||||
// Arrange
|
||||
(Guid firstUserId, _) = await SeedMusicOnlyUserAsync();
|
||||
await SeedBookOnlyUserAsync();
|
||||
string toUtc = Uri.EscapeDataString("2026-02-28T23:59:59");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/consumption-statistics?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
// Every music record of this class starts in March, so a February end date can only leave book sessions in the summary.
|
||||
Assert.All(statistics!.Users, summary => Assert.All(summary.MediaKindSummaries, kind => Assert.Equal(MediaKind.Book, kind.MediaKind)));
|
||||
Assert.All(statistics.Total.MediaKindSummaries, kind => Assert.Equal(MediaKind.Book, kind.MediaKind));
|
||||
Assert.DoesNotContain(statistics.Users, summary => summary.UserId == firstUserId);
|
||||
AssertTotalsMatchUsers(statistics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenTargetUserIdQueryParameterIsNotAValidGuid_ShouldIgnoreIt()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/consumption-statistics?userId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/consumption-statistics";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/consumption-statistics";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // A number that is not a member name.
|
||||
[InlineData("1")] // A number that is a defined enumeration value, which must still be rejected.
|
||||
[InlineData("not-a-media-kind")] // A name that is not a member of the enumeration.
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/consumption-statistics";
|
||||
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/consumption-statistics";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the combined totals are exactly the sum of the returned user summaries.
|
||||
/// </summary>
|
||||
/// <param name="statistics">The all users statistics response to assert on.</param>
|
||||
private static void AssertTotalsMatchUsers(AllUsersConsumptionStatisticsResponse statistics)
|
||||
{
|
||||
Assert.Equal(statistics.Users.Sum(summary => summary.TotalConsumedDurationInSeconds), statistics.Total.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(statistics.Users.Sum(summary => summary.CountedSessionCount), statistics.Total.CountedSessionCount);
|
||||
Assert.Equal(statistics.Users.Sum(summary => summary.CompletedSessionCount), statistics.Total.CompletedSessionCount);
|
||||
Assert.Equal(statistics.Users.Sum(summary => summary.StoppedSessionCount), statistics.Total.StoppedSessionCount);
|
||||
double expectedCompletionRate = statistics.Total.CountedSessionCount == 0
|
||||
? 0
|
||||
: (double)statistics.Total.CompletedSessionCount / statistics.Total.CountedSessionCount;
|
||||
Assert.Equal(expectedCompletionRate, statistics.Total.CompletionRate, 6);
|
||||
|
||||
MediaKind[] expectedMediaKinds = [.. statistics.Users
|
||||
.SelectMany(summary => summary.MediaKindSummaries)
|
||||
.Select(summary => summary.MediaKind)
|
||||
.Distinct()
|
||||
.Order()];
|
||||
Assert.Equal(expectedMediaKinds, statistics.Total.MediaKindSummaries.Select(summary => summary.MediaKind).ToArray());
|
||||
foreach (MediaKindConsumptionSummaryResponse totalKind in statistics.Total.MediaKindSummaries)
|
||||
{
|
||||
List<MediaKindConsumptionSummaryResponse> userKinds = [.. statistics.Users
|
||||
.SelectMany(summary => summary.MediaKindSummaries)
|
||||
.Where(summary => summary.MediaKind == totalKind.MediaKind)];
|
||||
Assert.Equal(userKinds.Sum(summary => summary.TotalConsumedDurationInSeconds), totalKind.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(userKinds.Sum(summary => summary.CountedSessionCount), totalKind.CountedSessionCount);
|
||||
Assert.Equal(userKinds.Sum(summary => summary.CompletedSessionCount), totalKind.CompletedSessionCount);
|
||||
Assert.Equal(userKinds.Sum(summary => summary.StoppedSessionCount), totalKind.StoppedSessionCount);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user with a music library and two counted music sessions.
|
||||
/// </summary>
|
||||
/// <returns>The Ids of the seeded user and of its music library.</returns>
|
||||
private async Task<(Guid userId, Guid libraryId)> SeedMusicOnlyUserAsync()
|
||||
{
|
||||
Guid userId = await SeedUserAsync($"musicuser_{Guid.NewGuid()}");
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackId = Guid.NewGuid();
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_musicStartedOnUtc, 60_000, 0);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_musicStartedOnUtc.AddMinutes(5), 40_000, 0);
|
||||
return (userId, libraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user with an ebook library and one counted book session and one uncounted one.
|
||||
/// </summary>
|
||||
/// <returns>The Ids of the seeded user and of its ebook library.</returns>
|
||||
private async Task<(Guid userId, Guid libraryId)> SeedBookOnlyUserAsync()
|
||||
{
|
||||
Guid userId = await SeedUserAsync($"bookuser_{Guid.NewGuid()}");
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid bookId = Guid.NewGuid();
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, s_bookStartedOnUtc, 300_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, bookId, ConsumptionStatus.Stopped, s_bookStartedOnUtc.AddMinutes(5), 100_000, 1);
|
||||
return (userId, libraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
ConsumptionStatus status,
|
||||
DateTime startedOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc.AddMinutes(1),
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, 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(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The authorization rows are removed with the users, so that the next test of the class can create its own admin user without colliding with the
|
||||
/// admin role permissions of the previous one.
|
||||
/// </remarks>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.MediaConsumptionRecords.ExecuteDeleteAsync();
|
||||
await dbContext.Libraries.ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+540
@@ -0,0 +1,540 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionStatisticsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_trackCompletedStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackStoppedCountedStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackStoppedUncountedStartedOnUtc = new(2026, 3, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackInProgressStartedOnUtc = new(2026, 3, 4, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookCompletedStartedOnUtc = new(2026, 2, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookStoppedFivePagesStartedOnUtc = new(2026, 2, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookStoppedSixPagesStartedOnUtc = new(2026, 2, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookInProgressStartedOnUtc = new(2026, 2, 4, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetConsumptionStatisticsEndpointTests(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 GetConsumptionStatistics_WhenHistoryExists_ShouldApplyCountingRulesAndBreakdownByMediaKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(userId, summary!.UserId);
|
||||
Assert.Equal(359.999, summary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(4, summary.CountedSessionCount);
|
||||
Assert.Equal(2, summary.CompletedSessionCount);
|
||||
Assert.Equal(2, summary.StoppedSessionCount);
|
||||
Assert.Equal(0.5, summary.CompletionRate, 6);
|
||||
|
||||
Assert.Equal(2, summary.MediaKindSummaries.Count);
|
||||
|
||||
MediaKindConsumptionSummaryResponse trackSummary = summary.MediaKindSummaries[0];
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
Assert.Equal(79.999, trackSummary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, trackSummary.CountedSessionCount);
|
||||
Assert.Equal(1, trackSummary.CompletedSessionCount);
|
||||
Assert.Equal(1, trackSummary.StoppedSessionCount);
|
||||
Assert.Equal(0.5, trackSummary.CompletionRate, 6);
|
||||
|
||||
MediaKindConsumptionSummaryResponse bookSummary = summary.MediaKindSummaries[1];
|
||||
Assert.Equal(MediaKind.Book, bookSummary.MediaKind);
|
||||
Assert.Equal(280d, bookSummary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, bookSummary.CountedSessionCount);
|
||||
Assert.Equal(1, bookSummary.CompletedSessionCount);
|
||||
Assert.Equal(1, bookSummary.StoppedSessionCount);
|
||||
Assert.Equal(0.5, bookSummary.CompletionRate, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookLibraryId) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics?libraryId={bookLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(280d, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
Assert.Equal(1, summary.CompletedSessionCount);
|
||||
Assert.Equal(1, summary.StoppedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse bookSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.Book, bookSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKindStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(79.999, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(79.999, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenStartDateCarriesAZoneDesignator_ShouldUseTheDescribedUtcInstant()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00Z");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(79.999, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
string toUtc = Uri.EscapeDataString("2026-02-28T23:59:59");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(280d, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse bookSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.Book, bookSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenHistoryIsEmpty_ShouldReturnZeroedTotalsAndEmptyBreakdown()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(userId, summary!.UserId);
|
||||
Assert.Equal(0d, summary.TotalConsumedDurationInSeconds);
|
||||
Assert.Equal(0, summary.CountedSessionCount);
|
||||
Assert.Equal(0, summary.CompletedSessionCount);
|
||||
Assert.Equal(0, summary.StoppedSessionCount);
|
||||
Assert.Equal(0d, summary.CompletionRate);
|
||||
Assert.Empty(summary.MediaKindSummaries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenInProgressSessionReachedTheThreshold_ShouldCountItTowardsStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackId = Guid.NewGuid();
|
||||
// The media kind rule counts a session when it completed or when it reached the threshold of its kind, which an in-progress session can do.
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.InProgress, s_trackCompletedStartedOnUtc, 30_000, 0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(1, summary!.CountedSessionCount);
|
||||
Assert.Equal(0, summary.CompletedSessionCount);
|
||||
Assert.Equal(0, summary.StoppedSessionCount);
|
||||
Assert.Equal(30d, summary.TotalConsumedDurationInSeconds, 3);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(1, trackSummary.CountedSessionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // A number that is not a member name.
|
||||
[InlineData("1")] // A number that is a defined enumeration value, which must still be rejected.
|
||||
[InlineData("not-a-media-kind")] // A name that is not a member of the enumeration.
|
||||
public async Task GetConsumptionStatistics_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not-a-date")] // A textual value that is not a date.
|
||||
[InlineData("2026-13-45T99:99:99")] // A value with out of range components.
|
||||
public async Task GetConsumptionStatistics_WhenADateBoundIsNotAValidDate_ShouldReturnValidationProblem(string invalidDate)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
string url = $"{path}?fromUtc={Uri.EscapeDataString(invalidDate)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library and an ebook library owned by <paramref name="userId"/>, with one track and one book history.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the libraries and the consumption records.</param>
|
||||
/// <returns>The Ids of the music library and the ebook library.</returns>
|
||||
private async Task<(Guid musicLibraryId, Guid bookLibraryId)> SeedConsumptionScenarioAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_trackCompletedStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackStoppedCountedStartedOnUtc, 30_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackStoppedUncountedStartedOnUtc, 29_999, 0);
|
||||
// An in-progress session counts only through the threshold branch of its media kind rule, so it is kept below both thresholds here.
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.InProgress, s_trackInProgressStartedOnUtc, 10_000, 0);
|
||||
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, s_bookCompletedStartedOnUtc, 100_000, 0);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Stopped, s_bookStoppedFivePagesStartedOnUtc, 60_000, 5);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Stopped, s_bookStoppedSixPagesStartedOnUtc, 90_000, 6);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.InProgress, s_bookInProgressStartedOnUtc, 30_000, 2);
|
||||
|
||||
return (musicLibraryId, bookLibraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
ConsumptionStatus status,
|
||||
DateTime startedOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc.AddMinutes(1),
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+413
@@ -0,0 +1,413 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserConsumptionStatisticsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_completedStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_stoppedStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserConsumptionStatisticsEndpointTests(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 GetUserConsumptionStatistics_WhenCurrentUserNamesTheirOwnId_ShouldReturnTheirStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackId = Guid.NewGuid();
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_completedStartedOnUtc, 60_000, 0);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_stoppedStartedOnUtc, 30_000, 0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(userId, summary!.UserId);
|
||||
Assert.Equal(90d, summary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
Assert.Equal(1, summary.CompletedSessionCount);
|
||||
Assert.Equal(1, summary.StoppedSessionCount);
|
||||
Assert.Equal(0.5, summary.CompletionRate, 6);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
Assert.Equal(90d, trackSummary.TotalConsumedDurationInSeconds, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other Library");
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.MusicTrack, Guid.NewGuid(), ConsumptionStatus.Completed, s_completedStartedOnUtc, 60_000, 0);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.False(problemDetails!.ContainsKey("mediaKindSummaries"));
|
||||
Assert.False(problemDetails.ContainsKey("countedSessionCount"));
|
||||
Assert.False(problemDetails.ContainsKey("totalConsumedDurationInSeconds"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenAdminNamesAnotherUser_ShouldReturnThatUsersStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedUserAsync($"targetuser_{Guid.NewGuid()}");
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.EBook, "Target Book Library");
|
||||
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.Book, Guid.NewGuid(), ConsumptionStatus.Completed, s_completedStartedOnUtc, 300_000, 10);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(targetUserId, summary!.UserId);
|
||||
Assert.Equal(300d, summary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, summary.CountedSessionCount);
|
||||
Assert.Equal(1, summary.CompletedSessionCount);
|
||||
Assert.Equal(0, summary.StoppedSessionCount);
|
||||
Assert.Equal(1d, summary.CompletionRate, 6);
|
||||
MediaKindConsumptionSummaryResponse bookSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.Book, bookSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
ConsumptionStatus status,
|
||||
DateTime startedOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc.AddMinutes(1),
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
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>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, 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(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+524
@@ -0,0 +1,524 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetGenreConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_trackCompletedStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackStoppedStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookCompletedStartedOnUtc = new(2026, 2, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_uncountedBookStartedOnUtc = new(2026, 2, 5, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetGenreConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
_seededUsernames.Add(_apiFactory.TestUsername!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WhenGenreBearingItemsWereConsumed_ShouldReturnLowercaseGenresOrderedByItemCountThenDurationThenName()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid musicLibraryId, Guid bookLibraryId, string rockGenre, string favouriteGenre, string bookClubGenre, string ignoredGenre) = await SeedGenreConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/genres");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
|
||||
Assert.NotNull(genres);
|
||||
Assert.Equal(3, genres!.Count);
|
||||
Assert.All(genres, genre => Assert.Equal(genre.Name.ToLowerInvariant(), genre.Name));
|
||||
Assert.Equal(
|
||||
new[] { favouriteGenre.ToLowerInvariant(), rockGenre.ToLowerInvariant(), bookClubGenre.ToLowerInvariant() },
|
||||
genres.Select(genre => genre.Name).ToArray());
|
||||
|
||||
Assert.Equal(2, genres[0].ConsumedItemCount);
|
||||
Assert.Equal(360d, genres[0].ConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, genres[1].ConsumedItemCount);
|
||||
Assert.Equal(90d, genres[1].ConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, genres[2].ConsumedItemCount);
|
||||
Assert.Equal(300d, genres[2].ConsumedDurationInSeconds, 3);
|
||||
Assert.DoesNotContain(genres, genre => genre.Name == ignoredGenre.ToLowerInvariant());
|
||||
Assert.NotEqual(musicLibraryId, bookLibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryGenres()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookLibraryId, _, string favouriteGenre, string bookClubGenre, string ignoredGenre) = await SeedGenreConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/genres?libraryId={bookLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
|
||||
Assert.NotNull(genres);
|
||||
Assert.Equal(
|
||||
new[] { bookClubGenre.ToLowerInvariant(), favouriteGenre.ToLowerInvariant() },
|
||||
genres!.Select(genre => genre.Name).ToArray());
|
||||
Assert.All(genres, genre => Assert.Equal(1, genre.ConsumedItemCount));
|
||||
Assert.All(genres, genre => Assert.Equal(300d, genre.ConsumedDurationInSeconds, 3));
|
||||
Assert.DoesNotContain(genres, genre => genre.Name == ignoredGenre.ToLowerInvariant());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKindGenres()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, string rockGenre, string favouriteGenre, string bookClubGenre, _) = await SeedGenreConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/genres?mediaKind={nameof(MediaKind.MusicTrack)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
|
||||
Assert.NotNull(genres);
|
||||
Assert.Equal(
|
||||
new[] { rockGenre.ToLowerInvariant(), favouriteGenre.ToLowerInvariant() },
|
||||
genres!.Select(genre => genre.Name).ToArray());
|
||||
Assert.Equal(2, genres[0].ConsumedItemCount);
|
||||
Assert.Equal(90d, genres[0].ConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, genres[1].ConsumedItemCount);
|
||||
Assert.Equal(60d, genres[1].ConsumedDurationInSeconds, 3);
|
||||
Assert.DoesNotContain(genres, genre => genre.Name == bookClubGenre.ToLowerInvariant());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, string rockGenre, string favouriteGenre, string bookClubGenre, _) = await SeedGenreConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/genres?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
|
||||
Assert.NotNull(genres);
|
||||
Assert.Equal(
|
||||
new[] { rockGenre.ToLowerInvariant(), favouriteGenre.ToLowerInvariant() },
|
||||
genres!.Select(genre => genre.Name).ToArray());
|
||||
Assert.Equal(2, genres[0].ConsumedItemCount);
|
||||
Assert.Equal(90d, genres[0].ConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, genres[1].ConsumedItemCount);
|
||||
Assert.Equal(60d, genres[1].ConsumedDurationInSeconds, 3);
|
||||
Assert.DoesNotContain(genres, genre => genre.Name == bookClubGenre.ToLowerInvariant());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, string rockGenre, string favouriteGenre, string bookClubGenre, _) = await SeedGenreConsumptionScenarioAsync(userId);
|
||||
string toUtc = Uri.EscapeDataString("2026-02-28T23:59:59");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/genres?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
|
||||
Assert.NotNull(genres);
|
||||
Assert.Equal(
|
||||
new[] { bookClubGenre.ToLowerInvariant(), favouriteGenre.ToLowerInvariant() },
|
||||
genres!.Select(genre => genre.Name).ToArray());
|
||||
Assert.All(genres, genre => Assert.Equal(1, genre.ConsumedItemCount));
|
||||
Assert.All(genres, genre => Assert.Equal(300d, genre.ConsumedDurationInSeconds, 3));
|
||||
Assert.DoesNotContain(genres, genre => genre.Name == rockGenre.ToLowerInvariant());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WhenHistoryIsEmpty_ShouldReturnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
_ = GetCurrentUserId();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/genres");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
|
||||
Assert.NotNull(genres);
|
||||
Assert.Empty(genres!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-statistics/genres";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/genres";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/genres";
|
||||
string url = $"{path}?mediaKind={nameof(MediaKind.None)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // A number that is not a member name.
|
||||
[InlineData("not-a-media-kind")] // A name that is not a member of the enumeration.
|
||||
public async Task GetGenreConsumption_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/genres";
|
||||
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/genres";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track and a book in two libraries of <paramref name="userId"/>, with counted and uncounted sessions.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the libraries and the consumption records.</param>
|
||||
/// <returns>
|
||||
/// The Ids of the music library and the ebook library, and the unique rock, favourite, book club, and ignored genre names that were seeded.
|
||||
/// </returns>
|
||||
private async Task<(Guid musicLibraryId, Guid bookLibraryId, string rockGenre, string favouriteGenre, string bookClubGenre, string ignoredGenre)> SeedGenreConsumptionScenarioAsync(Guid userId)
|
||||
{
|
||||
// Each test seeds its own genre rows, so every name carries a unique suffix to keep the shared Genres table collision free.
|
||||
string suffix = Guid.NewGuid().ToString("N")[..8].ToUpperInvariant();
|
||||
string rockGenre = $"Rock-{suffix}";
|
||||
string favouriteGenre = $"Favourite-{suffix}";
|
||||
string bookClubGenre = $"Book-Club-{suffix}";
|
||||
string ignoredGenre = $"Ignored-{suffix}";
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// The track and the book share a genre, so the genre rows are resolved once per name, and the whole graph is saved through one context.
|
||||
Dictionary<string, GenreEntity> genres = [];
|
||||
GenreEntity ResolveGenre(string name)
|
||||
{
|
||||
if (!genres.TryGetValue(name, out GenreEntity? genre))
|
||||
{
|
||||
genre = _genreEntityFixture.Create(name: name);
|
||||
genres[name] = genre;
|
||||
}
|
||||
return genre;
|
||||
}
|
||||
|
||||
Guid musicLibraryId = Guid.NewGuid();
|
||||
Guid bookLibraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid firstTrackId = Guid.NewGuid();
|
||||
Guid secondTrackId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid uncountedBookId = Guid.NewGuid();
|
||||
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: musicLibraryId, userId: userId, title: "Music Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: bookLibraryId, userId: userId, title: "Book Library", libraryType: LibraryType.EBook, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: musicLibraryId, name: "Queen", includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: musicLibraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false));
|
||||
|
||||
TrackEntity firstTrack = _trackEntityFixture.Create(id: firstTrackId, albumId: albumId, libraryId: musicLibraryId, path: $"/music/{firstTrackId:N}.flac", title: "Bohemian Rhapsody", includeMetadata: false);
|
||||
firstTrack.Genres.Add(ResolveGenre(rockGenre));
|
||||
firstTrack.Genres.Add(ResolveGenre(favouriteGenre));
|
||||
dbContext.Tracks.Add(firstTrack);
|
||||
|
||||
TrackEntity secondTrack = _trackEntityFixture.Create(id: secondTrackId, albumId: albumId, libraryId: musicLibraryId, path: $"/music/{secondTrackId:N}.flac", title: "Love of My Life", includeMetadata: false);
|
||||
secondTrack.Genres.Add(ResolveGenre(rockGenre));
|
||||
dbContext.Tracks.Add(secondTrack);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: bookLibraryId, path: $"/books/{bookId:N}.epub", title: "The Fellowship of the Ring", includeMetadata: false);
|
||||
book.Genres.Add(ResolveGenre(favouriteGenre));
|
||||
book.Genres.Add(ResolveGenre(bookClubGenre));
|
||||
dbContext.Books.Add(book);
|
||||
|
||||
BookEntity uncountedBook = _bookEntityFixture.Create(id: uncountedBookId, libraryId: bookLibraryId, path: $"/books/{uncountedBookId:N}.epub", title: "Uncounted Book", includeMetadata: false);
|
||||
uncountedBook.Genres.Add(ResolveGenre(ignoredGenre));
|
||||
dbContext.Books.Add(uncountedBook);
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, firstTrackId, ConsumptionStatus.Completed, s_trackCompletedStartedOnUtc, 60_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, secondTrackId, ConsumptionStatus.Stopped, s_trackStoppedStartedOnUtc, 30_000, 0);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, s_bookCompletedStartedOnUtc, 300_000, 10);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, uncountedBookId, ConsumptionStatus.Stopped, s_uncountedBookStartedOnUtc, 500_000, 3);
|
||||
|
||||
return (musicLibraryId, bookLibraryId, rockGenre, favouriteGenre, bookClubGenre, ignoredGenre);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
ConsumptionStatus status,
|
||||
DateTime startedOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc.AddMinutes(1),
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes every user created by the test, together with the libraries it owns.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
foreach (string username in _seededUsernames)
|
||||
{
|
||||
UserEntity? user = dbContext.Users
|
||||
.Include(candidate => candidate.Libraries)
|
||||
.FirstOrDefault(candidate => candidate.Username == username);
|
||||
if (user is null)
|
||||
continue;
|
||||
dbContext.Libraries.RemoveRange(user.Libraries);
|
||||
dbContext.Users.Remove(user);
|
||||
}
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+485
@@ -0,0 +1,485 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserGenreConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserGenreConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserGenreConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserGenreConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
_seededUsernames.Add(_apiFactory.TestUsername!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserGenreConsumption_WhenCurrentUserNamesTheirOwnId_ShouldReturnTheirGenreStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
string suffix = Guid.NewGuid().ToString("N")[..8];
|
||||
string firstGenre = $"First-{suffix}";
|
||||
string secondGenre = $"Second-{suffix}";
|
||||
Guid trackId = await SeedTrackAsync(libraryId, "Bohemian Rhapsody", "A Night at the Opera", "Queen", [firstGenre, secondGenre]);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, 60_000, 0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-statistics/genres");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
|
||||
Assert.NotNull(genres);
|
||||
Assert.Equal(2, genres!.Count);
|
||||
Assert.Equal(
|
||||
new[] { firstGenre.ToLowerInvariant(), secondGenre.ToLowerInvariant() },
|
||||
genres.Select(genre => genre.Name).ToArray());
|
||||
Assert.All(genres, genre => Assert.Equal(1, genre.ConsumedItemCount));
|
||||
Assert.All(genres, genre => Assert.Equal(60d, genre.ConsumedDurationInSeconds, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserGenreConsumption_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedUserAsync();
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other Library");
|
||||
string secretGenre = $"Secret-{Guid.NewGuid().ToString("N")[..8]}";
|
||||
Guid otherTrackId = await SeedTrackAsync(otherLibraryId, "Secret Track", "Secret Album", "Secret Artist", [secretGenre]);
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.MusicTrack, otherTrackId, 60_000, 0);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-statistics/genres";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(secretGenre, content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Secret Track", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserGenreConsumption_WhenAdminNamesAnotherUser_ShouldReturnThatUsersGenreStatistics()
|
||||
{
|
||||
// Arrange
|
||||
_ = GetCurrentUserId();
|
||||
Guid targetUserId = await SeedUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.EBook, "Target Book Library");
|
||||
string targetGenre = $"Target-{Guid.NewGuid().ToString("N")[..8]}";
|
||||
Guid targetBookId = await SeedBookAsync(targetLibraryId, "Target Book", [targetGenre]);
|
||||
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.Book, targetBookId, 300_000, 10);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
_seededUsernames.Add(_apiFactory.TestUsername!);
|
||||
|
||||
try
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-statistics/genres");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
|
||||
Assert.NotNull(genres);
|
||||
GenreConsumptionResponse genre = Assert.Single(genres!);
|
||||
Assert.Equal(targetGenre.ToLowerInvariant(), genre.Name);
|
||||
Assert.Equal(1, genre.ConsumedItemCount);
|
||||
Assert.Equal(300d, genre.ConsumedDurationInSeconds, 3);
|
||||
}
|
||||
finally
|
||||
{
|
||||
adminClient.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserGenreConsumption_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-statistics/genres";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserGenreConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-statistics/genres";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserGenreConsumption_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics/genres";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserGenreConsumption_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics/genres";
|
||||
string url = $"{path}?mediaKind={nameof(MediaKind.None)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserGenreConsumption_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics/genres";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a genre-bearing track of <paramref name="libraryId"/>, together with its artist and album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the track.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="albumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="genreNames">The genre names carried by the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName, IReadOnlyList<string> genreNames)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false));
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false);
|
||||
foreach (string genreName in genreNames)
|
||||
track.Genres.Add(_genreEntityFixture.Create(name: genreName));
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a genre-bearing book of <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <param name="genreNames">The genre names carried by the book.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, IReadOnlyList<string> genreNames)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
foreach (string genreName in genreNames)
|
||||
book.Genres.Add(_genreEntityFixture.Create(name: genreName));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a completed consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_startedOnUtc.AddMinutes(1),
|
||||
endedOnUtc: s_startedOnUtc.AddMinutes(2),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
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>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, 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(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes every user created by the test, together with the libraries it owns.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
foreach (string username in _seededUsernames)
|
||||
{
|
||||
UserEntity? user = dbContext.Users
|
||||
.Include(candidate => candidate.Libraries)
|
||||
.FirstOrDefault(candidate => candidate.Username == username);
|
||||
if (user is null)
|
||||
continue;
|
||||
dbContext.Libraries.RemoveRange(user.Libraries);
|
||||
dbContext.Users.Remove(user);
|
||||
}
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+550
@@ -0,0 +1,550 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMostConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMostConsumedEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_trackAFirstStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackASecondStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackAThirdStartedOnUtc = new(2026, 3, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackBFirstStartedOnUtc = new(2026, 3, 2, 8, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackBSecondStartedOnUtc = new(2026, 3, 2, 9, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookFirstStartedOnUtc = new(2026, 2, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookSecondStartedOnUtc = new(2026, 2, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMostConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetMostConsumedEndpointTests(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 GetMostConsumed_WhenHistoryExists_ShouldOrderByCountedSessionsThenDurationThenLastConsumed()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid musicLibraryId, Guid trackAId, Guid trackBId, Guid bookLibraryId, Guid bookCId) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/most-consumed?currentPage=1&perPage=10");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(1, history!.CurrentPage);
|
||||
Assert.Equal(10, history.PerPage);
|
||||
Assert.Equal(3, history.Count);
|
||||
Assert.Equal(1, history.NumberOfPages);
|
||||
Assert.Equal(3, history.Data.Count);
|
||||
|
||||
Assert.Equal(new[] { trackAId, trackBId, bookCId }, history.Data.Select(item => item.MediaItemId).ToArray());
|
||||
|
||||
ConsumedItemResponse mostConsumed = history.Data[0];
|
||||
Assert.Equal(MediaKind.MusicTrack, mostConsumed.MediaKind);
|
||||
Assert.Equal(musicLibraryId, mostConsumed.LibraryId);
|
||||
Assert.True(mostConsumed.IsAvailable);
|
||||
Assert.Equal("Track A", mostConsumed.Title);
|
||||
Assert.Equal("Album A", mostConsumed.CollectionTitle);
|
||||
Assert.Equal("Artist A", mostConsumed.CreatorName);
|
||||
Assert.Null(mostConsumed.CoverPath);
|
||||
Assert.Equal(s_trackAThirdStartedOnUtc, mostConsumed.LastConsumedOnUtc);
|
||||
Assert.Equal(3, mostConsumed.CountedSessionCount);
|
||||
Assert.Equal(3, mostConsumed.CompletedSessionCount);
|
||||
Assert.Equal(30d, mostConsumed.ConsumedDurationInSeconds);
|
||||
|
||||
ConsumedItemResponse second = history.Data[1];
|
||||
Assert.Equal(trackBId, second.MediaItemId);
|
||||
Assert.Equal(2, second.CountedSessionCount);
|
||||
Assert.Equal(200d, second.ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_trackBSecondStartedOnUtc, second.LastConsumedOnUtc);
|
||||
|
||||
ConsumedItemResponse third = history.Data[2];
|
||||
Assert.Equal(bookCId, third.MediaItemId);
|
||||
Assert.Equal(bookLibraryId, third.LibraryId);
|
||||
Assert.Equal(2, third.CountedSessionCount);
|
||||
Assert.Equal(200d, third.ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_bookSecondStartedOnUtc, third.LastConsumedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, _, Guid bookLibraryId, Guid bookCId) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/most-consumed?libraryId={bookLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(bookCId, item.MediaItemId);
|
||||
Assert.Equal(bookLibraryId, item.LibraryId);
|
||||
Assert.Equal(1, history.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackAId, Guid trackBId, _, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/most-consumed?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.All(history!.Data, item => Assert.Equal(MediaKind.MusicTrack, item.MediaKind));
|
||||
Assert.Equal(new[] { trackAId, trackBId }, history.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(2, history.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackAId, Guid trackBId, _, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-02T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/most-consumed?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(new[] { trackBId, trackAId }, history!.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(2, history.Count);
|
||||
Assert.Equal(2, history.Data[0].CountedSessionCount);
|
||||
Assert.Equal(200d, history.Data[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal(2, history.Data[1].CountedSessionCount);
|
||||
Assert.Equal(20d, history.Data[1].ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackAId, Guid trackBId, _, Guid bookCId) = await SeedConsumptionScenarioAsync(userId);
|
||||
string toUtc = Uri.EscapeDataString("2026-03-02T08:30:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/most-consumed?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
// The end of the range keeps the February book sessions and drops the later track sessions, which changes both the counts and the order.
|
||||
Assert.Equal(new[] { bookCId, trackBId, trackAId }, history!.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(2, history.Data[0].CountedSessionCount);
|
||||
Assert.Equal(200d, history.Data[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal(1, history.Data[1].CountedSessionCount);
|
||||
Assert.Equal(100d, history.Data[1].ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_trackBFirstStartedOnUtc, history.Data[1].LastConsumedOnUtc);
|
||||
Assert.Equal(1, history.Data[2].CountedSessionCount);
|
||||
Assert.Equal(10d, history.Data[2].ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_trackAFirstStartedOnUtc, history.Data[2].LastConsumedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenPaginationIsRequested_ShouldReturnRequestedPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, _, _, Guid bookCId) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/most-consumed?currentPage=2&perPage=2");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(2, history!.CurrentPage);
|
||||
Assert.Equal(2, history.PerPage);
|
||||
Assert.Equal(3, history.Count);
|
||||
Assert.Equal(2, history.NumberOfPages);
|
||||
ConsumedItemResponse item = Assert.Single(history.Data);
|
||||
Assert.Equal(bookCId, item.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // A number that is not a member name.
|
||||
[InlineData("1")] // A number that is a defined enumeration value, which must still be rejected.
|
||||
[InlineData("not-a-media-kind")] // A name that is not a member of the enumeration.
|
||||
public async Task GetMostConsumed_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds two tracks with three and two sessions and a book with two sessions, all owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the libraries and the consumption records.</param>
|
||||
/// <returns>The Ids of the music library, both tracks, the ebook library, and the book.</returns>
|
||||
private async Task<(Guid musicLibraryId, Guid trackAId, Guid trackBId, Guid bookLibraryId, Guid bookCId)> SeedConsumptionScenarioAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackAId = await SeedTrackAsync(musicLibraryId, "Track A", "Album A", "Artist A");
|
||||
Guid trackBId = await SeedTrackAsync(musicLibraryId, "Track B", "Album B", "Artist B");
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
// The contributor display name is unique across the whole database, so every test seeds its own spelling of the author.
|
||||
Guid bookCId = await SeedBookAsync(bookLibraryId, "Book C", $"Author C {Guid.NewGuid():N}");
|
||||
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackAId, s_trackAFirstStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackAId, s_trackASecondStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackAId, s_trackAThirdStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackBId, s_trackBFirstStartedOnUtc, 100_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackBId, s_trackBSecondStartedOnUtc, 100_000, 0);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookCId, s_bookFirstStartedOnUtc, 100_000, 10);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookCId, s_bookSecondStartedOnUtc, 100_000, 10);
|
||||
|
||||
return (musicLibraryId, trackAId, trackBId, bookLibraryId, bookCId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of <paramref name="libraryId"/>, together with its artist and album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the track.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="albumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false));
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of <paramref name="libraryId"/>, together with an author contributor when a name is supplied.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <param name="authorName">The name of the author of the book, or <see langword="null"/> for no contributor.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid? contributorId = null;
|
||||
if (authorName is not null)
|
||||
{
|
||||
contributorId = Guid.NewGuid();
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId.Value, displayName: authorName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
if (contributorId is not null)
|
||||
book.Contributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId.Value, role: MediaContributorRole.Author));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a completed consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
DateTime startedOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc,
|
||||
endedOnUtc: startedOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+473
@@ -0,0 +1,473 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserMostConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserMostConsumedEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_firstStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_secondStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserMostConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserMostConsumedEndpointTests(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 GetUserMostConsumed_WhenCurrentUserNamesTheirOwnId_ShouldReturnTheirMostConsumedItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid mostConsumedBookId = await SeedBookAsync(libraryId, "Most Consumed Book", "Author One");
|
||||
Guid lessConsumedBookId = await SeedBookAsync(libraryId, "Less Consumed Book", "Author Two");
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, mostConsumedBookId, s_firstStartedOnUtc, 120_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, mostConsumedBookId, s_secondStartedOnUtc, 120_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, lessConsumedBookId, s_secondStartedOnUtc, 300_000, 10);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-history/most-consumed?currentPage=1&perPage=10");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(2, history!.Count);
|
||||
Assert.Equal(1, history.CurrentPage);
|
||||
Assert.Equal(10, history.PerPage);
|
||||
Assert.Equal(1, history.NumberOfPages);
|
||||
Assert.Equal(new[] { mostConsumedBookId, lessConsumedBookId }, history.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(2, history.Data[0].CountedSessionCount);
|
||||
Assert.Equal(240d, history.Data[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal("Most Consumed Book", history.Data[0].Title);
|
||||
Assert.Equal("Author One", history.Data[0].CreatorName);
|
||||
Assert.Equal(1, history.Data[1].CountedSessionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.EBook, "Other Library");
|
||||
Guid otherBookId = await SeedBookAsync(otherLibraryId, "Other User Secret Book", "Secret Author");
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.Book, otherBookId, s_firstStartedOnUtc, 120_000, 10);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-history/most-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Other User Secret Book", content);
|
||||
Assert.DoesNotContain("Secret Author", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenAdminNamesAnotherUser_ShouldReturnThatUsersMostConsumedItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedUserAsync($"targetuser_{Guid.NewGuid()}");
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.Music, "Target Music Library");
|
||||
Guid targetTrackId = await SeedTrackAsync(targetLibraryId, "The Show Must Go On", "Innuendo", "Queen");
|
||||
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, targetTrackId, s_firstStartedOnUtc, 60_000, 0);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-history/most-consumed");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(targetTrackId, item.MediaItemId);
|
||||
Assert.Equal(targetLibraryId, item.LibraryId);
|
||||
Assert.Equal("The Show Must Go On", item.Title);
|
||||
Assert.Equal(1, item.CountedSessionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-history/most-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/most-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/most-consumed";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/most-consumed";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/most-consumed";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of <paramref name="libraryId"/>, together with its artist and album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the track.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="albumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false));
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of <paramref name="libraryId"/>, together with an author contributor when a name is supplied.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <param name="authorName">The name of the author of the book, or <see langword="null"/> for no contributor.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid? contributorId = null;
|
||||
if (authorName is not null)
|
||||
{
|
||||
contributorId = Guid.NewGuid();
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId.Value, displayName: authorName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
if (contributorId is not null)
|
||||
book.Contributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId.Value, role: MediaContributorRole.Author));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a completed consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
DateTime startedOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc,
|
||||
endedOnUtc: startedOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
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>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, 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(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+639
@@ -0,0 +1,639 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetRecentlyConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRecentlyConsumedEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_trackFirstStartedOnUtc = new(2026, 3, 1, 9, 55, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackFirstLastActivityOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackSecondStartedOnUtc = new(2026, 3, 2, 9, 55, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackSecondLastActivityOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackThirdStartedOnUtc = new(2026, 3, 3, 9, 55, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackThirdLastActivityOnUtc = new(2026, 3, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookStartedOnUtc = new(2026, 2, 28, 19, 50, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookLastActivityOnUtc = new(2026, 2, 28, 20, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_missingItemLastActivityOnUtc = new(2026, 3, 5, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRecentlyConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetRecentlyConsumedEndpointTests(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 GetRecentlyConsumed_WhenCalledForCurrentUser_ShouldReturnAggregatedHistory()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid musicLibraryId, Guid trackId, Guid bookLibraryId, Guid bookId, string authorName) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed?currentPage=1&perPage=10");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(1, history!.CurrentPage);
|
||||
Assert.Equal(10, history.PerPage);
|
||||
Assert.Equal(2, history.Count);
|
||||
Assert.Equal(1, history.NumberOfPages);
|
||||
Assert.Equal(2, history.Data.Count);
|
||||
|
||||
ConsumedItemResponse track = history.Data[0];
|
||||
Assert.Equal(MediaKind.MusicTrack, track.MediaKind);
|
||||
Assert.Equal(trackId, track.MediaItemId);
|
||||
Assert.Equal(musicLibraryId, track.LibraryId);
|
||||
Assert.True(track.IsAvailable);
|
||||
Assert.Equal("Bohemian Rhapsody", track.Title);
|
||||
Assert.Equal("A Night at the Opera", track.CollectionTitle);
|
||||
Assert.Equal("Queen", track.CreatorName);
|
||||
Assert.Null(track.CoverPath);
|
||||
Assert.Equal(s_trackThirdLastActivityOnUtc, track.LastConsumedOnUtc);
|
||||
Assert.Equal(2, track.CountedSessionCount);
|
||||
Assert.Equal(1, track.CompletedSessionCount);
|
||||
Assert.Equal(100d, track.ConsumedDurationInSeconds);
|
||||
|
||||
ConsumedItemResponse book = history.Data[1];
|
||||
Assert.Equal(MediaKind.Book, book.MediaKind);
|
||||
Assert.Equal(bookId, book.MediaItemId);
|
||||
Assert.Equal(bookLibraryId, book.LibraryId);
|
||||
Assert.True(book.IsAvailable);
|
||||
Assert.Equal("The Fellowship of the Ring", book.Title);
|
||||
Assert.Equal(string.Empty, book.CollectionTitle);
|
||||
Assert.Equal(authorName, book.CreatorName);
|
||||
Assert.Null(book.CoverPath);
|
||||
Assert.Equal(s_bookLastActivityOnUtc, book.LastConsumedOnUtc);
|
||||
Assert.Equal(1, book.CountedSessionCount);
|
||||
Assert.Equal(1, book.CompletedSessionCount);
|
||||
Assert.Equal(500d, book.ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, Guid bookLibraryId, Guid bookId, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/recently-consumed?libraryId={bookLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(bookId, item.MediaItemId);
|
||||
Assert.Equal(bookLibraryId, item.LibraryId);
|
||||
Assert.Equal(1, history.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid musicLibraryId, Guid trackId, _, _, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(MediaKind.MusicTrack, item.MediaKind);
|
||||
Assert.Equal(trackId, item.MediaItemId);
|
||||
Assert.Equal(musicLibraryId, item.LibraryId);
|
||||
Assert.Equal(1, history.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackId, _, _, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/recently-consumed?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(trackId, item.MediaItemId);
|
||||
Assert.Equal(2, item.CountedSessionCount);
|
||||
Assert.Equal(100d, item.ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackId, _, Guid bookId, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
string toUtc = Uri.EscapeDataString("2026-03-02T23:59:59");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/recently-consumed?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
// The end of the range keeps the book session of February and drops only the third track session of March, which started after it.
|
||||
Assert.Equal(new[] { trackId, bookId }, history!.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(1, history.Data[0].CountedSessionCount);
|
||||
Assert.Equal(1, history.Data[0].CompletedSessionCount);
|
||||
Assert.Equal(55d, history.Data[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_trackSecondLastActivityOnUtc, history.Data[0].LastConsumedOnUtc);
|
||||
Assert.Equal(500d, history.Data[1].ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenPaginationIsRequested_ShouldReturnRequestedPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid newestBookId = await SeedBookAsync(libraryId, "Newest Book");
|
||||
Guid middleBookId = await SeedBookAsync(libraryId, "Middle Book");
|
||||
Guid oldestBookId = await SeedBookAsync(libraryId, "Oldest Book");
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, newestBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 3, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 3, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, middleBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 2, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, oldestBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 1, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed?currentPage=2&perPage=2");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(2, history!.CurrentPage);
|
||||
Assert.Equal(2, history.PerPage);
|
||||
Assert.Equal(3, history.Count);
|
||||
Assert.Equal(2, history.NumberOfPages);
|
||||
ConsumedItemResponse item = Assert.Single(history.Data);
|
||||
Assert.Equal(oldestBookId, item.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenAnotherUserHasHistory_ShouldReturnOnlyCurrentUserItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid ownLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Own Library");
|
||||
Guid ownBookId = await SeedBookAsync(ownLibraryId, "Own Book");
|
||||
await SeedRecordAsync(userId, ownLibraryId, MediaKind.Book, ownBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 1, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.EBook, "Other Library");
|
||||
Guid otherBookId = await SeedBookAsync(otherLibraryId, "Other User Secret Book");
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.Book, otherBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 2, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(ownBookId, item.MediaItemId);
|
||||
Assert.Equal("Own Book", item.Title);
|
||||
Assert.DoesNotContain(history.Data, candidate => candidate.Title == "Other User Secret Book");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenMediaItemNoLongerExists_ShouldReturnCountsWithBlankDisplayData()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid missingTrackId = Guid.NewGuid();
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, missingTrackId, ConsumptionStatus.Completed, s_trackFirstStartedOnUtc, s_missingItemLastActivityOnUtc, 30_000, 0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(MediaKind.MusicTrack, item.MediaKind);
|
||||
Assert.Equal(missingTrackId, item.MediaItemId);
|
||||
Assert.Equal(libraryId, item.LibraryId);
|
||||
Assert.False(item.IsAvailable);
|
||||
Assert.Equal(string.Empty, item.Title);
|
||||
Assert.Equal(string.Empty, item.CollectionTitle);
|
||||
Assert.Equal(string.Empty, item.CreatorName);
|
||||
Assert.Null(item.CoverPath);
|
||||
Assert.Equal(s_missingItemLastActivityOnUtc, item.LastConsumedOnUtc);
|
||||
Assert.Equal(1, item.CountedSessionCount);
|
||||
Assert.Equal(1, item.CompletedSessionCount);
|
||||
Assert.Equal(30d, item.ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // A number that is not a member name.
|
||||
[InlineData("1")] // A number that is a defined enumeration value, which must still be rejected.
|
||||
[InlineData("not-a-media-kind")] // A name that is not a member of the enumeration.
|
||||
public async Task GetRecentlyConsumed_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds two libraries owned by <paramref name="userId"/>, a track with three sessions, and a book with one session.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the libraries and the consumption records.</param>
|
||||
/// <returns>The Ids of the music library, the track, the ebook library, and the book, and the unique name of the book author.</returns>
|
||||
private async Task<(Guid musicLibraryId, Guid trackId, Guid bookLibraryId, Guid bookId, string authorName)> SeedConsumptionScenarioAsync(Guid userId)
|
||||
{
|
||||
// The contributor display name is unique across the whole database, so every test seeds its own spelling of the author.
|
||||
string authorName = $"J. R. R. Tolkien {Guid.NewGuid():N}";
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackId = await SeedTrackAsync(musicLibraryId, "Bohemian Rhapsody", "A Night at the Opera", "Queen", []);
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid bookId = await SeedBookAsync(bookLibraryId, "The Fellowship of the Ring", authorName, []);
|
||||
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_trackFirstStartedOnUtc, s_trackFirstLastActivityOnUtc, 40_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackSecondStartedOnUtc, s_trackSecondLastActivityOnUtc, 15_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackThirdStartedOnUtc, s_trackThirdLastActivityOnUtc, 45_000, 0);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, s_bookStartedOnUtc, s_bookLastActivityOnUtc, 500_000, 10);
|
||||
|
||||
return (musicLibraryId, trackId, bookLibraryId, bookId, authorName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of <paramref name="libraryId"/>, together with its artist and album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the track.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="albumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="tagNames">The tag names carried by the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName, IReadOnlyList<string> tagNames)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false));
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false);
|
||||
foreach (string tagName in tagNames)
|
||||
track.Tags.Add(_tagEntityFixture.Create(name: tagName));
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of <paramref name="libraryId"/>, together with an author contributor when a name is supplied.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <param name="authorName">The name of the author of the book, or <see langword="null"/> for no contributor.</param>
|
||||
/// <param name="tagNames">The tag names carried by the book.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null, IReadOnlyList<string>? tagNames = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid? contributorId = null;
|
||||
if (authorName is not null)
|
||||
{
|
||||
contributorId = Guid.NewGuid();
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId.Value, displayName: authorName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
foreach (string tagName in tagNames ?? [])
|
||||
book.Tags.Add(_tagEntityFixture.Create(name: tagName));
|
||||
if (contributorId is not null)
|
||||
book.Contributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId.Value, role: MediaContributorRole.Author));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
ConsumptionStatus status,
|
||||
DateTime startedOnUtc,
|
||||
DateTime lastActivityOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
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>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+498
@@ -0,0 +1,498 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserRecentlyConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserRecentlyConsumedEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 9, 55, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserRecentlyConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserRecentlyConsumedEndpointTests(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 GetUserRecentlyConsumed_WhenCurrentUserNamesTheirOwnId_ShouldReturnSameDataAsMeRoute()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid bookId = await SeedBookAsync(libraryId, "The Fellowship of the Ring", "J. R. R. Tolkien");
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, 500_000, 10);
|
||||
string query = "currentPage=1&perPage=10";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage meResponse = await _client.GetAsync($"/api/v1/users/me/consumption-history/recently-consumed?{query}");
|
||||
HttpResponseMessage userResponse = await _client.GetAsync($"/api/v1/users/{userId}/consumption-history/recently-consumed?{query}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, meResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, userResponse.StatusCode);
|
||||
AssertCacheHeaders(userResponse);
|
||||
|
||||
PaginatedResponse<ConsumedItemResponse>? meHistory = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(meResponse);
|
||||
PaginatedResponse<ConsumedItemResponse>? userHistory = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(userResponse);
|
||||
Assert.NotNull(meHistory);
|
||||
Assert.NotNull(userHistory);
|
||||
Assert.Equal(meHistory!.Count, userHistory!.Count);
|
||||
Assert.Equal(meHistory.CurrentPage, userHistory.CurrentPage);
|
||||
Assert.Equal(meHistory.PerPage, userHistory.PerPage);
|
||||
Assert.Equal(meHistory.NumberOfPages, userHistory.NumberOfPages);
|
||||
Assert.Equal(JsonSerializer.Serialize(meHistory.Data, _jsonOptions), JsonSerializer.Serialize(userHistory.Data, _jsonOptions));
|
||||
|
||||
ConsumedItemResponse item = Assert.Single(userHistory.Data);
|
||||
Assert.Equal(bookId, item.MediaItemId);
|
||||
Assert.Equal(libraryId, item.LibraryId);
|
||||
Assert.Equal("The Fellowship of the Ring", item.Title);
|
||||
Assert.Equal("J. R. R. Tolkien", item.CreatorName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenUserHasNoHistory_ShouldReturnEmptyPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-history/recently-consumed?currentPage=1&perPage=50");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Empty(history!.Data);
|
||||
Assert.Equal(1, history.CurrentPage);
|
||||
Assert.Equal(50, history.PerPage);
|
||||
Assert.Equal(0, history.Count);
|
||||
Assert.Equal(0, history.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.EBook, "Other Library");
|
||||
Guid otherBookId = await SeedBookAsync(otherLibraryId, "Other User Secret Book", "Secret Author");
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.Book, otherBookId, ConsumptionStatus.Completed, 500_000, 10);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-history/recently-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Other User Secret Book", content);
|
||||
Assert.DoesNotContain("Secret Author", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenAdminNamesAnotherUser_ShouldReturnThatUsersData()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedUserAsync($"targetuser_{Guid.NewGuid()}");
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.Music, "Target Music Library");
|
||||
Guid targetTrackId = await SeedTrackAsync(targetLibraryId, "The Show Must Go On", "Innuendo", "Queen");
|
||||
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, targetTrackId, ConsumptionStatus.Completed, 60_000, 0);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-history/recently-consumed");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(targetTrackId, item.MediaItemId);
|
||||
Assert.Equal(targetLibraryId, item.LibraryId);
|
||||
Assert.Equal("The Show Must Go On", item.Title);
|
||||
Assert.Equal("Innuendo", item.CollectionTitle);
|
||||
Assert.Equal("Queen", item.CreatorName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-history/recently-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/recently-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/recently-consumed";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/recently-consumed";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/recently-consumed";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of <paramref name="libraryId"/>, together with its artist and album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the track.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="albumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false));
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of <paramref name="libraryId"/>, together with an author contributor when a name is supplied.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <param name="authorName">The name of the author of the book, or <see langword="null"/> for no contributor.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid? contributorId = null;
|
||||
if (authorName is not null)
|
||||
{
|
||||
contributorId = Guid.NewGuid();
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId.Value, displayName: authorName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
if (contributorId is not null)
|
||||
book.Contributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId.Value, role: MediaContributorRole.Author));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a completed consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
ConsumptionStatus status,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : s_lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
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>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, 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(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+496
@@ -0,0 +1,496 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetTagConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTagConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTagConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_trackCompletedStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackStoppedStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookCompletedStartedOnUtc = new(2026, 2, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_uncountedBookStartedOnUtc = new(2026, 2, 5, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTagConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetTagConsumptionEndpointTests(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 GetTagConsumption_WhenTaggedItemsWereConsumed_ShouldReturnLowercaseTagsOrderedByItemCountThenDurationThenName()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid musicLibraryId, Guid bookLibraryId, string favouriteTag, string bookClubTag, string rockTag, string ignoredTag) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/tags");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(3, tags!.Count);
|
||||
Assert.All(tags, tag => Assert.Equal(tag.Name.ToLowerInvariant(), tag.Name));
|
||||
Assert.Equal(
|
||||
new[] { favouriteTag.ToLowerInvariant(), bookClubTag.ToLowerInvariant(), rockTag.ToLowerInvariant() },
|
||||
tags.Select(tag => tag.Name).ToArray());
|
||||
|
||||
Assert.Equal(2, tags[0].ConsumedItemCount);
|
||||
Assert.Equal(370d, tags[0].ConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, tags[1].ConsumedItemCount);
|
||||
Assert.Equal(300d, tags[1].ConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, tags[2].ConsumedItemCount);
|
||||
Assert.Equal(70d, tags[2].ConsumedDurationInSeconds, 3);
|
||||
Assert.DoesNotContain(tags, tag => tag.Name == ignoredTag.ToLowerInvariant());
|
||||
Assert.NotEqual(musicLibraryId, bookLibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryTags()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookLibraryId, string favouriteTag, string bookClubTag, _, string ignoredTag) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/tags?libraryId={bookLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(
|
||||
new[] { bookClubTag.ToLowerInvariant(), favouriteTag.ToLowerInvariant() },
|
||||
tags!.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(1, tag.ConsumedItemCount));
|
||||
Assert.All(tags, tag => Assert.Equal(300d, tag.ConsumedDurationInSeconds, 3));
|
||||
Assert.DoesNotContain(tags, tag => tag.Name == ignoredTag.ToLowerInvariant());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKindTags()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, string favouriteTag, _, string rockTag, _) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/tags?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(
|
||||
new[] { favouriteTag.ToLowerInvariant(), rockTag.ToLowerInvariant() },
|
||||
tags!.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(1, tag.ConsumedItemCount));
|
||||
Assert.All(tags, tag => Assert.Equal(70d, tag.ConsumedDurationInSeconds, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, string favouriteTag, _, string rockTag, _) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/tags?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(
|
||||
new[] { favouriteTag.ToLowerInvariant(), rockTag.ToLowerInvariant() },
|
||||
tags!.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(70d, tag.ConsumedDurationInSeconds, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, string favouriteTag, string bookClubTag, _, _) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
string toUtc = Uri.EscapeDataString("2026-02-28T23:59:59");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/tags?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(
|
||||
new[] { bookClubTag.ToLowerInvariant(), favouriteTag.ToLowerInvariant() },
|
||||
tags!.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(1, tag.ConsumedItemCount));
|
||||
Assert.All(tags, tag => Assert.Equal(300d, tag.ConsumedDurationInSeconds, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenHistoryIsEmpty_ShouldReturnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
_ = GetCurrentUserId();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/tags");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Empty(tags!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-statistics/tags";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/tags";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/tags";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // A number that is not a member name.
|
||||
[InlineData("1")] // A number that is a defined enumeration value, which must still be rejected.
|
||||
[InlineData("not-a-media-kind")] // A name that is not a member of the enumeration.
|
||||
public async Task GetTagConsumption_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/tags";
|
||||
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/tags";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a tagged track with a counted and an uncounted session, a tagged book with a counted session, and a tagged book without any counted session.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the libraries and the consumption records.</param>
|
||||
/// <returns>
|
||||
/// The Ids of the music library and the ebook library, and the unique favourite, book club, rock, and ignored tag names that were seeded.
|
||||
/// </returns>
|
||||
private async Task<(Guid musicLibraryId, Guid bookLibraryId, string favouriteTag, string bookClubTag, string rockTag, string ignoredTag)> SeedTaggedConsumptionScenarioAsync(Guid userId)
|
||||
{
|
||||
// Each test seeds its own tag rows, so every name carries a unique suffix to keep the shared Tags table collision free.
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
string favouriteTag = $"Favourite-{suffix}";
|
||||
string bookClubTag = $"Book-Club-{suffix}";
|
||||
string rockTag = $"Rock-{suffix}";
|
||||
string ignoredTag = $"Ignored-{suffix}";
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// The track and the book share a tag, so the tag rows are resolved once per name, and the whole graph is saved through one context, so the
|
||||
// shared row is inserted once instead of once per item that carries it.
|
||||
Dictionary<string, TagEntity> tags = [];
|
||||
TagEntity ResolveTag(string name)
|
||||
{
|
||||
if (!tags.TryGetValue(name, out TagEntity? tag))
|
||||
{
|
||||
tag = _tagEntityFixture.Create(name: name);
|
||||
tags[name] = tag;
|
||||
}
|
||||
return tag;
|
||||
}
|
||||
|
||||
Guid musicLibraryId = Guid.NewGuid();
|
||||
Guid bookLibraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid uncountedBookId = Guid.NewGuid();
|
||||
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: musicLibraryId, userId: userId, title: "Music Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: bookLibraryId, userId: userId, title: "Book Library", libraryType: LibraryType.EBook, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: musicLibraryId, name: "Queen", includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: musicLibraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false));
|
||||
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: musicLibraryId, path: $"/music/{trackId:N}.flac", title: "Bohemian Rhapsody", includeMetadata: false);
|
||||
track.Tags.Add(ResolveTag(rockTag));
|
||||
track.Tags.Add(ResolveTag(favouriteTag));
|
||||
dbContext.Tracks.Add(track);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: bookLibraryId, path: $"/books/{bookId:N}.epub", title: "The Fellowship of the Ring", includeMetadata: false);
|
||||
book.Tags.Add(ResolveTag(favouriteTag));
|
||||
book.Tags.Add(ResolveTag(bookClubTag));
|
||||
dbContext.Books.Add(book);
|
||||
|
||||
BookEntity uncountedBook = _bookEntityFixture.Create(id: uncountedBookId, libraryId: bookLibraryId, path: $"/books/{uncountedBookId:N}.epub", title: "Uncounted Book", includeMetadata: false);
|
||||
uncountedBook.Tags.Add(ResolveTag(ignoredTag));
|
||||
dbContext.Books.Add(uncountedBook);
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_trackCompletedStartedOnUtc, 60_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackStoppedStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, s_bookCompletedStartedOnUtc, 300_000, 10);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, uncountedBookId, ConsumptionStatus.Stopped, s_uncountedBookStartedOnUtc, 500_000, 3);
|
||||
|
||||
return (musicLibraryId, bookLibraryId, favouriteTag, bookClubTag, rockTag, ignoredTag);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
ConsumptionStatus status,
|
||||
DateTime startedOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc.AddMinutes(1),
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+459
@@ -0,0 +1,459 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetTagConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserTagConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserTagConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserTagConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserTagConsumptionEndpointTests(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 GetUserTagConsumption_WhenCurrentUserNamesTheirOwnId_ShouldReturnTheirTagStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
string firstTag = $"First-{Guid.NewGuid():N}";
|
||||
string secondTag = $"Second-{Guid.NewGuid():N}";
|
||||
Guid trackId = await SeedTrackAsync(libraryId, "Bohemian Rhapsody", "A Night at the Opera", "Queen", [firstTag, secondTag]);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, 60_000, 0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-statistics/tags");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(2, tags!.Count);
|
||||
Assert.Equal(
|
||||
new[] { firstTag.ToLowerInvariant(), secondTag.ToLowerInvariant() },
|
||||
tags.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(1, tag.ConsumedItemCount));
|
||||
Assert.All(tags, tag => Assert.Equal(60d, tag.ConsumedDurationInSeconds, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other Library");
|
||||
string secretTag = $"Secret-{Guid.NewGuid():N}";
|
||||
Guid otherTrackId = await SeedTrackAsync(otherLibraryId, "Secret Track", "Secret Album", "Secret Artist", [secretTag]);
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.MusicTrack, otherTrackId, 60_000, 0);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-statistics/tags";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(secretTag.ToLowerInvariant(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Secret Track", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenAdminNamesAnotherUser_ShouldReturnThatUsersTagStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedUserAsync($"targetuser_{Guid.NewGuid()}");
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.EBook, "Target Book Library");
|
||||
string targetTag = $"Target-{Guid.NewGuid():N}";
|
||||
Guid targetBookId = await SeedBookAsync(targetLibraryId, "Target Book", [targetTag]);
|
||||
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.Book, targetBookId, 300_000, 10);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-statistics/tags");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
TagConsumptionResponse tag = Assert.Single(tags!);
|
||||
Assert.Equal(targetTag.ToLowerInvariant(), tag.Name);
|
||||
Assert.Equal(1, tag.ConsumedItemCount);
|
||||
Assert.Equal(300d, tag.ConsumedDurationInSeconds, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-statistics/tags";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-statistics/tags";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics/tags";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics/tags";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics/tags";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a tagged track of <paramref name="libraryId"/>, together with its artist and album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the track.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="albumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="tagNames">The tag names carried by the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName, IReadOnlyList<string> tagNames)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false));
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false);
|
||||
foreach (string tagName in tagNames)
|
||||
track.Tags.Add(_tagEntityFixture.Create(name: tagName));
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a tagged book of <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <param name="tagNames">The tag names carried by the book.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, IReadOnlyList<string> tagNames)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
foreach (string tagName in tagNames)
|
||||
book.Tags.Add(_tagEntityFixture.Create(name: tagName));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a completed consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_startedOnUtc.AddMinutes(1),
|
||||
endedOnUtc: s_startedOnUtc.AddMinutes(2),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
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>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, 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(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+1928
File diff suppressed because it is too large.
Load diff
+420
@@ -0,0 +1,420 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
|
||||
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.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteBookEndpointTests(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 DeleteBook_WhenBookBelongsToAnOwnedLibrary_ShouldSoftDeleteTheBook()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/books/{bookId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
BookEntity? book = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId);
|
||||
Assert.NotNull(book);
|
||||
Assert.True(book!.IsDeleted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteBook_WhenBookHasStoredArtwork_ShouldKeepTheArtworkAndTheStoredCoverFileForRestore()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid bookId, string storedCoverPath) = await SeedLibraryBookAndCoverAsync(userId);
|
||||
string fullCoverPath = Path.Combine(AppContext.BaseDirectory, storedCoverPath.TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
|
||||
Assert.True(File.Exists(fullCoverPath));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/books/{bookId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
BookEntity? book = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId);
|
||||
Assert.NotNull(book);
|
||||
Assert.True(book!.IsDeleted);
|
||||
Assert.NotNull(await dbContext.Books.SelectMany(book => book.Artwork).FirstOrDefaultAsync(artwork => artwork.BookId == bookId));
|
||||
Assert.True(File.Exists(fullCoverPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteBook_WhenBookIsSoftDeleted_ShouldHideItFromTheCatalogueAndReadingEndpoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
|
||||
HttpResponseMessage deleteResponse = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/books/{bookId}");
|
||||
deleteResponse.EnsureSuccessStatusCode();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage booksResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books");
|
||||
HttpResponseMessage booksLiteResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite");
|
||||
HttpResponseMessage bookResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}");
|
||||
HttpResponseMessage availabilityResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability");
|
||||
HttpResponseMessage manifestResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest");
|
||||
HttpResponseMessage sectionResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/section-1");
|
||||
HttpResponseMessage resourceResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/resource-1");
|
||||
|
||||
// Assert
|
||||
PaginatedResponse<BookResponse>? books = await booksResponse.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
|
||||
Assert.NotNull(books);
|
||||
Assert.Equal(0, books!.Count);
|
||||
Assert.Empty(books.Data);
|
||||
PaginatedResponse<BookLiteResponse>? booksLite = await booksLiteResponse.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(booksLite);
|
||||
Assert.Equal(0, booksLite!.Count);
|
||||
Assert.Empty(booksLite.Data);
|
||||
await AssertNotFoundAsync(bookResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}");
|
||||
await AssertNotFoundAsync(availabilityResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability");
|
||||
await AssertNotFoundAsync(manifestResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest");
|
||||
await AssertNotFoundAsync(sectionResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/section-1");
|
||||
await AssertNotFoundAsync(resourceResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/resource-1");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteBook_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/books/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "BookNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteBook_WhenBookRequestedThroughDifferentLibrary_ShouldReturnBookNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookId) = await SeedLibraryAndBookAsync(userId);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
// The route library id is enforced, so a book can never be deleted through another library's route, and the mismatch is
|
||||
// reported as not found, without disclosing that the book exists in another library.
|
||||
await AssertNotFoundAsync(response, "BookNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteBook_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherBookId) = await SeedLibraryAndBookAsync(otherUserId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/books/{otherBookId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteBook_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/not-a-guid/books/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteBook_WhenBookIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "BookIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an ebook library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an ebook library owned by <paramref name="userId"/> and a book belonging to it.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library and book.</returns>
|
||||
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false);
|
||||
dbContext.Libraries.Add(library);
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, bookId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an ebook library owned by <paramref name="userId"/>, a book belonging to it, and a stored cover file of that book together with its artwork row.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library and book, and the relative path of the stored cover file.</returns>
|
||||
private async Task<(Guid libraryId, Guid bookId, string storedCoverPath)> SeedLibraryBookAndCoverAsync(Guid userId)
|
||||
{
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
LibraryEntity library = await dbContext.Libraries.SingleAsync(library => library.Id == libraryId);
|
||||
BookEntity book = await dbContext.Books.Include(book => book.Artwork).SingleAsync(book => book.Id == bookId);
|
||||
IBookArtworkService bookArtworkService = scope.ServiceProvider.GetRequiredService<IBookArtworkService>();
|
||||
|
||||
// Store a minimal PNG-like payload through the same artwork service that the API uses, so that the stored path matches the one the deletion resolves.
|
||||
byte[] payload = new byte[100];
|
||||
payload[0] = 137;
|
||||
payload[1] = 80;
|
||||
payload[2] = 78;
|
||||
payload[3] = 71;
|
||||
payload[4] = 13;
|
||||
payload[5] = 10;
|
||||
payload[6] = 26;
|
||||
payload[7] = 10;
|
||||
Result<string> saveArtworkResult;
|
||||
using (MemoryStream artworkStream = new(payload))
|
||||
saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(libraryId, bookId, library.Title, string.Empty, book.Title, artworkStream, "cover.png", CancellationToken.None);
|
||||
Assert.False(saveArtworkResult.IsFailure);
|
||||
|
||||
book.Artwork.Add(_bookArtworkEntityFixture.Create(bookId: bookId, fileName: saveArtworkResult.Value));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, bookId, saveArtworkResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user 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>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
Loaded 100 of 6450 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user