Adds music stack test coverage and fixes playlist cache and stream error handling

This commit is contained in:
BinaryAlley committed 2026-10-29 15:46:24 +02:00
1 parent 394f6b510c
commit aba803b106
197 files changed
+29081 -34

No files matched your search

@@ -0,0 +1,586 @@
#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.Fixtures.Core.Requests.Playlists;
using Lumina.Contracts.Requests.Playlists;
using Lumina.Contracts.Responses.Playlists;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntries;
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.Playlists.AddPlaylistEntries;
/// <summary>
/// Contains integration tests for the <see cref="AddPlaylistEntriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntriesEndpointTests : 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 PlaylistEntityFixture _playlistEntityFixture = new();
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly AddPlaylistEntriesRequestFixture _addPlaylistEntriesRequestFixture = 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="AddPlaylistEntriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddPlaylistEntriesEndpointTests(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 AddPlaylistEntries_WhenTheTracksExist_ShouldAppendEveryEntryInTheRequestedOrder()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "Innuendo");
Guid firstTrackId = await SeedTrackAsync(libraryId, albumId, "Innuendo", 393);
Guid secondTrackId = await SeedTrackAsync(libraryId, albumId, "The Show Must Go On", 262);
Guid thirdTrackId = await SeedTrackAsync(libraryId, albumId, "These Are the Days of Our Lives", 255);
Guid playlistId = await SeedPlaylistAsync(userId, "Evening listening", entryCount: 0);
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [thirdTrackId, firstTrackId, secondTrackId]);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-batch", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("private", response.Headers.CacheControl?.ToString());
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
Assert.Contains("Authorization", response.Headers.Vary);
PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync<PlaylistEntriesAddedResponse>(response);
Assert.NotNull(addedEntries);
Assert.Equal(playlistId, addedEntries!.PlaylistId);
Assert.Equal(3, addedEntries.AddedCount);
Assert.NotEqual(default, addedEntries.UpdatedOnUtc);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> storedTrackIds = await GetOrderedTrackIdsAsync(dbContext, playlistId);
Assert.Equal([thirdTrackId, firstTrackId, secondTrackId], storedTrackIds);
PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId);
Assert.Equal(3, playlist.EntryCount);
}
[Fact]
public async Task AddPlaylistEntries_WhenTheSameTrackAppearsTwice_ShouldKeepOneEntryPerOccurrence()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "News of the World");
Guid firstTrackId = await SeedTrackAsync(libraryId, albumId, "We Will Rock You", 122);
Guid secondTrackId = await SeedTrackAsync(libraryId, albumId, "We Are the Champions", 179);
Guid playlistId = await SeedPlaylistAsync(userId, "Repeats allowed", entryCount: 0);
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [firstTrackId, secondTrackId, firstTrackId]);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-batch", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync<PlaylistEntriesAddedResponse>(response);
Assert.NotNull(addedEntries);
Assert.Equal(3, addedEntries!.AddedCount);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> storedTrackIds = await GetOrderedTrackIdsAsync(dbContext, playlistId);
Assert.Equal([firstTrackId, secondTrackId, firstTrackId], storedTrackIds);
}
[Fact]
public async Task AddPlaylistEntries_WhenThePlaylistAlreadyHasEntries_ShouldAppendAfterThem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
Guid existingTrackId = await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 354);
Guid firstNewTrackId = await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219);
Guid secondNewTrackId = await SeedTrackAsync(libraryId, albumId, "You're My Best Friend", 170);
Guid playlistId = await SeedPlaylistAsync(userId, "Append after existing", entryCount: 1);
await SeedPlaylistEntryAsync(playlistId, existingTrackId, 0);
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [firstNewTrackId, secondNewTrackId]);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-batch", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync<PlaylistEntriesAddedResponse>(response);
Assert.NotNull(addedEntries);
Assert.Equal(2, addedEntries!.AddedCount);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> storedTrackIds = await GetOrderedTrackIdsAsync(dbContext, playlistId);
Assert.Equal([existingTrackId, firstNewTrackId, secondNewTrackId], storedTrackIds);
}
[Fact]
public async Task AddPlaylistEntries_WhenTheTrackListIsMissing_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "No tracks", entryCount: 0);
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(includeTrackIds: false);
string url = $"{PATH}/{playlistId}/entries-batch";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "TrackIdCannotBeEmpty");
}
[Fact]
public async Task AddPlaylistEntries_WhenTheTrackListIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Empty batch", entryCount: 0);
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: []);
string url = $"{PATH}/{playlistId}/entries-batch";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "TrackIdCannotBeEmpty");
}
[Fact]
public async Task AddPlaylistEntries_WhenAnEntryIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Empty entry", entryCount: 0);
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [Guid.NewGuid(), Guid.Empty]);
string url = $"{PATH}/{playlistId}/entries-batch";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "TrackIdCannotBeEmpty");
}
[Fact]
public async Task AddPlaylistEntries_WhenThePlaylistDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid playlistId = Guid.NewGuid();
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create();
string url = $"{PATH}/{playlistId}/entries-batch";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
}
[Fact]
public async Task AddPlaylistEntries_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundWithoutAddingEntries()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "Someone Else");
Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Private Album");
Guid otherTrackId = await SeedTrackAsync(otherLibraryId, otherAlbumId, "Private Track", 200);
Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", entryCount: 0);
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [otherTrackId]);
string url = $"{PATH}/{otherPlaylistId}/entries-batch";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == otherPlaylistId));
}
[Fact]
public async Task AddPlaylistEntries_WhenOneTrackDoesNotExist_ShouldReturnTrackNotFoundAndAddNothing()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "Jazz");
Guid existingTrackId = await SeedTrackAsync(libraryId, albumId, "Bicycle Race", 184);
Guid playlistId = await SeedPlaylistAsync(userId, "Partial batch", entryCount: 0);
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [existingTrackId, Guid.NewGuid()]);
string url = $"{PATH}/{playlistId}/entries-batch";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId));
}
[Fact]
public async Task AddPlaylistEntries_WhenATrackBelongsToAnotherUsersLibrary_ShouldReturnTheSameNotFoundAsAMissingTrack()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Only my library", entryCount: 0);
Guid otherUserId = await SeedOtherUserAsync();
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "Not Mine");
Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Not Mine Either");
Guid otherTrackId = await SeedTrackAsync(otherLibraryId, otherAlbumId, "Unreachable Track", 210);
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [otherTrackId]);
string url = $"{PATH}/{playlistId}/entries-batch";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId));
}
[Fact]
public async Task AddPlaylistEntries_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem()
{
// Arrange
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create();
string url = $"{PATH}/not-a-guid/entries-batch";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty");
}
/// <summary>
/// Reads the media item Ids of the entries of <paramref name="playlistId"/>, in stored order.
/// </summary>
/// <param name="dbContext">The database context to read from.</param>
/// <param name="playlistId">The Id of the playlist whose entries are read.</param>
/// <returns>The media item Ids in stored order.</returns>
private static async Task<List<Guid>> GetOrderedTrackIdsAsync(LuminaDbContext dbContext, Guid playlistId)
{
return await dbContext.PlaylistEntries
.AsNoTracking()
.Where(candidate => candidate.PlaylistId == playlistId)
.OrderBy(candidate => candidate.Position)
.Select(candidate => candidate.MediaItemId)
.ToListAsync();
}
/// <summary>
/// Seeds a music 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();
dbContext.Albums.Add(_albumEntityFixture.Create(
id: albumId,
artistId: artistId,
libraryId: libraryId,
title: title,
includeTracks: false,
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false));
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 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>
/// <param name="entryCount">The number of entries the playlist already holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
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: entryCount,
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 track.</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();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", 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 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];
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
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();
}
}
@@ -0,0 +1,579 @@
#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.Fixtures.Core.Requests.Playlists;
using Lumina.Contracts.Requests.Playlists;
using Lumina.Contracts.Responses.Playlists;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntry;
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.Playlists.AddPlaylistEntry;
/// <summary>
/// Contains integration tests for the <see cref="AddPlaylistEntryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntryEndpointTests : 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 PlaylistEntityFixture _playlistEntityFixture = new();
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly AddPlaylistEntryRequestFixture _addPlaylistEntryRequestFixture = 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="AddPlaylistEntryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddPlaylistEntryEndpointTests(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 AddPlaylistEntry_WhenThePlaylistAndTrackExist_ShouldAppendTheEntryAndReturnIt()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "Innuendo");
Guid trackId = await SeedTrackAsync(libraryId, albumId, "Innuendo", 393);
Guid playlistId = await SeedPlaylistAsync(userId, "Evening listening", entryCount: 0);
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: trackId);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("private", response.Headers.CacheControl?.ToString());
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
Assert.Contains("Authorization", response.Headers.Vary);
PlaylistEntryAddedResponse? addedEntry = await DeserializeAsync<PlaylistEntryAddedResponse>(response);
Assert.NotNull(addedEntry);
Assert.Equal(playlistId, addedEntry!.PlaylistId);
Assert.NotEqual(default, addedEntry.UpdatedOnUtc);
PlaylistEntryResponse entry = addedEntry.Entry;
Assert.NotEqual(Guid.Empty, entry.Id);
Assert.Equal(trackId, entry.MediaItemId);
Assert.Equal(PlaylistMediaItemType.MusicTrack, entry.MediaItemType);
Assert.Equal(0, entry.Position);
Assert.Equal(libraryId, entry.LibraryId);
Assert.Equal(albumId, entry.CollectionId);
Assert.Equal(artistId, entry.CreatorId);
Assert.Equal("Innuendo", entry.MediaItemTitle);
Assert.Equal("Innuendo", entry.CollectionTitle);
Assert.Equal("Queen", entry.CreatorName);
Assert.Equal(393, entry.DurationInSeconds);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
PlaylistEntryEntity? storedEntry = await dbContext.PlaylistEntries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == entry.Id);
Assert.NotNull(storedEntry);
Assert.Equal(playlistId, storedEntry!.PlaylistId);
Assert.Equal(trackId, storedEntry.MediaItemId);
Assert.Equal(0, storedEntry.Position);
PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId);
Assert.Equal(1, playlist.EntryCount);
}
[Fact]
public async Task AddPlaylistEntry_WhenThePlaylistAlreadyHasEntries_ShouldAppendTheEntryAtTheNextDensePosition()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Kind of Magic");
Guid firstTrackId = await SeedTrackAsync(libraryId, albumId, "One Vision", 308);
Guid secondTrackId = await SeedTrackAsync(libraryId, albumId, "A Kind of Magic", 262);
Guid thirdTrackId = await SeedTrackAsync(libraryId, albumId, "Friends Will Be Friends", 248);
Guid playlistId = await SeedPlaylistAsync(userId, "Ordered listening", entryCount: 2);
await SeedPlaylistEntryAsync(playlistId, firstTrackId, 0);
await SeedPlaylistEntryAsync(playlistId, secondTrackId, 1_000_000_000L);
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: thirdTrackId);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistEntryAddedResponse? addedEntry = await DeserializeAsync<PlaylistEntryAddedResponse>(response);
Assert.NotNull(addedEntry);
// The stored order keys are sparse, so the appended entry reports the dense display position derived from the entry count.
Assert.Equal(2, addedEntry!.Entry.Position);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> storedTrackIds = await dbContext.PlaylistEntries
.AsNoTracking()
.Where(candidate => candidate.PlaylistId == playlistId)
.OrderBy(candidate => candidate.Position)
.Select(candidate => candidate.MediaItemId)
.ToListAsync();
Assert.Equal([firstTrackId, secondTrackId, thirdTrackId], storedTrackIds);
}
[Fact]
public async Task AddPlaylistEntry_WhenTheSameTrackIsAddedTwice_ShouldKeepBothEntries()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "News of the World");
Guid trackId = await SeedTrackAsync(libraryId, albumId, "We Will Rock You", 122);
Guid playlistId = await SeedPlaylistAsync(userId, "Repeats allowed", entryCount: 0);
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: trackId);
// Act
HttpResponseMessage firstResponse = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries", request);
HttpResponseMessage secondResponse = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries", request);
// Assert
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
PlaylistEntryAddedResponse? firstEntry = await DeserializeAsync<PlaylistEntryAddedResponse>(firstResponse);
PlaylistEntryAddedResponse? secondEntry = await DeserializeAsync<PlaylistEntryAddedResponse>(secondResponse);
Assert.NotNull(firstEntry);
Assert.NotNull(secondEntry);
Assert.NotEqual(firstEntry!.Entry.Id, secondEntry!.Entry.Id);
Assert.Equal(0, firstEntry.Entry.Position);
Assert.Equal(1, secondEntry.Entry.Position);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(2, await dbContext.PlaylistEntries.CountAsync(candidate => candidate.PlaylistId == playlistId && candidate.MediaItemId == trackId));
}
[Fact]
public async Task AddPlaylistEntry_WhenThePlaylistDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "Jazz");
Guid trackId = await SeedTrackAsync(libraryId, albumId, "Bicycle Race", 184);
Guid playlistId = Guid.NewGuid();
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: trackId);
string url = $"{PATH}/{playlistId}/entries";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
}
[Fact]
public async Task AddPlaylistEntry_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundWithoutAddingAnEntry()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "Someone Else");
Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Private Album");
Guid otherTrackId = await SeedTrackAsync(otherLibraryId, otherAlbumId, "Private Track", 200);
Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", entryCount: 0);
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: otherTrackId);
string url = $"{PATH}/{otherPlaylistId}/entries";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == otherPlaylistId));
}
[Fact]
public async Task AddPlaylistEntry_WhenTheTrackDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Missing track", entryCount: 0);
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: Guid.NewGuid());
string url = $"{PATH}/{playlistId}/entries";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId));
}
[Fact]
public async Task AddPlaylistEntry_WhenTheTrackBelongsToAnotherUsersLibrary_ShouldReturnTheSameNotFoundAsAMissingTrack()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Only my library", entryCount: 0);
Guid otherUserId = await SeedOtherUserAsync();
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "Not Mine");
Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Not Mine Either");
Guid otherTrackId = await SeedTrackAsync(otherLibraryId, otherAlbumId, "Unreachable Track", 210);
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: otherTrackId);
string url = $"{PATH}/{playlistId}/entries";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
// The unreachable track is reported exactly like a missing one, so the response cannot be used to probe another user's library.
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId));
}
[Fact]
public async Task AddPlaylistEntry_WhenTheTrackIdIsMissing_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "No track", entryCount: 0);
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(includeTrackId: false);
string url = $"{PATH}/{playlistId}/entries";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "TrackIdCannotBeEmpty");
}
[Fact]
public async Task AddPlaylistEntry_WhenTheTrackIdIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Empty track id", entryCount: 0);
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: Guid.Empty);
string url = $"{PATH}/{playlistId}/entries";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "TrackIdCannotBeEmpty");
}
[Fact]
public async Task AddPlaylistEntry_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem()
{
// Arrange
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: Guid.NewGuid());
string url = $"{PATH}/not-a-guid/entries";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty");
}
/// <summary>
/// Seeds a music 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();
dbContext.Albums.Add(_albumEntityFixture.Create(
id: albumId,
artistId: artistId,
libraryId: libraryId,
title: title,
includeTracks: false,
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false));
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 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>
/// <param name="entryCount">The number of entries the playlist already holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
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: entryCount,
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 track.</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();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", 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 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];
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
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();
}
}
@@ -0,0 +1,610 @@
#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.Fixtures.Core.Requests.Playlists;
using Lumina.Contracts.Requests.Playlists;
using Lumina.Contracts.Responses.Playlists;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistScopeEntries;
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.Playlists.AddPlaylistScopeEntries;
/// <summary>
/// Contains integration tests for the <see cref="AddPlaylistScopeEntriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistScopeEntriesEndpointTests : 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 PlaylistEntityFixture _playlistEntityFixture = new();
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly AddPlaylistScopeEntriesRequestFixture _addPlaylistScopeEntriesRequestFixture = 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="AddPlaylistScopeEntriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddPlaylistScopeEntriesEndpointTests(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 AddPlaylistScopeEntries_WhenTheWholeLibraryIsScoped_ShouldAppendEveryTrackInCatalogueOrder()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid alphaArtistId = await SeedArtistAsync(libraryId, "Alpha Artist");
Guid alphaAlbumId = await SeedAlbumAsync(libraryId, alphaArtistId, "Alpha Album");
Guid alphaFirstTrackId = await SeedTrackAsync(libraryId, alphaAlbumId, "Alpha One", 100, trackNumber: 1);
Guid alphaSecondTrackId = await SeedTrackAsync(libraryId, alphaAlbumId, "Alpha Two", 110, trackNumber: 2);
Guid betaArtistId = await SeedArtistAsync(libraryId, "Beta Artist");
Guid betaAlbumId = await SeedAlbumAsync(libraryId, betaArtistId, "Beta Album");
Guid betaTrackId = await SeedTrackAsync(libraryId, betaAlbumId, "Beta One", 120, trackNumber: 1);
Guid playlistId = await SeedPlaylistAsync(userId, "Whole library", entryCount: 0);
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: libraryId);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-scope", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("private", response.Headers.CacheControl?.ToString());
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
Assert.Contains("Authorization", response.Headers.Vary);
PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync<PlaylistEntriesAddedResponse>(response);
Assert.NotNull(addedEntries);
Assert.Equal(playlistId, addedEntries!.PlaylistId);
Assert.Equal(3, addedEntries.AddedCount);
Assert.NotEqual(default, addedEntries.UpdatedOnUtc);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> storedTrackIds = await GetOrderedTrackIdsAsync(dbContext, playlistId);
Assert.Equal([alphaFirstTrackId, alphaSecondTrackId, betaTrackId], storedTrackIds);
PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId);
Assert.Equal(3, playlist.EntryCount);
}
[Fact]
public async Task AddPlaylistScopeEntries_WhenAnArtistIsScoped_ShouldAppendOnlyThatArtistsTracks()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid alphaArtistId = await SeedArtistAsync(libraryId, "Alpha Artist");
Guid alphaAlbumId = await SeedAlbumAsync(libraryId, alphaArtistId, "Alpha Album");
Guid alphaFirstTrackId = await SeedTrackAsync(libraryId, alphaAlbumId, "Alpha One", 100, trackNumber: 1);
Guid alphaSecondTrackId = await SeedTrackAsync(libraryId, alphaAlbumId, "Alpha Two", 110, trackNumber: 2);
Guid betaArtistId = await SeedArtistAsync(libraryId, "Beta Artist");
Guid betaAlbumId = await SeedAlbumAsync(libraryId, betaArtistId, "Beta Album");
await SeedTrackAsync(libraryId, betaAlbumId, "Beta One", 120, trackNumber: 1);
Guid playlistId = await SeedPlaylistAsync(userId, "One artist", entryCount: 0);
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(
libraryId: libraryId, artistId: alphaArtistId, includeArtistId: true);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-scope", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync<PlaylistEntriesAddedResponse>(response);
Assert.NotNull(addedEntries);
Assert.Equal(2, addedEntries!.AddedCount);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> storedTrackIds = await GetOrderedTrackIdsAsync(dbContext, playlistId);
Assert.Equal([alphaFirstTrackId, alphaSecondTrackId], storedTrackIds);
}
[Fact]
public async Task AddPlaylistScopeEntries_WhenAnAlbumIsScoped_ShouldAppendOnlyThatAlbumsTracks()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid artistId = await SeedArtistAsync(libraryId, "Alpha Artist");
Guid firstAlbumId = await SeedAlbumAsync(libraryId, artistId, "First Album");
await SeedTrackAsync(libraryId, firstAlbumId, "First One", 100, trackNumber: 1);
await SeedTrackAsync(libraryId, firstAlbumId, "First Two", 110, trackNumber: 2);
Guid secondAlbumId = await SeedAlbumAsync(libraryId, artistId, "Second Album");
Guid scopedTrackId = await SeedTrackAsync(libraryId, secondAlbumId, "Second One", 120, trackNumber: 1);
Guid playlistId = await SeedPlaylistAsync(userId, "One album", entryCount: 0);
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(
libraryId: libraryId, albumId: secondAlbumId, includeAlbumId: true);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-scope", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync<PlaylistEntriesAddedResponse>(response);
Assert.NotNull(addedEntries);
Assert.Equal(1, addedEntries!.AddedCount);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> storedTrackIds = await GetOrderedTrackIdsAsync(dbContext, playlistId);
Assert.Equal([scopedTrackId], storedTrackIds);
}
[Fact]
public async Task AddPlaylistScopeEntries_WhenTheScopeIsEmpty_ShouldAppendNothingAndReportAZeroCount()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid artistId = await SeedArtistAsync(libraryId, "Alpha Artist");
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "Empty Album");
Guid playlistId = await SeedPlaylistAsync(userId, "Empty scope", entryCount: 0);
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(
libraryId: libraryId, albumId: albumId, includeAlbumId: true);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-scope", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync<PlaylistEntriesAddedResponse>(response);
Assert.NotNull(addedEntries);
Assert.Equal(0, addedEntries!.AddedCount);
// An empty scope is a successful no-op, so the playlist activity time is not touched.
Assert.Null(addedEntries.UpdatedOnUtc);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId));
PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId);
Assert.Equal(0, playlist.EntryCount);
Assert.Equal(0, playlist.Version);
}
[Fact]
public async Task AddPlaylistScopeEntries_WhenThePlaylistDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid playlistId = Guid.NewGuid();
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: libraryId);
string url = $"{PATH}/{playlistId}/entries-scope";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
}
[Fact]
public async Task AddPlaylistScopeEntries_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundWithoutAddingEntries()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "Someone Else");
Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Private Album");
await SeedTrackAsync(otherLibraryId, otherAlbumId, "Private Track", 200, trackNumber: 1);
Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", entryCount: 0);
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: otherLibraryId);
string url = $"{PATH}/{otherPlaylistId}/entries-scope";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == otherPlaylistId));
}
[Fact]
public async Task AddPlaylistScopeEntries_WhenTheLibraryBelongsToAnotherUser_ShouldReturnForbiddenWithoutAddingEntries()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Only my library", entryCount: 0);
Guid otherUserId = await SeedOtherUserAsync();
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "Not Mine");
Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Not Mine Either");
await SeedTrackAsync(otherLibraryId, otherAlbumId, "Unreachable Track", 210, trackNumber: 1);
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: otherLibraryId);
string url = $"{PATH}/{playlistId}/entries-scope";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId));
}
[Fact]
public async Task AddPlaylistScopeEntries_WhenTheLibraryDoesNotExist_ShouldReturnForbiddenWithoutAddingEntries()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Unknown library", entryCount: 0);
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: Guid.NewGuid());
string url = $"{PATH}/{playlistId}/entries-scope";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId));
}
[Fact]
public async Task AddPlaylistScopeEntries_WhenTheLibraryIdIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Empty library", entryCount: 0);
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: Guid.Empty);
string url = $"{PATH}/{playlistId}/entries-scope";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "LibraryIdCannotBeEmpty");
}
[Fact]
public async Task AddPlaylistScopeEntries_WhenTheArtistIdIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Empty artist", entryCount: 0);
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(
libraryId: Guid.NewGuid(), artistId: Guid.Empty, includeArtistId: true);
string url = $"{PATH}/{playlistId}/entries-scope";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "ArtistIdCannotBeEmpty");
}
[Fact]
public async Task AddPlaylistScopeEntries_WhenTheAlbumIdIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Empty album", entryCount: 0);
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(
libraryId: Guid.NewGuid(), albumId: Guid.Empty, includeAlbumId: true);
string url = $"{PATH}/{playlistId}/entries-scope";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "AlbumIdCannotBeEmpty");
}
[Fact]
public async Task AddPlaylistScopeEntries_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem()
{
// Arrange
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create();
string url = $"{PATH}/not-a-guid/entries-scope";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty");
}
/// <summary>
/// Reads the media item Ids of the entries of <paramref name="playlistId"/>, in stored order.
/// </summary>
/// <param name="dbContext">The database context to read from.</param>
/// <param name="playlistId">The Id of the playlist whose entries are read.</param>
/// <returns>The media item Ids in stored order.</returns>
private static async Task<List<Guid>> GetOrderedTrackIdsAsync(LuminaDbContext dbContext, Guid playlistId)
{
return await dbContext.PlaylistEntries
.AsNoTracking()
.Where(candidate => candidate.PlaylistId == playlistId)
.OrderBy(candidate => candidate.Position)
.Select(candidate => candidate.MediaItemId)
.ToListAsync();
}
/// <summary>
/// Seeds a music 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();
dbContext.Albums.Add(_albumEntityFixture.Create(
id: albumId,
artistId: artistId,
libraryId: libraryId,
title: title,
includeTracks: false,
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false));
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>
/// <param name="trackNumber">The number of the track on its album.</param>
/// <returns>The Id of the seeded track.</returns>
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title, int durationInSeconds, int trackNumber)
{
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,
trackNumber: trackNumber,
// Catalogue order is resolved by disc and then track number, so the disc is pinned to keep the appended order deterministic.
discNumber: 1,
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
track.DurationInSeconds = durationInSeconds;
dbContext.Tracks.Add(track);
await dbContext.SaveChangesAsync();
return trackId;
}
/// <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>
/// <param name="entryCount">The number of entries the playlist already holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
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: entryCount,
version: 0,
createdBy: userId));
await dbContext.SaveChangesAsync();
_seededPlaylistIds.Add(playlistId);
return playlistId;
}
/// <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();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", 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 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];
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
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();
}
}
@@ -0,0 +1,355 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Playlists;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Playlists;
using Lumina.Contracts.Requests.Playlists;
using Lumina.Contracts.Responses.Playlists;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using Lumina.Presentation.Api.Core.Endpoints.Playlists.CreatePlaylist;
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.Playlists.CreatePlaylist;
/// <summary>
/// Contains integration tests for the <see cref="CreatePlaylistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CreatePlaylistEndpointTests : 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 PlaylistEntityFixture _playlistEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly CreatePlaylistRequestFixture _createPlaylistRequestFixture = new();
private readonly List<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="CreatePlaylistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public CreatePlaylistEndpointTests(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 CreatePlaylist_WhenTheRequestIsValid_ShouldCreateThePlaylistForTheCallerAndReturnIt()
{
// Arrange
Guid userId = GetCurrentUserId();
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(
name: "Evening listening", description: "Quiet tracks for the end of the day", type: PlaylistType.Music);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("private", response.Headers.CacheControl?.ToString());
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
Assert.Contains("Authorization", response.Headers.Vary);
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
Assert.NotNull(playlist);
Assert.NotEqual(Guid.Empty, playlist!.Id);
Assert.Equal("Evening listening", playlist.Name);
Assert.Equal("Quiet tracks for the end of the day", playlist.Description);
Assert.Equal(PlaylistType.Music, playlist.Type);
Assert.Empty(playlist.Entries.Data);
Assert.Equal(0, playlist.Entries.Count);
Assert.NotEqual(default, playlist.CreatedOnUtc);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlist.Id);
Assert.Equal(userId, storedPlaylist.UserId);
Assert.Equal(userId, storedPlaylist.CreatedBy);
Assert.Equal("Evening listening", storedPlaylist.Name);
Assert.Equal("Quiet tracks for the end of the day", storedPlaylist.Description);
Assert.Equal(PlaylistType.Music, storedPlaylist.Type);
Assert.Equal(0, storedPlaylist.EntryCount);
Assert.Equal(0, storedPlaylist.Version);
Assert.False(await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == playlist.Id));
}
[Fact]
public async Task CreatePlaylist_WhenTheDescriptionIsOmitted_ShouldCreateThePlaylistWithoutADescription()
{
// Arrange
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: "No description", includeDescription: false);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
Assert.NotNull(playlist);
Assert.Null(playlist!.Description);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlist.Id);
Assert.Null(storedPlaylist.Description);
}
[Fact]
public async Task CreatePlaylist_WhenTheNameHasTheMaximumLength_ShouldCreateThePlaylist()
{
// Arrange
string maximumLengthName = new('a', 255);
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: maximumLengthName);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
Assert.NotNull(playlist);
Assert.Equal(maximumLengthName, playlist!.Name);
}
[Fact]
public async Task CreatePlaylist_WhenTheNameIsMissing_ShouldReturnValidationProblem()
{
// Arrange
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(includeName: false);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request);
// Assert
await AssertValidationProblemAsync(response, PATH, "PlaylistNameCannotBeEmpty");
}
[Fact]
public async Task CreatePlaylist_WhenTheNameIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: string.Empty);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request);
// Assert
await AssertValidationProblemAsync(response, PATH, "PlaylistNameCannotBeEmpty");
}
[Fact]
public async Task CreatePlaylist_WhenTheNameIsTooLong_ShouldReturnValidationProblem()
{
// Arrange
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: new string('a', 256));
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request);
// Assert
await AssertValidationProblemAsync(response, PATH, "PlaylistNameMustBeMaximum255CharactersLong");
}
[Fact]
public async Task CreatePlaylist_WhenTheDescriptionIsTooLong_ShouldReturnValidationProblem()
{
// Arrange
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(description: new string('a', 2001));
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request);
// Assert
await AssertValidationProblemAsync(response, PATH, "PlaylistDescriptionMustBeMaximum2000CharactersLong");
}
[Fact]
public async Task CreatePlaylist_WhenTheTypeIsMissing_ShouldReturnValidationProblem()
{
// Arrange
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(includeType: false);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request);
// Assert
await AssertValidationProblemAsync(response, PATH, "PlaylistTypeIsInvalid");
}
[Fact]
public async Task CreatePlaylist_WhenTheTypeIsNotADefinedMember_ShouldReturnValidationProblem()
{
// Arrange
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(type: (PlaylistType)99);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request);
// Assert
await AssertValidationProblemAsync(response, PATH, "PlaylistTypeIsInvalid");
}
[Fact]
public async Task CreatePlaylist_WhenAnotherUserHasPlaylists_ShouldCreateThePlaylistOnlyForTheCaller()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist");
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: "Mine");
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
Assert.NotNull(playlist);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlist!.Id);
Assert.Equal(GetCurrentUserId(), storedPlaylist.UserId);
PlaylistEntity otherPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == otherPlaylistId);
Assert.Equal(otherUserId, otherPlaylist.UserId);
Assert.Equal("Someone else's playlist", otherPlaylist.Name);
}
/// <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 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();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", 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 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> playlistIds = [.. _seededPlaylistIds];
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
await dbContext.SaveChangesAsync();
}
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,312 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Playlists;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using Lumina.Presentation.Api.Core.Endpoints.Playlists.DeletePlaylist;
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.Playlists.DeletePlaylist;
/// <summary>
/// Contains integration tests for the <see cref="DeletePlaylistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletePlaylistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private const string PATH = "/api/v1/users/me/playlists";
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly PlaylistEntityFixture _playlistEntityFixture = new();
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeletePlaylistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeletePlaylistEndpointTests(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 DeletePlaylist_WhenThePlaylistExists_ShouldDeleteItTogetherWithItsEntries()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "To delete", entryCount: 2);
await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 0);
await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 1_000_000_000L);
// Act
HttpResponseMessage response = await _client.DeleteAsync($"{PATH}/{playlistId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("private", response.Headers.CacheControl?.ToString());
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
Assert.Contains("Authorization", response.Headers.Vary);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument document = JsonDocument.Parse(content);
Assert.Equal(JsonValueKind.Object, document.RootElement.ValueKind);
Assert.Empty(document.RootElement.EnumerateObject());
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId));
Assert.False(await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == playlistId));
}
[Fact]
public async Task DeletePlaylist_WhenCalledTwice_ShouldDeleteOnlyOnceAndReportTheSecondCallAsNotFound()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Deleted once", entryCount: 1);
Guid otherPlaylistId = await SeedPlaylistAsync(userId, "Untouched", entryCount: 1);
await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 0);
await SeedPlaylistEntryAsync(otherPlaylistId, Guid.NewGuid(), 0);
// Act
HttpResponseMessage firstResponse = await _client.DeleteAsync($"{PATH}/{playlistId}");
HttpResponseMessage secondResponse = await _client.DeleteAsync($"{PATH}/{playlistId}");
// Assert
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
await AssertProblemAsync(secondResponse, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", $"{PATH}/{playlistId}");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId));
Assert.True(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == otherPlaylistId));
Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == otherPlaylistId));
}
[Fact]
public async Task DeletePlaylist_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundAndKeepTheData()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", entryCount: 1);
await SeedPlaylistEntryAsync(otherPlaylistId, Guid.NewGuid(), 0);
string url = $"{PATH}/{otherPlaylistId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.True(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == otherPlaylistId));
Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == otherPlaylistId));
}
[Fact]
public async Task DeletePlaylist_WhenThePlaylistDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid playlistId = Guid.NewGuid();
string url = $"{PATH}/{playlistId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
}
[Fact]
public async Task DeletePlaylist_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem()
{
// Arrange
string url = $"{PATH}/not-a-guid";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty");
}
[Fact]
public async Task DeletePlaylist_WhenThePlaylistIdIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
string url = $"{PATH}/{Guid.Empty}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty");
}
/// <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>
/// <param name="entryCount">The number of entries the playlist holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
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: entryCount,
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 track.</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();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", 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 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> playlistIds = [.. _seededPlaylistIds];
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
await dbContext.SaveChangesAsync();
}
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,259 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Playlists;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
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.Playlists;
using Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylists;
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.GetPlaylists;
/// <summary>
/// Contains integration tests for the <see cref="GetPlaylistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaylistsEndpointTests : 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 PlaylistEntityFixture _playlistEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaylistsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPlaylistsEndpointTests(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 GetPlaylists_WhenTheCallerHasNoPlaylists_ShouldReturnAnEmptyList()
{
// Act
HttpResponseMessage response = await _client.GetAsync(PATH);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertCacheHeaders(response);
PlaylistSummaryResponse[]? playlists = await DeserializeAsync<PlaylistSummaryResponse[]>(response);
Assert.NotNull(playlists);
Assert.Empty(playlists!);
}
[Fact]
public async Task GetPlaylists_WhenTheCallerHasPlaylists_ShouldReturnThemWithTheirEntryCountsOrderedByActivity()
{
// Arrange
Guid userId = GetCurrentUserId();
DateTime now = DateTime.UtcNow;
Guid oldestId = await SeedPlaylistAsync(userId, "Beta Morning", description: "Oldest", entryCount: 0, createdOnUtc: now.AddHours(-3));
Guid middleId = await SeedPlaylistAsync(userId, "Alpha Evening", description: "Middle", entryCount: 2, createdOnUtc: now.AddHours(-2));
Guid mostRecentId = await SeedPlaylistAsync(userId, "Gamma Afternoon", description: "Most recent", entryCount: 1, createdOnUtc: now.AddHours(-4), updatedOnUtc: now);
// Act
HttpResponseMessage response = await _client.GetAsync(PATH);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertCacheHeaders(response);
PlaylistSummaryResponse[]? playlists = await DeserializeAsync<PlaylistSummaryResponse[]>(response);
Assert.NotNull(playlists);
Assert.Equal(3, playlists!.Length);
// The order is the most recent activity first: the updated playlist, then the two that were never updated, by creation time.
Assert.Equal([mostRecentId, middleId, oldestId], playlists.Select(playlist => playlist.Id));
PlaylistSummaryResponse mostRecent = playlists[0];
Assert.Equal("Gamma Afternoon", mostRecent.Name);
Assert.Equal("Most recent", mostRecent.Description);
Assert.Equal(PlaylistType.Music, mostRecent.Type);
Assert.Equal(1, mostRecent.EntryCount);
Assert.NotEqual(default, mostRecent.CreatedOnUtc);
Assert.NotNull(mostRecent.UpdatedOnUtc);
PlaylistSummaryResponse middle = playlists[1];
Assert.Equal("Alpha Evening", middle.Name);
Assert.Equal(2, middle.EntryCount);
Assert.Null(middle.UpdatedOnUtc);
}
[Fact]
public async Task GetPlaylists_WhenTwoPlaylistsShareTheSameActivityTime_ShouldOrderThemByName()
{
// Arrange
Guid userId = GetCurrentUserId();
DateTime sharedCreationTime = DateTime.UtcNow.AddHours(-1);
Guid zebraId = await SeedPlaylistAsync(userId, "Zebra", description: null, entryCount: 0, createdOnUtc: sharedCreationTime);
Guid alphaId = await SeedPlaylistAsync(userId, "Alpha", description: null, entryCount: 0, createdOnUtc: sharedCreationTime);
// Act
HttpResponseMessage response = await _client.GetAsync(PATH);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistSummaryResponse[]? playlists = await DeserializeAsync<PlaylistSummaryResponse[]>(response);
Assert.NotNull(playlists);
Assert.Equal([alphaId, zebraId], playlists!.Select(playlist => playlist.Id));
}
[Fact]
public async Task GetPlaylists_WhenAnotherUserHasPlaylists_ShouldReturnOnlyTheCallersPlaylists()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid ownPlaylistId = await SeedPlaylistAsync(userId, "Mine", description: null, entryCount: 0, createdOnUtc: DateTime.UtcNow);
Guid otherUserId = await SeedOtherUserAsync();
Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", description: "Private", entryCount: 3, createdOnUtc: DateTime.UtcNow);
// Act
HttpResponseMessage response = await _client.GetAsync(PATH);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("Someone else's playlist", content, StringComparison.Ordinal);
Assert.DoesNotContain(otherPlaylistId.ToString(), content, StringComparison.Ordinal);
PlaylistSummaryResponse[]? playlists = await DeserializeAsync<PlaylistSummaryResponse[]>(response);
Assert.NotNull(playlists);
PlaylistSummaryResponse playlist = Assert.Single(playlists!);
Assert.Equal(ownPlaylistId, playlist.Id);
}
/// <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>
/// <param name="description">The description of the playlist, or <see langword="null"/>.</param>
/// <param name="entryCount">The number of entries the playlist holds.</param>
/// <param name="createdOnUtc">The creation time of the playlist.</param>
/// <param name="updatedOnUtc">The activity time of the playlist, or <see langword="null"/> when it was never updated.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, string? description, int entryCount, DateTime createdOnUtc, DateTime? updatedOnUtc = null)
{
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,
description: description ?? string.Empty,
includeDescription: description is not null,
type: PlaylistType.Music,
entryCount: entryCount,
version: 0,
createdBy: userId));
await dbContext.SaveChangesAsync();
// The auditing interceptor overwrites both timestamps when a row is inserted, so the activity times that the ordering depends on
// are written afterwards, in the same form a real details update or entry operation would leave them.
await dbContext.Playlists
.Where(playlist => playlist.Id == playlistId)
.ExecuteUpdateAsync(setters => setters
.SetProperty(playlist => playlist.CreatedOnUtc, createdOnUtc)
.SetProperty(playlist => playlist.UpdatedOnUtc, updatedOnUtc)
.SetProperty(playlist => playlist.UpdatedBy, updatedOnUtc is null ? (Guid?)null : userId));
_seededPlaylistIds.Add(playlistId);
return playlistId;
}
/// <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();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", 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> playlistIds = [.. _seededPlaylistIds];
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
await dbContext.SaveChangesAsync();
}
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,508 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Playlists;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Playlists;
using Lumina.Contracts.Requests.Playlists;
using Lumina.Contracts.Responses.Playlists;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using Lumina.Presentation.Api.Core.Endpoints.Playlists.MovePlaylistEntry;
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.Playlists.MovePlaylistEntry;
/// <summary>
/// Contains integration tests for the <see cref="MovePlaylistEntryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MovePlaylistEntryEndpointTests : 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 PlaylistEntityFixture _playlistEntityFixture = new();
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly MovePlaylistEntryRequestFixture _movePlaylistEntryRequestFixture = new();
private readonly List<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="MovePlaylistEntryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public MovePlaylistEntryEndpointTests(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 MovePlaylistEntry_WhenMovedToTheFront_ShouldReturnTheNewPositionAndReorderTheEntries()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid playlistId, Guid firstEntryId, Guid secondEntryId, _) = await SeedOrderedPlaylistAsync(userId);
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0);
string url = $"{PATH}/{playlistId}/entries/{secondEntryId}/move";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("private", response.Headers.CacheControl?.ToString());
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
Assert.Contains("Authorization", response.Headers.Vary);
PlaylistEntryMovedResponse? movedEntry = await DeserializeAsync<PlaylistEntryMovedResponse>(response);
Assert.NotNull(movedEntry);
Assert.Equal(playlistId, movedEntry!.PlaylistId);
Assert.Equal(secondEntryId, movedEntry.EntryId);
Assert.Equal(0, movedEntry.Position);
Assert.NotEqual(default, movedEntry.UpdatedOnUtc);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId);
Assert.Equal(secondEntryId, orderedEntryIds[0]);
Assert.Equal(firstEntryId, orderedEntryIds[1]);
}
[Fact]
public async Task MovePlaylistEntry_WhenMovedToTheEnd_ShouldReturnTheLastPositionAndReorderTheEntries()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId);
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 2);
string url = $"{PATH}/{playlistId}/entries/{firstEntryId}/move";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistEntryMovedResponse? movedEntry = await DeserializeAsync<PlaylistEntryMovedResponse>(response);
Assert.NotNull(movedEntry);
Assert.Equal(2, movedEntry!.Position);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId);
Assert.Equal(secondEntryId, orderedEntryIds[0]);
Assert.Equal(thirdEntryId, orderedEntryIds[1]);
Assert.Equal(firstEntryId, orderedEntryIds[2]);
}
[Fact]
public async Task MovePlaylistEntry_WhenMovedToAMiddlePosition_ShouldReorderOnlyTheAffectedEntries()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId);
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 1);
string url = $"{PATH}/{playlistId}/entries/{thirdEntryId}/move";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistEntryMovedResponse? movedEntry = await DeserializeAsync<PlaylistEntryMovedResponse>(response);
Assert.NotNull(movedEntry);
Assert.Equal(1, movedEntry!.Position);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId);
Assert.Equal(firstEntryId, orderedEntryIds[0]);
Assert.Equal(thirdEntryId, orderedEntryIds[1]);
Assert.Equal(secondEntryId, orderedEntryIds[2]);
}
[Fact]
public async Task MovePlaylistEntry_WhenTheTargetPositionIsBeyondTheEntryCount_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid playlistId, _, Guid secondEntryId, _) = await SeedOrderedPlaylistAsync(userId);
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 3);
string url = $"{PATH}/{playlistId}/entries/{secondEntryId}/move";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistMoveTargetPositionIsInvalid");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
PlaylistEntryEntity storedEntry = await dbContext.PlaylistEntries.AsNoTracking().FirstAsync(entry => entry.Id == secondEntryId);
Assert.Equal(1_000_000_000L, storedEntry.Position);
}
[Fact]
public async Task MovePlaylistEntry_WhenTheTargetPositionIsNegative_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid playlistId, _, Guid secondEntryId, _) = await SeedOrderedPlaylistAsync(userId);
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: -1);
string url = $"{PATH}/{playlistId}/entries/{secondEntryId}/move";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistMoveTargetPositionIsInvalid");
}
[Fact]
public async Task MovePlaylistEntry_WhenTheTargetPositionIsMissing_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid playlistId, _, Guid secondEntryId, _) = await SeedOrderedPlaylistAsync(userId);
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(includeTargetPosition: false);
string url = $"{PATH}/{playlistId}/entries/{secondEntryId}/move";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistMoveTargetPositionIsInvalid");
}
[Fact]
public async Task MovePlaylistEntry_WhenThePlaylistDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid playlistId = Guid.NewGuid();
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0);
string url = $"{PATH}/{playlistId}/entries/{Guid.NewGuid()}/move";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
}
[Fact]
public async Task MovePlaylistEntry_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundAndKeepTheOrder()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
(Guid otherPlaylistId, _, Guid otherEntryId, _) = await SeedOrderedPlaylistAsync(otherUserId);
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0);
string url = $"{PATH}/{otherPlaylistId}/entries/{otherEntryId}/move";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
PlaylistEntryEntity storedEntry = await dbContext.PlaylistEntries.AsNoTracking().FirstAsync(entry => entry.Id == otherEntryId);
Assert.Equal(1_000_000_000L, storedEntry.Position);
}
[Fact]
public async Task MovePlaylistEntry_WhenTheEntryBelongsToAnotherPlaylist_ShouldReturnNotFoundAndKeepTheOrder()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId);
Guid otherPlaylistId = await SeedPlaylistAsync(userId, "Another playlist", entryCount: 1);
Guid otherPlaylistEntryId = await SeedPlaylistEntryAsync(otherPlaylistId, Guid.NewGuid(), 0);
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0);
string url = $"{PATH}/{playlistId}/entries/{otherPlaylistEntryId}/move";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistEntryNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId);
Assert.Equal([firstEntryId, secondEntryId, thirdEntryId], orderedEntryIds);
PlaylistEntryEntity storedEntry = await dbContext.PlaylistEntries.AsNoTracking().FirstAsync(entry => entry.Id == otherPlaylistEntryId);
Assert.Equal(0, storedEntry.Position);
Assert.Equal(otherPlaylistId, storedEntry.PlaylistId);
}
[Fact]
public async Task MovePlaylistEntry_WhenTheEntryBelongsToAnotherUsersPlaylist_ShouldReturnNotFound()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid playlistId, Guid firstEntryId, _, _) = await SeedOrderedPlaylistAsync(userId);
Guid otherUserId = await SeedOtherUserAsync();
(Guid otherPlaylistId, _, Guid otherEntryId, _) = await SeedOrderedPlaylistAsync(otherUserId);
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0);
string url = $"{PATH}/{playlistId}/entries/{otherEntryId}/move";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistEntryNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
PlaylistEntryEntity callerEntry = await dbContext.PlaylistEntries.AsNoTracking().FirstAsync(entry => entry.Id == firstEntryId);
Assert.Equal(0, callerEntry.Position);
PlaylistEntryEntity otherEntry = await dbContext.PlaylistEntries.AsNoTracking().FirstAsync(entry => entry.Id == otherEntryId);
Assert.Equal(1_000_000_000L, otherEntry.Position);
Assert.True(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == otherPlaylistId));
}
[Fact]
public async Task MovePlaylistEntry_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem()
{
// Arrange
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0);
string url = $"{PATH}/not-a-guid/entries/{Guid.NewGuid()}/move";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty");
}
[Fact]
public async Task MovePlaylistEntry_WhenTheEntryIdIsNotAGuid_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Invalid entry id", entryCount: 0);
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0);
string url = $"{PATH}/{playlistId}/entries/not-a-guid/move";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistEntryIdCannotBeEmpty");
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> with three ordered entries and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <returns>The Id of the playlist and the Ids of its first, second and third entries.</returns>
private async Task<(Guid PlaylistId, Guid FirstEntryId, Guid SecondEntryId, Guid ThirdEntryId)> SeedOrderedPlaylistAsync(Guid userId)
{
Guid playlistId = await SeedPlaylistAsync(userId, "Ordered playlist", entryCount: 3);
Guid firstEntryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 0);
Guid secondEntryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 1_000_000_000L);
Guid thirdEntryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 2_000_000_000L);
return (playlistId, firstEntryId, secondEntryId, thirdEntryId);
}
/// <summary>
/// Reads the entry Ids of the playlist identified by <paramref name="playlistId"/>, in stored order.
/// </summary>
/// <param name="dbContext">The database context to read from.</param>
/// <param name="playlistId">The Id of the playlist whose entries are read.</param>
/// <returns>The entry Ids in stored order.</returns>
private static async Task<List<Guid>> GetOrderedEntryIdsAsync(LuminaDbContext dbContext, Guid playlistId)
{
return await dbContext.PlaylistEntries
.AsNoTracking()
.Where(candidate => candidate.PlaylistId == playlistId)
.OrderBy(candidate => candidate.Position)
.Select(candidate => candidate.Id)
.ToListAsync();
}
/// <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>
/// <param name="entryCount">The number of entries the playlist holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
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: entryCount,
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 track.</param>
/// <param name="position">The sparse order key of the entry.</param>
/// <returns>The Id of the seeded entry.</returns>
private async Task<Guid> SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid entryId = Guid.NewGuid();
dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create(
id: entryId,
playlistId: playlistId,
mediaItemId: mediaItemId,
mediaItemType: PlaylistMediaItemType.MusicTrack,
position: position));
await dbContext.SaveChangesAsync();
return entryId;
}
/// <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();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", 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 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> playlistIds = [.. _seededPlaylistIds];
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
await dbContext.SaveChangesAsync();
}
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,438 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Playlists;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
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.Playlists;
using Lumina.Presentation.Api.Core.Endpoints.Playlists.RemovePlaylistEntry;
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.RemovePlaylistEntry;
/// <summary>
/// Contains integration tests for the <see cref="RemovePlaylistEntryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemovePlaylistEntryEndpointTests : 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 PlaylistEntityFixture _playlistEntityFixture = new();
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="RemovePlaylistEntryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RemovePlaylistEntryEndpointTests(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 RemovePlaylistEntry_WhenTheEntryExists_ShouldRemoveOnlyThatEntryAndReturnTheResult()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId);
string url = $"{PATH}/{playlistId}/entries/{secondEntryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("private", response.Headers.CacheControl?.ToString());
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
Assert.Contains("Authorization", response.Headers.Vary);
PlaylistEntryRemovedResponse? removedEntry = await DeserializeAsync<PlaylistEntryRemovedResponse>(response);
Assert.NotNull(removedEntry);
Assert.Equal(playlistId, removedEntry!.PlaylistId);
Assert.Equal(secondEntryId, removedEntry.RemovedEntryId);
Assert.Equal(0, removedEntry.RepositionedCount);
Assert.NotEqual(default, removedEntry.UpdatedOnUtc);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.PlaylistEntries.AnyAsync(entry => entry.Id == secondEntryId));
List<Guid> orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId);
Assert.Equal([firstEntryId, thirdEntryId], orderedEntryIds);
PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId);
Assert.Equal(2, playlist.EntryCount);
Assert.Equal(1, playlist.Version);
}
[Fact]
public async Task RemovePlaylistEntry_WhenTheEntryIsTheLastOne_ShouldLeaveThePlaylistEmpty()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "One entry", entryCount: 1);
Guid entryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 0);
string url = $"{PATH}/{playlistId}/entries/{entryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == playlistId));
PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId);
Assert.Equal(0, playlist.EntryCount);
}
[Fact]
public async Task RemovePlaylistEntry_WhenCalledTwice_ShouldRemoveOnceAndReportTheSecondCallAsNotFound()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid playlistId, Guid firstEntryId, Guid secondEntryId, _) = await SeedOrderedPlaylistAsync(userId);
string url = $"{PATH}/{playlistId}/entries/{secondEntryId}";
// Act
HttpResponseMessage firstResponse = await _client.DeleteAsync(url);
HttpResponseMessage secondResponse = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
await AssertProblemAsync(secondResponse, HttpStatusCode.NotFound, "General.NotFound", "PlaylistEntryNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId);
Assert.Equal(2, playlist.EntryCount);
Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.Id == firstEntryId));
}
[Fact]
public async Task RemovePlaylistEntry_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundAndKeepTheEntry()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
(Guid otherPlaylistId, _, Guid otherEntryId, _) = await SeedOrderedPlaylistAsync(otherUserId);
string url = $"{PATH}/{otherPlaylistId}/entries/{otherEntryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.Id == otherEntryId));
PlaylistEntity otherPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == otherPlaylistId);
Assert.Equal(3, otherPlaylist.EntryCount);
}
[Fact]
public async Task RemovePlaylistEntry_WhenTheEntryBelongsToAnotherPlaylist_ShouldReturnNotFoundAndKeepIt()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId);
Guid otherPlaylistId = await SeedPlaylistAsync(userId, "Another playlist", entryCount: 1);
Guid otherPlaylistEntryId = await SeedPlaylistEntryAsync(otherPlaylistId, Guid.NewGuid(), 0);
string url = $"{PATH}/{playlistId}/entries/{otherPlaylistEntryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistEntryNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.Id == otherPlaylistEntryId));
List<Guid> orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId);
Assert.Equal([firstEntryId, secondEntryId, thirdEntryId], orderedEntryIds);
}
[Fact]
public async Task RemovePlaylistEntry_WhenTheEntryBelongsToAnotherUsersPlaylist_ShouldReturnNotFound()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId);
Guid otherUserId = await SeedOtherUserAsync();
(Guid otherPlaylistId, _, Guid otherEntryId, _) = await SeedOrderedPlaylistAsync(otherUserId);
string url = $"{PATH}/{playlistId}/entries/{otherEntryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistEntryNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.Id == otherEntryId));
List<Guid> orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId);
Assert.Equal([firstEntryId, secondEntryId, thirdEntryId], orderedEntryIds);
Assert.True(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == otherPlaylistId));
}
[Fact]
public async Task RemovePlaylistEntry_WhenThePlaylistDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid playlistId = Guid.NewGuid();
string url = $"{PATH}/{playlistId}/entries/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
}
[Fact]
public async Task RemovePlaylistEntry_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem()
{
// Arrange
string url = $"{PATH}/not-a-guid/entries/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty");
}
[Fact]
public async Task RemovePlaylistEntry_WhenTheEntryIdIsNotAGuid_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Invalid entry id", entryCount: 0);
string url = $"{PATH}/{playlistId}/entries/not-a-guid";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistEntryIdCannotBeEmpty");
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> with three ordered entries and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <returns>The Id of the playlist and the Ids of its first, second and third entries.</returns>
private async Task<(Guid PlaylistId, Guid FirstEntryId, Guid SecondEntryId, Guid ThirdEntryId)> SeedOrderedPlaylistAsync(Guid userId)
{
Guid playlistId = await SeedPlaylistAsync(userId, "Ordered playlist", entryCount: 3);
Guid firstEntryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 0);
Guid secondEntryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 1_000_000_000L);
Guid thirdEntryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 2_000_000_000L);
return (playlistId, firstEntryId, secondEntryId, thirdEntryId);
}
/// <summary>
/// Reads the entry Ids of the playlist identified by <paramref name="playlistId"/>, in stored order.
/// </summary>
/// <param name="dbContext">The database context to read from.</param>
/// <param name="playlistId">The Id of the playlist whose entries are read.</param>
/// <returns>The entry Ids in stored order.</returns>
private static async Task<List<Guid>> GetOrderedEntryIdsAsync(LuminaDbContext dbContext, Guid playlistId)
{
return await dbContext.PlaylistEntries
.AsNoTracking()
.Where(candidate => candidate.PlaylistId == playlistId)
.OrderBy(candidate => candidate.Position)
.Select(candidate => candidate.Id)
.ToListAsync();
}
/// <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>
/// <param name="entryCount">The number of entries the playlist holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
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: entryCount,
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 track.</param>
/// <param name="position">The sparse order key of the entry.</param>
/// <returns>The Id of the seeded entry.</returns>
private async Task<Guid> SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid entryId = Guid.NewGuid();
dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create(
id: entryId,
playlistId: playlistId,
mediaItemId: mediaItemId,
mediaItemType: PlaylistMediaItemType.MusicTrack,
position: position));
await dbContext.SaveChangesAsync();
return entryId;
}
/// <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();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", 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 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> playlistIds = [.. _seededPlaylistIds];
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
await dbContext.SaveChangesAsync();
}
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,420 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Playlists;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Playlists;
using Lumina.Contracts.Requests.Playlists;
using Lumina.Contracts.Responses.Playlists;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using Lumina.Presentation.Api.Core.Endpoints.Playlists.UpdatePlaylist;
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.Playlists.UpdatePlaylist;
/// <summary>
/// Contains integration tests for the <see cref="UpdatePlaylistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePlaylistEndpointTests : 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 PlaylistEntityFixture _playlistEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly UpdatePlaylistRequestFixture _updatePlaylistRequestFixture = new();
private readonly List<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="UpdatePlaylistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdatePlaylistEndpointTests(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 UpdatePlaylist_WhenTheRequestIsValid_ShouldUpdateTheDetailsAndReturnThem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Old name", "Old description");
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: "New name", description: "New description");
string url = $"{PATH}/{playlistId}";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("private", response.Headers.CacheControl?.ToString());
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
Assert.Contains("Authorization", response.Headers.Vary);
PlaylistDetailsResponse? playlist = await DeserializeAsync<PlaylistDetailsResponse>(response);
Assert.NotNull(playlist);
Assert.Equal(playlistId, playlist!.Id);
Assert.Equal("New name", playlist.Name);
Assert.Equal("New description", playlist.Description);
Assert.Equal(PlaylistType.Music, playlist.Type);
Assert.NotNull(playlist.UpdatedOnUtc);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId);
Assert.Equal("New name", storedPlaylist.Name);
Assert.Equal("New description", storedPlaylist.Description);
Assert.Equal(userId, storedPlaylist.UpdatedBy);
Assert.NotNull(storedPlaylist.UpdatedOnUtc);
Assert.Equal(1, storedPlaylist.Version);
}
[Fact]
public async Task UpdatePlaylist_WhenTheDescriptionIsOmitted_ShouldClearTheStoredDescription()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Named playlist", "Description to clear");
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: "Named playlist", includeDescription: false);
string url = $"{PATH}/{playlistId}";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistDetailsResponse? playlist = await DeserializeAsync<PlaylistDetailsResponse>(response);
Assert.NotNull(playlist);
Assert.Null(playlist!.Description);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId);
Assert.Null(storedPlaylist.Description);
}
[Fact]
public async Task UpdatePlaylist_WhenTheNameHasTheMaximumLength_ShouldUpdateTheDetails()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Short name", null);
string maximumLengthName = new('a', 255);
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: maximumLengthName);
string url = $"{PATH}/{playlistId}";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaylistDetailsResponse? playlist = await DeserializeAsync<PlaylistDetailsResponse>(response);
Assert.NotNull(playlist);
Assert.Equal(maximumLengthName, playlist!.Name);
}
[Fact]
public async Task UpdatePlaylist_WhenTheNameIsMissing_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Old name", null);
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(includeName: false);
string url = $"{PATH}/{playlistId}";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistNameCannotBeEmpty");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId);
Assert.Equal("Old name", storedPlaylist.Name);
}
[Fact]
public async Task UpdatePlaylist_WhenTheNameIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Old name", null);
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: string.Empty);
string url = $"{PATH}/{playlistId}";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistNameCannotBeEmpty");
}
[Fact]
public async Task UpdatePlaylist_WhenTheNameIsTooLong_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Old name", null);
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: new string('a', 256));
string url = $"{PATH}/{playlistId}";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistNameMustBeMaximum255CharactersLong");
}
[Fact]
public async Task UpdatePlaylist_WhenTheDescriptionIsTooLong_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid playlistId = await SeedPlaylistAsync(userId, "Old name", null);
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(description: new string('a', 2001));
string url = $"{PATH}/{playlistId}";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistDescriptionMustBeMaximum2000CharactersLong");
}
[Fact]
public async Task UpdatePlaylist_WhenThePlaylistDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid playlistId = Guid.NewGuid();
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create();
string url = $"{PATH}/{playlistId}";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
}
[Fact]
public async Task UpdatePlaylist_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundAndKeepTheData()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", "Private");
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: "Hijacked", description: "Hijacked");
string url = $"{PATH}/{otherPlaylistId}";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == otherPlaylistId);
Assert.Equal("Someone else's playlist", storedPlaylist.Name);
Assert.Equal("Private", storedPlaylist.Description);
Assert.Equal(otherUserId, storedPlaylist.UserId);
}
[Fact]
public async Task UpdatePlaylist_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem()
{
// Arrange
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create();
string url = $"{PATH}/not-a-guid";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty");
}
[Fact]
public async Task UpdatePlaylist_WhenThePlaylistIdIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create();
string url = $"{PATH}/{Guid.Empty}";
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
// Assert
await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty");
}
/// <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>
/// <param name="description">The description of the playlist, or <see langword="null"/>.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, string? description)
{
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,
description: description ?? string.Empty,
includeDescription: description is not null,
type: PlaylistType.Music,
entryCount: 0,
version: 0,
createdBy: userId,
includeUpdatedOnUtc: true,
updatedOnUtc: DateTime.UtcNow.AddHours(-1),
updatedBy: userId));
await dbContext.SaveChangesAsync();
_seededPlaylistIds.Add(playlistId);
return playlistId;
}
/// <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();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", 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 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> playlistIds = [.. _seededPlaylistIds];
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
await dbContext.SaveChangesAsync();
}
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,176 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.UsersManagement.Settings;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetPlaybackState;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Settings.GetPlaybackState;
/// <summary>
/// Contains integration tests for the <see cref="GetPlaybackStateEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaybackStateEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaybackStateEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPlaybackStateEndpointTests(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 GetPlaybackState_WhenNoSettingsAreStored_ShouldReturnTheDefaultPlaybackState()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PlaybackStateResponse? result = JsonSerializer.Deserialize<PlaybackStateResponse>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Equal(1.0, result!.Volume);
Assert.False(result.IsMuted);
}
[Fact]
public async Task GetPlaybackState_WhenSettingsAreStored_ShouldReturnTheStoredPlaybackState()
{
// Arrange
await CreateTestUserSettings(volume: 0.42, isMuted: true);
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PlaybackStateResponse? result = JsonSerializer.Deserialize<PlaybackStateResponse>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Equal(0.42, result!.Volume);
Assert.True(result.IsMuted);
}
[Fact]
public async Task GetPlaybackState_WhenSettingsBelongToAnotherUser_ShouldReturnTheDefaultPlaybackState()
{
// Arrange
await CreateSettingsForAnotherUserAsync(volume: 0.1, isMuted: true);
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state");
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
PlaybackStateResponse? result = JsonSerializer.Deserialize<PlaybackStateResponse>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Equal(1.0, result!.Volume);
Assert.False(result.IsMuted);
}
[Fact]
public async Task GetPlaybackState_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/users/me/settings/playback-state");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Stores the playback state of the currently authenticated test user.
/// </summary>
/// <param name="volume">The volume to store.</param>
/// <param name="isMuted">The mute state to store.</param>
/// <returns>The stored settings.</returns>
private async Task<UserSettingsEntity> CreateTestUserSettings(double volume, bool isMuted)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id;
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: userId, volume: volume, isMuted: isMuted);
dbContext.UserSettings.Add(settings);
await dbContext.SaveChangesAsync();
return settings;
}
/// <summary>
/// Seeds another user and stores that user's playback state, keeping it out of the current user's scope.
/// </summary>
/// <param name="volume">The volume to store.</param>
/// <param name="isMuted">The mute state to store.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task CreateSettingsForAnotherUserAsync(double volume, bool isMuted)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity otherUser = _userEntityFixture.Create(username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!");
otherUser.TotpSecret = null;
dbContext.Users.Add(otherUser);
dbContext.UserSettings.Add(_userSettingsEntityFixture.Create(userId: otherUser.Id, volume: volume, isMuted: isMuted));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
await dbContext.Set<UserSettingsEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,294 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
using Lumina.Contracts.Requests.UsersManagement.Settings;
using Lumina.Contracts.Responses.UsersManagement.Settings;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState;
/// <summary>
/// Contains integration tests for the <see cref="UpdatePlaybackStateEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePlaybackStateEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly UpdatePlaybackStateRequestFixture _updatePlaybackStateRequestFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="UpdatePlaybackStateEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdatePlaybackStateEndpointTests(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 UpdatePlaybackState_WhenCalledWithValidRequest_ShouldStoreTheReportedStateWithTheDefaultHandEditedSettings()
{
// Arrange
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.35, isMuted: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
UserSettingsEntity? storedSettings = await GetCurrentUserSettingsAsync();
Assert.NotNull(storedSettings);
Assert.Equal(0.35, storedSettings!.Volume);
Assert.True(storedSettings.IsMuted);
Assert.True(storedSettings.IsPaginationEnabled);
Assert.Equal(48, storedSettings.ItemsPerPage);
}
[Fact]
public async Task UpdatePlaybackState_WhenSettingsAlreadyExist_ShouldPreserveTheHandEditedSettings()
{
// Arrange
await CreateTestUserSettingsAsync(volume: 1.0, isMuted: false, itemsPerPage: 24, isPaginationEnabled: false);
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.25, isMuted: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
// Assert
response.EnsureSuccessStatusCode();
UserSettingsEntity? storedSettings = await GetCurrentUserSettingsAsync();
Assert.NotNull(storedSettings);
Assert.Equal(0.25, storedSettings!.Volume);
Assert.True(storedSettings.IsMuted);
Assert.False(storedSettings.IsPaginationEnabled);
Assert.Equal(24, storedSettings.ItemsPerPage);
}
[Fact]
public async Task UpdatePlaybackState_WhenUpdatedThenRead_ShouldReturnTheReportedState()
{
// Arrange
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.6, isMuted: true);
// Act
HttpResponseMessage updateResponse = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
HttpResponseMessage getResponse = await _client.GetAsync("/api/v1/users/me/settings/playback-state");
// Assert
updateResponse.EnsureSuccessStatusCode();
getResponse.EnsureSuccessStatusCode();
string content = await getResponse.Content.ReadAsStringAsync();
PlaybackStateResponse? result = JsonSerializer.Deserialize<PlaybackStateResponse>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Equal(0.6, result!.Volume);
Assert.True(result.IsMuted);
}
[Fact]
public async Task UpdatePlaybackState_WhenCalledByOneUser_ShouldNotChangeThePlaybackStateOfAnotherUser()
{
// Arrange
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.25, isMuted: true);
HttpResponseMessage updateResponse = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
HttpClient otherClient = await _apiFactory.CreateAuthenticatedClientAsync();
// Act
HttpResponseMessage getResponse = await otherClient.GetAsync("/api/v1/users/me/settings/playback-state");
// Assert
updateResponse.EnsureSuccessStatusCode();
getResponse.EnsureSuccessStatusCode();
string content = await getResponse.Content.ReadAsStringAsync();
PlaybackStateResponse? result = JsonSerializer.Deserialize<PlaybackStateResponse>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Equal(1.0, result!.Volume);
Assert.False(result.IsMuted);
}
[Fact]
public async Task UpdatePlaybackState_WhenVolumeIsNull_ShouldReturnValidationError()
{
// Arrange
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(includeVolume: false);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
// Assert
await AssertValidationErrorAsync(response, "VolumeCannotBeNull");
}
[Theory]
[InlineData(-0.01)] // just below the minimum
[InlineData(1.01)] // just above the maximum
public async Task UpdatePlaybackState_WhenVolumeIsOutOfRange_ShouldReturnValidationError(double volume)
{
// Arrange
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: volume);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
// Assert
await AssertValidationErrorAsync(response, "VolumeMustBeBetweenZeroAndOne");
}
[Fact]
public async Task UpdatePlaybackState_WhenIsMutedIsNull_ShouldReturnValidationError()
{
// Arrange
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(includeIsMuted: false);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
// Assert
await AssertValidationErrorAsync(response, "IsMutedCannotBeNull");
}
[Fact]
public async Task UpdatePlaybackState_WhenPayloadHasUnknownFields_ShouldIgnoreThemAndStoreTheReportedState()
{
// Arrange
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.15, isMuted: false);
JsonObject payload = JsonSerializer.SerializeToNode(request, new JsonSerializerOptions(JsonSerializerDefaults.Web))!.AsObject();
payload["unknownField"] = "ignored";
StringContent requestContent = new(payload.ToJsonString(), Encoding.UTF8, "application/json");
// Act
HttpResponseMessage response = await _client.PutAsync("/api/v1/users/me/settings/playback-state", requestContent);
// Assert
response.EnsureSuccessStatusCode();
UserSettingsEntity? storedSettings = await GetCurrentUserSettingsAsync();
Assert.NotNull(storedSettings);
Assert.Equal(0.15, storedSettings!.Volume);
Assert.False(storedSettings.IsMuted);
}
[Fact]
public async Task UpdatePlaybackState_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.35, isMuted: true);
// Act
HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Asserts that <paramref name="response"/> is a validation problem response carrying the specified error.
/// </summary>
/// <param name="response">The response to assert.</param>
/// <param name="expectedError">The exact error description expected in the validation errors.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task AssertValidationErrorAsync(HttpResponseMessage response, string expectedError)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/users/me/settings/playback-state", problemDetails["instance"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains(expectedError, errors["General.Validation"]);
}
/// <summary>
/// Stores a playback state for the currently authenticated test user.
/// </summary>
/// <param name="volume">The volume to store.</param>
/// <param name="isMuted">The mute state to store.</param>
/// <param name="itemsPerPage">The number of items displayed per page to store.</param>
/// <param name="isPaginationEnabled">Whether pagination is enabled.</param>
/// <returns>The stored settings.</returns>
private async Task<UserSettingsEntity> CreateTestUserSettingsAsync(double volume, bool isMuted, int itemsPerPage, bool isPaginationEnabled)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id;
UserSettingsEntity settings = _userSettingsEntityFixture.Create(
userId: userId,
volume: volume,
isMuted: isMuted,
itemsPerPage: itemsPerPage,
isPaginationEnabled: isPaginationEnabled);
dbContext.UserSettings.Add(settings);
await dbContext.SaveChangesAsync();
return settings;
}
/// <summary>
/// Reads the stored playback state of the currently authenticated test user.
/// </summary>
/// <returns>The stored settings, or <see langword="null"/> when the user has none.</returns>
private async Task<UserSettingsEntity?> GetCurrentUserSettingsAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id;
return await dbContext.UserSettings.FirstOrDefaultAsync(settings => settings.UserId == userId);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
await dbContext.Set<UserSettingsEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}