Implements tests for commit 525ac1348d

Covers the favorites feature and the playlist and favorite pagination changes with unit, integration and security tests, and fixtures for the new request, response, DTO and entity types.

Also fixes the issues found while covering the commit: declares FavoriteMediaKind.None as the default value and rejects it in every favorite operation; queues the favorite added domain event only after the persisted favorite is read back; and preserves the private, no-store cache header on view pages after the antiforgery and session middlewares overwrite it.
This commit is contained in:
BinaryAlley committed 2026-10-29 10:13:57 +02:00
1 parent 468f1846f1
commit 394f6b510c
135 files changed
+19167 -13

No files matched your search

@@ -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();
}
}
@@ -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();
}
}
@@ -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();
}
}
@@ -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();
}
}
@@ -0,0 +1,530 @@
#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.Playlists;
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.Playlists;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.Playlists;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylist;
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.Playlists.GetPlaylist;
/// <summary>
/// Contains integration tests for the <see cref="GetPlaylistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaylistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private const string PATH = "/api/v1/users/me/playlists";
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 PlaylistEntityFixture _playlistEntityFixture = new();
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<Guid> _seededLibraryIds = [];
private readonly List<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaylistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPlaylistEndpointTests(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 GetPlaylist_WhenThePlaylistExists_ShouldReturnItWithItsPageOfEntriesAndDensePositions()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid musicLibraryId = await SeedLibraryAsync(userId);
Guid artistId = await SeedArtistAsync(musicLibraryId, "Queen");
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Innuendo");
Guid firstTrackId = await SeedTrackAsync(musicLibraryId, albumId, "Innuendo", 393);
Guid secondTrackId = await SeedTrackAsync(musicLibraryId, albumId, "The Show Must Go On", 262);
await SeedAlbumCoverAsync(albumId, "innuendo-cover.jpg");
Guid deletedTrackId = Guid.NewGuid();
Guid playlistId = await SeedPlaylistAsync(userId, "Evening listening");
// The stored order keys are sparse, so the response must expose dense zero based display positions instead.
await SeedPlaylistEntryAsync(playlistId, firstTrackId, 0);
await SeedPlaylistEntryAsync(playlistId, secondTrackId, 1_000_000_000L);
await SeedPlaylistEntryAsync(playlistId, deletedTrackId, 2_000_000_000L);
// Act
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertCacheHeaders(response);
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
Assert.NotNull(playlist);
Assert.Equal(playlistId, playlist!.Id);
Assert.Equal("Evening listening", playlist.Name);
Assert.Equal(PlaylistType.Music, playlist.Type);
Assert.Equal(3, playlist.Entries.Count);
Assert.Equal(1, playlist.Entries.CurrentPage);
Assert.Equal(3, playlist.Entries.PerPage);
Assert.Equal(1, playlist.Entries.NumberOfPages);
Assert.Equal([0, 1, 2], playlist.Entries.Data.Select(entry => entry.Position));
PlaylistEntryResponse firstEntry = playlist.Entries.Data[0];
Assert.Equal(firstTrackId, firstEntry.MediaItemId);
Assert.Equal(PlaylistMediaItemType.MusicTrack, firstEntry.MediaItemType);
Assert.Equal(musicLibraryId, firstEntry.LibraryId);
Assert.Equal("Innuendo", firstEntry.MediaItemTitle);
Assert.Equal(albumId, firstEntry.CollectionId);
Assert.Equal("Innuendo", firstEntry.CollectionTitle);
Assert.Equal(artistId, firstEntry.CreatorId);
Assert.Equal("Queen", firstEntry.CreatorName);
Assert.Equal(393, firstEntry.DurationInSeconds);
Assert.Equal("innuendo-cover.jpg", firstEntry.CoverPath);
PlaylistEntryResponse deletedEntry = playlist.Entries.Data[2];
Assert.Equal(deletedTrackId, deletedEntry.MediaItemId);
Assert.Equal(Guid.Empty, deletedEntry.LibraryId);
Assert.Equal(string.Empty, deletedEntry.MediaItemTitle);
Assert.Equal(Guid.Empty, deletedEntry.CollectionId);
Assert.Equal(Guid.Empty, deletedEntry.CreatorId);
Assert.Equal(0, deletedEntry.DurationInSeconds);
Assert.Null(deletedEntry.CoverPath);
}
[Fact]
public async Task GetPlaylist_WhenThePlaylistIsEmpty_ShouldReturnAnEmptyPage()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Nothing yet");
// Act
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
Assert.NotNull(playlist);
Assert.Empty(playlist!.Entries.Data);
Assert.Equal(0, playlist.Entries.Count);
Assert.Equal(1, playlist.Entries.CurrentPage);
}
[Fact]
public async Task GetPlaylist_WhenNoPaginationIsRequested_ShouldReturnEveryEntryInOnePage()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Every entry");
for (int index = 0; index < 4; index++)
await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), index * 1_000_000_000L);
// Act
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
Assert.NotNull(playlist);
Assert.Equal(1, playlist!.Entries.CurrentPage);
Assert.Equal(4, playlist.Entries.PerPage);
Assert.Equal(4, playlist.Entries.Count);
Assert.Equal(1, playlist.Entries.NumberOfPages);
Assert.Equal([0, 1, 2, 3], playlist.Entries.Data.Select(entry => entry.Position));
}
[Fact]
public async Task GetPlaylist_WhenAPageIsRequested_ShouldReturnOnlyThatPageWithThePaginationMetadata()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Paged playlist");
for (int index = 0; index < 3; index++)
await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), index * 1_000_000_000L);
// Act
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}?currentPage=2&perPage=2");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertCacheHeaders(response);
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
Assert.NotNull(playlist);
Assert.Equal(2, playlist!.Entries.CurrentPage);
Assert.Equal(2, playlist.Entries.PerPage);
Assert.Equal(3, playlist.Entries.Count);
Assert.Equal(2, playlist.Entries.NumberOfPages);
PlaylistEntryResponse entry = Assert.Single(playlist.Entries.Data);
// The display position stays dense across pages, so the only entry of the second page is the third entry of the playlist.
Assert.Equal(2, entry.Position);
}
[Fact]
public async Task GetPlaylist_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFound()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist");
// Act
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{otherPlaylistId}");
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", $"{PATH}/{otherPlaylistId}");
AssertCacheHeaders(response);
}
[Fact]
public async Task GetPlaylist_WhenThePlaylistDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid playlistId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", $"{PATH}/{playlistId}");
AssertCacheHeaders(response);
}
[Fact]
public async Task GetPlaylist_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"{PATH}/not-a-guid");
// Assert
await AssertValidationProblemAsync(response, $"{PATH}/not-a-guid", "PlaylistIdCannotBeEmpty");
AssertCacheHeaders(response);
}
[Fact]
public async Task GetPlaylist_WhenThePlaylistIdIsEmpty_ShouldReturnValidationProblem()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{Guid.Empty}");
// Assert
await AssertValidationProblemAsync(response, $"{PATH}/{Guid.Empty}", "PlaylistIdCannotBeEmpty");
}
/// <summary>
/// Seeds a media library 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>
/// <returns>The Id of the seeded media 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: $"Library-{Guid.NewGuid():N}", 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,
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));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid playlistId = Guid.NewGuid();
dbContext.Playlists.Add(_playlistEntityFixture.Create(
id: playlistId,
userId: userId,
name: name,
type: PlaylistType.Music,
entryCount: 0,
version: 0,
createdBy: userId));
await dbContext.SaveChangesAsync();
_seededPlaylistIds.Add(playlistId);
return playlistId;
}
/// <summary>
/// Seeds an entry of the playlist identified by <paramref name="playlistId"/>.
/// </summary>
/// <param name="playlistId">The Id of the playlist the entry belongs to.</param>
/// <param name="mediaItemId">The Id of the referenced media item.</param>
/// <param name="position">The sparse order key of the entry.</param>
private async Task SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create(
playlistId: playlistId,
mediaItemId: mediaItemId,
mediaItemType: PlaylistMediaItemType.MusicTrack,
position: position));
await dbContext.SaveChangesAsync();
}
/// <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()));
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
}
/// <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>();
List<Guid> libraryIds = [.. _seededLibraryIds];
List<Guid> playlistIds = [.. _seededPlaylistIds];
List<Guid> albumIds = await dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)).Select(album => album.Id).ToListAsync();
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
dbContext.MusicArtwork.RemoveRange(dbContext.MusicArtwork.Where(artwork => albumIds.Contains(artwork.OwnerId)));
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.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
await dbContext.SaveChangesAsync();
}
await _apiFactory.RemoveTestUserAsync();
}
}