mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 05:01:10 +00:00
Adds music stack test coverage and fixes playlist cache and stream error handling
This commit is contained in:
1 parent
394f6b510c
commit
aba803b106
197 files changed
+29081
-34
No files matched your search
+586
@@ -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();
|
||||
}
|
||||
}
|
||||
+579
@@ -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();
|
||||
}
|
||||
}
|
||||
+610
@@ -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();
|
||||
}
|
||||
}
|
||||
+355
@@ -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();
|
||||
}
|
||||
}
|
||||
+312
@@ -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();
|
||||
}
|
||||
}
|
||||
+259
@@ -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();
|
||||
}
|
||||
}
|
||||
+508
@@ -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();
|
||||
}
|
||||
}
|
||||
+438
@@ -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();
|
||||
}
|
||||
}
|
||||
+420
@@ -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();
|
||||
}
|
||||
}
|
||||
+176
@@ -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();
|
||||
}
|
||||
}
|
||||
+294
@@ -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();
|
||||
}
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="StreamMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StreamMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public StreamMusicTrackEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrack_WhenRequestIsValid_ShouldProxyTheApiStream()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId);
|
||||
byte[] contentBytes = CreateBytes(2048);
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(HttpStatusCode.OK, contentBytes, "audio/mpeg"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(libraryId, artistId, albumId, trackId));
|
||||
byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("audio/mpeg", response.Content.Headers.ContentType?.MediaType);
|
||||
Assert.Equal(contentBytes.Length, response.Content.Headers.ContentLength);
|
||||
Assert.Equal(contentBytes, responseBytes);
|
||||
Assert.Contains("private", response.Headers.CacheControl?.ToString());
|
||||
Assert.DoesNotContain("public", response.Headers.CacheControl?.ToString());
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.Single(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
|
||||
Assert.Equal(expectedEndpoint, _apiFactory.StreamingApiClientStub.GetEndpointsCalled[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrack_WhenConditionalHeadersArePresent_ShouldForwardThemToTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId);
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(HttpStatusCode.PartialContent, CreateBytes(100), "audio/mpeg"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, BuildBrowserPath(libraryId, artistId, albumId, trackId));
|
||||
request.Headers.Range = new RangeHeaderValue(100, 199);
|
||||
request.Headers.IfRange = new RangeConditionHeaderValue(new EntityTagHeaderValue("\"etag-value\""));
|
||||
request.Headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"etag-value\""));
|
||||
request.Headers.IfModifiedSince = new DateTimeOffset(2015, 10, 21, 7, 28, 0, TimeSpan.Zero);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode);
|
||||
Assert.Single(_apiFactory.StreamingApiClientStub.StreamRequests);
|
||||
IReadOnlyDictionary<string, string> forwardedHeaders = _apiFactory.StreamingApiClientStub.StreamRequests[0].Headers;
|
||||
Assert.Equal("bytes=100-199", forwardedHeaders["Range"]);
|
||||
Assert.Equal("\"etag-value\"", forwardedHeaders["If-Range"]);
|
||||
Assert.Equal("\"etag-value\"", forwardedHeaders["If-None-Match"]);
|
||||
Assert.Equal("Wed, 21 Oct 2015 07:28:00 GMT", forwardedHeaders["If-Modified-Since"]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.ServiceUnavailable)] // a busy normalization pipeline is a transient condition
|
||||
[InlineData(HttpStatusCode.TooManyRequests)] // the stream concurrency limit was reached
|
||||
public async Task StreamMusicTrack_WhenApiReportsATransientCondition_ShouldReturnABareStatus(HttpStatusCode statusCode)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId);
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamException(expectedEndpoint, new ApiException(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode },
|
||||
statusCode,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, BuildBrowserPath(libraryId, artistId, albumId, trackId));
|
||||
// A media caller asks for audio, which is what makes the failure a bare status rather than a JSON or page response.
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/mpeg"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal(string.Empty, content);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.ServiceUnavailable)] // a busy normalization pipeline is a transient condition
|
||||
[InlineData(HttpStatusCode.TooManyRequests)] // the stream concurrency limit was reached
|
||||
public async Task StreamMusicTrack_WhenApiReportsATransientConditionForANonMediaCaller_ShouldStillReturnABareStatus(HttpStatusCode statusCode)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId);
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamException(expectedEndpoint, new ApiException(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode },
|
||||
statusCode,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
// No Accept and no Range header: a caller that is not asking for media must still receive the bare transient status, not a
|
||||
// JSON body with status 200 that the navigation error middleware would otherwise produce.
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, BuildBrowserPath(libraryId, artistId, albumId, trackId));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal(string.Empty, content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrack_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync(BuildBrowserPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the browser facing route of the direct stream of a track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <returns>The browser facing route of the requested stream.</returns>
|
||||
private static string BuildBrowserPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track?libraryId={libraryId}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the stream request is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return ApiRoutes.Music.STREAM_TRACK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a streamed API response with a status code, a body and a media type.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The status code of the response.</param>
|
||||
/// <param name="contentBytes">The bytes of the content of the response.</param>
|
||||
/// <param name="contentType">The media type of the content.</param>
|
||||
/// <returns>The created streamed response.</returns>
|
||||
private static async Task<ApiStreamResult> CreateStreamResultAsync(HttpStatusCode statusCode, byte[] contentBytes, string contentType)
|
||||
{
|
||||
HttpResponseMessage response = new(statusCode)
|
||||
{
|
||||
Content = new ByteArrayContent(contentBytes)
|
||||
};
|
||||
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
||||
response.Headers.CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromSeconds(60) };
|
||||
return await ApiStreamResult.CreateAsync(response, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic byte array that stands in for the content of a stream.
|
||||
/// </summary>
|
||||
/// <param name="length">The number of bytes to create.</param>
|
||||
/// <returns>The created bytes.</returns>
|
||||
private static byte[] CreateBytes(int length)
|
||||
{
|
||||
return [.. Enumerable.Range(0, length).Select(index => (byte)(index % 256))];
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.AddPlaylistEntries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddPlaylistEntriesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddPlaylistEntriesEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly AddPlaylistEntriesRequestFixture _addPlaylistEntriesRequestFixture = new();
|
||||
private readonly PlaylistEntriesAddedDtoFixture _playlistEntriesAddedDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistEntriesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddPlaylistEntriesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntries_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheEntriesAndReturnTheAddedCount()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
List<Guid> trackIds = [Guid.NewGuid(), Guid.NewGuid()];
|
||||
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: trackIds);
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-batch";
|
||||
PlaylistEntriesAddedDto expectedResult = _playlistEntriesAddedDtoFixture.Create(playlistId: playlistId, addedCount: 2);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, expectedResult);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(expectedResult.PlaylistId, data.GetProperty("playlistId").GetGuid());
|
||||
Assert.Equal(expectedResult.AddedCount, data.GetProperty("addedCount").GetInt32());
|
||||
Assert.Equal(expectedResult.UpdatedOnUtc, data.GetProperty("updatedOnUtc").GetDateTime());
|
||||
List<(string Endpoint, object? Data)> addRequests = GetAddRequests();
|
||||
(string Endpoint, object? Data) addRequestCall = Assert.Single(addRequests);
|
||||
Assert.Equal(expectedEndpoint, addRequestCall.Endpoint);
|
||||
AddPlaylistEntriesRequest forwardedPayload = Assert.IsType<AddPlaylistEntriesRequest>(addRequestCall.Data);
|
||||
Assert.Equal(trackIds, forwardedPayload.TrackIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntries_WhenApiRejectsTheEntries_ShouldReturnAFailureEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-batch";
|
||||
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Validation", detail: "PlaylistEntryCannotBeNull"),
|
||||
HttpStatusCode.UnprocessableEntity,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains("<b>", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntries_WhenPlaylistDoesNotExist_ShouldReturnNotFoundEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-batch";
|
||||
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntries_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntries_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries-batch";
|
||||
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest("not-a-guid", request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedEndpoint], GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint));
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint)), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the add entries requests that were sent upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream add entries requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetAddRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PostRequests
|
||||
.Where(postRequest => postRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal)
|
||||
&& postRequest.Endpoint.EndsWith("/entries-batch", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the add entries request for the specified playlist route value.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="request">The request payload to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured add entries request.</returns>
|
||||
private static HttpRequestMessage CreateAddRequest(string playlistId, AddPlaylistEntriesRequest request, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/api-add-entries")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return addRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntry;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.AddPlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddPlaylistEntryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddPlaylistEntryEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly AddPlaylistEntryRequestFixture _addPlaylistEntryRequestFixture = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PlaylistEntryAddedDtoFixture _playlistEntryAddedDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistEntryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddPlaylistEntryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntry_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheTrackAndReturnTheAddedEntry()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: trackId);
|
||||
PlaylistEntryDto expectedEntry = _playlistEntryDtoFixture.Create(
|
||||
mediaItemId: trackId,
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
position: 3,
|
||||
mediaItemTitle: "Added track");
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries";
|
||||
PlaylistEntryAddedDto expectedResult = _playlistEntryAddedDtoFixture.Create(playlistId: playlistId, entry: expectedEntry);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, expectedResult);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(expectedResult.PlaylistId, data.GetProperty("playlistId").GetGuid());
|
||||
JsonElement entry = data.GetProperty("entry");
|
||||
Assert.Equal(expectedEntry.Id, entry.GetProperty("id").GetGuid());
|
||||
Assert.Equal(expectedEntry.MediaItemId, entry.GetProperty("mediaItemId").GetGuid());
|
||||
Assert.Equal(nameof(PlaylistMediaItemType.MusicTrack), entry.GetProperty("mediaItemType").GetString());
|
||||
Assert.Equal(expectedEntry.Position, entry.GetProperty("position").GetInt32());
|
||||
Assert.Equal(expectedEntry.MediaItemTitle, entry.GetProperty("mediaItemTitle").GetString());
|
||||
List<(string Endpoint, object? Data)> addRequests = GetAddRequests();
|
||||
(string Endpoint, object? Data) addRequestCall = Assert.Single(addRequests);
|
||||
Assert.Equal(expectedEndpoint, addRequestCall.Endpoint);
|
||||
AddPlaylistEntryRequest forwardedPayload = Assert.IsType<AddPlaylistEntryRequest>(addRequestCall.Data);
|
||||
Assert.Equal(trackId, forwardedPayload.TrackId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntry_WhenApiRejectsTheTrack_ShouldReturnAFailureEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries";
|
||||
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Validation", detail: "MusicTrackNotFound"),
|
||||
HttpStatusCode.UnprocessableEntity,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains("<b>", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntry_WhenPlaylistDoesNotExist_ShouldReturnNotFoundEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries";
|
||||
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntry_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntry_WhenPlaylistIdIsAnUppercaseGuid_ShouldForwardItInLowercase()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB");
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries";
|
||||
AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntryAddedDtoFixture.Create(playlistId: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString().ToUpperInvariant(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedEndpoint], GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint));
|
||||
Assert.DoesNotContain(playlistId.ToString().ToUpperInvariant(), string.Join(",", GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint)), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the add entry requests that were sent upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream add entry requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetAddRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PostRequests
|
||||
.Where(postRequest => postRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal)
|
||||
&& postRequest.Endpoint.EndsWith("/entries", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the add entry request for the specified playlist route value.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="request">The request payload to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured add entry request.</returns>
|
||||
private static HttpRequestMessage CreateAddRequest(string playlistId, AddPlaylistEntryRequest request, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/entries/api-add-entry")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return addRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistScopeEntries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.AddPlaylistScopeEntries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddPlaylistScopeEntriesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddPlaylistScopeEntriesEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly AddPlaylistScopeEntriesRequestFixture _addPlaylistScopeEntriesRequestFixture = new();
|
||||
private readonly PlaylistEntriesAddedDtoFixture _playlistEntriesAddedDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistScopeEntriesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddPlaylistScopeEntriesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistScopeEntries_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheScopeAndReturnTheAddedCount()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
artistId: artistId,
|
||||
albumId: albumId);
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-scope";
|
||||
PlaylistEntriesAddedDto expectedResult = _playlistEntriesAddedDtoFixture.Create(playlistId: playlistId, addedCount: 12);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, expectedResult);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(expectedResult.PlaylistId, data.GetProperty("playlistId").GetGuid());
|
||||
Assert.Equal(expectedResult.AddedCount, data.GetProperty("addedCount").GetInt32());
|
||||
List<(string Endpoint, object? Data)> addRequests = GetAddRequests();
|
||||
(string Endpoint, object? Data) addRequestCall = Assert.Single(addRequests);
|
||||
Assert.Equal(expectedEndpoint, addRequestCall.Endpoint);
|
||||
AddPlaylistScopeEntriesRequest forwardedPayload = Assert.IsType<AddPlaylistScopeEntriesRequest>(addRequestCall.Data);
|
||||
Assert.Equal(libraryId, forwardedPayload.LibraryId);
|
||||
Assert.Equal(artistId, forwardedPayload.ArtistId);
|
||||
Assert.Equal(albumId, forwardedPayload.AlbumId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistScopeEntries_WhenScopeIsLimitedToTheLibrary_ShouldForwardTheOptionalIdsAsNull()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
includeArtistId: false,
|
||||
includeAlbumId: false);
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-scope";
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
(string Endpoint, object? Data) addRequestCall = Assert.Single(GetAddRequests());
|
||||
AddPlaylistScopeEntriesRequest forwardedPayload = Assert.IsType<AddPlaylistScopeEntriesRequest>(addRequestCall.Data);
|
||||
Assert.Equal(libraryId, forwardedPayload.LibraryId);
|
||||
Assert.Null(forwardedPayload.ArtistId);
|
||||
Assert.Null(forwardedPayload.AlbumId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistScopeEntries_WhenApiRejectsTheScope_ShouldReturnAFailureEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-scope";
|
||||
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Validation", detail: "MusicLibraryNotFound"),
|
||||
HttpStatusCode.UnprocessableEntity,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains("<b>", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistScopeEntries_WhenPlaylistDoesNotExist_ShouldReturnNotFoundEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-scope";
|
||||
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistScopeEntries_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistScopeEntries_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries-scope";
|
||||
AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest("not-a-guid", request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedEndpoint], GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint));
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint)), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the add scope entries requests that were sent upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream add scope entries requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetAddRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PostRequests
|
||||
.Where(postRequest => postRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal)
|
||||
&& postRequest.Endpoint.EndsWith("/entries-scope", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the add scope entries request for the specified playlist route value.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="request">The request payload to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured add scope entries request.</returns>
|
||||
private static HttpRequestMessage CreateAddRequest(string playlistId, AddPlaylistScopeEntriesRequest request, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/api-add-scope-entries")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return addRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.CreatePlaylist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.CreatePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="CreatePlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CreatePlaylistEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string UPSTREAM_ENDPOINT = "users/me/playlists";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly CreatePlaylistRequestFixture _createPlaylistRequestFixture = new();
|
||||
private readonly PlaylistDtoFixture _playlistDtoFixture = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<PlaylistEntryDto> _paginatedDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CreatePlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public CreatePlaylistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreatePlaylist_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheDetailsAndReturnThePlaylist()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(
|
||||
name: "Road trip",
|
||||
description: "Songs for the highway.",
|
||||
type: PlaylistType.Music);
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create(
|
||||
name: request.Name!,
|
||||
description: request.Description,
|
||||
type: PlaylistType.Music,
|
||||
entries: _paginatedDtoFixture.Create(data: _playlistEntryDtoFixture.CreateMany(1)));
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(UPSTREAM_ENDPOINT, expectedPlaylist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage createRequest = CreateCreateRequest(request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(createRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(expectedPlaylist.Id, data.GetProperty("id").GetGuid());
|
||||
Assert.Equal(expectedPlaylist.Name, data.GetProperty("name").GetString());
|
||||
Assert.Equal(expectedPlaylist.Description, data.GetProperty("description").GetString());
|
||||
Assert.Equal(nameof(PlaylistType.Music), data.GetProperty("type").GetString());
|
||||
List<(string Endpoint, object? Data)> createRequests = GetCreateRequests();
|
||||
(string Endpoint, object? Data) createRequestCall = Assert.Single(createRequests);
|
||||
Assert.Equal(UPSTREAM_ENDPOINT, createRequestCall.Endpoint);
|
||||
CreatePlaylistRequest forwardedPayload = Assert.IsType<CreatePlaylistRequest>(createRequestCall.Data);
|
||||
Assert.Equal(request.Name, forwardedPayload.Name);
|
||||
Assert.Equal(request.Description, forwardedPayload.Description);
|
||||
Assert.Equal(PlaylistType.Music, forwardedPayload.Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreatePlaylist_WhenNoDescriptionIsProvided_ShouldForwardTheNullDescription()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: "No description", includeDescription: false);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(UPSTREAM_ENDPOINT, _playlistDtoFixture.Create(includeDescription: false));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage createRequest = CreateCreateRequest(request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(createRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
(string Endpoint, object? Data) createRequestCall = Assert.Single(GetCreateRequests());
|
||||
CreatePlaylistRequest forwardedPayload = Assert.IsType<CreatePlaylistRequest>(createRequestCall.Data);
|
||||
Assert.Null(forwardedPayload.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreatePlaylist_WhenApiRejectsTheDetails_ShouldReturnAFailureEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(includeName: false);
|
||||
_apiFactory.ApiClientStub.RegisterPostException(UPSTREAM_ENDPOINT, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Validation", detail: "PlaylistNameCannotBeEmpty"),
|
||||
HttpStatusCode.UnprocessableEntity,
|
||||
UPSTREAM_ENDPOINT));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage createRequest = CreateCreateRequest(request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(createRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains("<b>", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreatePlaylist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
CreatePlaylistRequest request = _createPlaylistRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage createRequest = CreateCreateRequest(request, antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(createRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetCreateRequests());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the create playlist requests that were sent upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream create playlist requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetCreateRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PostRequests
|
||||
.Where(postRequest => postRequest.Endpoint == UPSTREAM_ENDPOINT)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the create playlist request that sends the given <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request payload to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured create playlist request.</returns>
|
||||
private static HttpRequestMessage CreateCreateRequest(CreatePlaylistRequest request, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/playlists/api-create-playlist")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
createRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return createRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.DeletePlaylist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.DeletePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeletePlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeletePlaylistEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeletePlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeletePlaylistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePlaylist_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheDeleteAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(playlistId.ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
Assert.Equal([expectedEndpoint], GetDeleteEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePlaylist_WhenPlaylistDoesNotExist_ShouldReturnNotFoundEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(playlistId.ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePlaylist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(playlistId.ToString(), antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetDeleteEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePlaylist_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest("not-a-guid", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedEndpoint], GetDeleteEndpointCalls());
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", GetDeleteEndpointCalls()), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePlaylist_WhenPlaylistIdIsAnUppercaseGuid_ShouldForwardItInLowercase()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB");
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(playlistId.ToString().ToUpperInvariant(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> deleteEndpoints = GetDeleteEndpointCalls();
|
||||
Assert.Equal([expectedEndpoint], deleteEndpoints);
|
||||
Assert.DoesNotContain(playlistId.ToString().ToUpperInvariant(), string.Join(",", deleteEndpoints), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the delete playlist endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream delete playlist endpoints that were called.</returns>
|
||||
private List<string> GetDeleteEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete playlist request for the specified route value.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured delete playlist request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(string playlistId, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/api-delete-playlist")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return deleteRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.GetPlaylists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPlaylistsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistsEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string UPSTREAM_ENDPOINT = "users/me/playlists";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaylistSummaryDtoFixture _playlistSummaryDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPlaylistsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylists_WhenCalledByAuthenticatedUser_ShouldReturnThePlaylistsWithNonStorableCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
PlaylistSummaryDto firstPlaylist = _playlistSummaryDtoFixture.Create(
|
||||
name: "Evening listening",
|
||||
description: "Quiet tracks.",
|
||||
type: PlaylistType.Music,
|
||||
entryCount: 7);
|
||||
PlaylistSummaryDto secondPlaylist = _playlistSummaryDtoFixture.Create(
|
||||
name: "Morning run",
|
||||
type: PlaylistType.Music,
|
||||
entryCount: 0);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(UPSTREAM_ENDPOINT, new[] { firstPlaylist, secondPlaylist });
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/api-get-playlists");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
List<JsonElement> data = [.. json.RootElement.GetProperty("data").EnumerateArray()];
|
||||
Assert.Equal(2, data.Count);
|
||||
Assert.Equal(firstPlaylist.Id, data[0].GetProperty("id").GetGuid());
|
||||
Assert.Equal(firstPlaylist.Name, data[0].GetProperty("name").GetString());
|
||||
Assert.Equal(firstPlaylist.Description, data[0].GetProperty("description").GetString());
|
||||
Assert.Equal(nameof(PlaylistType.Music), data[0].GetProperty("type").GetString());
|
||||
Assert.Equal(firstPlaylist.EntryCount, data[0].GetProperty("entryCount").GetInt32());
|
||||
Assert.Equal(firstPlaylist.CreatedOnUtc, data[0].GetProperty("createdOnUtc").GetDateTime());
|
||||
Assert.Equal(secondPlaylist.Id, data[1].GetProperty("id").GetGuid());
|
||||
Assert.Equal([UPSTREAM_ENDPOINT], GetPlaylistEndpointCalls());
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylists_WhenUserHasNoPlaylists_ShouldReturnAnEmptyArray()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(UPSTREAM_ENDPOINT, Array.Empty<PlaylistSummaryDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/api-get-playlists");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Empty(json.RootElement.GetProperty("data").EnumerateArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylists_WhenApiReportsAnError_ShouldReturnAFailureEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetException(UPSTREAM_ENDPOINT, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "UnexpectedError"),
|
||||
HttpStatusCode.InternalServerError,
|
||||
UPSTREAM_ENDPOINT));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/playlists/api-get-playlists");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylists_WhenApiReportsNotFound_ShouldReturnTheNotFoundEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetException(UPSTREAM_ENDPOINT, new ApiException(null, HttpStatusCode.NotFound, UPSTREAM_ENDPOINT));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/playlists/api-get-playlists");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist endpoints that were called upstream, excluding the endpoints called by the authentication helpers.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream playlist endpoints that were called.</returns>
|
||||
private List<string> GetPlaylistEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint == UPSTREAM_ENDPOINT)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.Index;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="PlaylistsIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistsIndexViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/playlists";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaylistsIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public PlaylistsIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistsIndexView_WhenCalledByAuthenticatedUser_ShouldRenderThePlaylistsPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("playlists-container", content, StringComparison.Ordinal);
|
||||
Assert.Contains("no-playlists", content, StringComparison.Ordinal);
|
||||
Assert.Contains("create-playlist-button", content, StringComparison.Ordinal);
|
||||
Assert.Contains("playlist-count", content, StringComparison.Ordinal);
|
||||
Assert.Contains("__RequestVerificationToken", content, StringComparison.Ordinal);
|
||||
Assert.Contains("Playlists", content, StringComparison.Ordinal);
|
||||
Assert.Contains("You have no playlists yet.", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistsIndexView_WhenCalledByAuthenticatedUser_ShouldRenderThePageDataUrls()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains("/playlists/api-get-playlists", content, StringComparison.Ordinal);
|
||||
Assert.Contains("/playlists/item/00000000-0000-0000-0000-000000000000", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/me/playlists", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistsIndexView_WhenCalledByAuthenticatedUser_ShouldReturnANonStorablePage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("no-store", string.Join(", ", response.Headers.GetValues("Cache-Control")), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.MovePlaylistEntry;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.MovePlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="MovePlaylistEntryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MovePlaylistEntryEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MovePlaylistEntryRequestFixture _movePlaylistEntryRequestFixture = new();
|
||||
private readonly PlaylistEntryMovedDtoFixture _playlistEntryMovedDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MovePlaylistEntryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public MovePlaylistEntryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MovePlaylistEntry_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardThePositionAndReturnTheMovedEntry()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
Guid playlistEntryId = Guid.NewGuid();
|
||||
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 2);
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}/move";
|
||||
PlaylistEntryMovedDto expectedResult = _playlistEntryMovedDtoFixture.Create(
|
||||
playlistId: playlistId,
|
||||
entryId: playlistEntryId,
|
||||
position: 2);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, expectedResult);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage moveRequest = CreateMoveRequest(playlistId.ToString(), playlistEntryId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(expectedResult.PlaylistId, data.GetProperty("playlistId").GetGuid());
|
||||
Assert.Equal(expectedResult.EntryId, data.GetProperty("entryId").GetGuid());
|
||||
Assert.Equal(expectedResult.Position, data.GetProperty("position").GetInt32());
|
||||
List<(string Endpoint, object? Data)> moveRequests = GetMoveRequests();
|
||||
(string Endpoint, object? Data) moveRequestCall = Assert.Single(moveRequests);
|
||||
Assert.Equal(expectedEndpoint, moveRequestCall.Endpoint);
|
||||
MovePlaylistEntryRequest forwardedPayload = Assert.IsType<MovePlaylistEntryRequest>(moveRequestCall.Data);
|
||||
Assert.Equal(2, forwardedPayload.TargetPosition);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MovePlaylistEntry_WhenApiRejectsThePosition_ShouldReturnAFailureEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
Guid playlistEntryId = Guid.NewGuid();
|
||||
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}/move";
|
||||
_apiFactory.ApiClientStub.RegisterPutException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Validation", detail: "TargetPositionOutOfRange"),
|
||||
HttpStatusCode.UnprocessableEntity,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage moveRequest = CreateMoveRequest(playlistId.ToString(), playlistEntryId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains("<b>", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MovePlaylistEntry_WhenTheEntryDoesNotExist_ShouldReturnNotFoundEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
Guid playlistEntryId = Guid.NewGuid();
|
||||
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}/move";
|
||||
_apiFactory.ApiClientStub.RegisterPutException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage moveRequest = CreateMoveRequest(playlistId.ToString(), playlistEntryId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MovePlaylistEntry_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage moveRequest = CreateMoveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), request, antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetMoveRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MovePlaylistEntry_WhenRouteIdsAreNotGuids_ShouldForwardTheEmptyGuids()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create();
|
||||
string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}/move";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, _playlistEntryMovedDtoFixture.Create(playlistId: Guid.Empty, entryId: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage moveRequest = CreateMoveRequest("not-a-guid", "also-not-a-guid", request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedEndpoint], GetMoveRequests().Select(moveRequestCall => moveRequestCall.Endpoint));
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", GetMoveRequests().Select(moveRequestCall => moveRequestCall.Endpoint)), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the move entry requests that were sent upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream move entry requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetMoveRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PutRequests
|
||||
.Where(putRequest => putRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal)
|
||||
&& putRequest.Endpoint.EndsWith("/move", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the move entry request for the specified route values.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="playlistEntryId">The value of the playlist entry identifier route segment.</param>
|
||||
/// <param name="request">The request payload to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured move entry request.</returns>
|
||||
private static HttpRequestMessage CreateMoveRequest(string playlistId, string playlistEntryId, MovePlaylistEntryRequest request, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage moveRequest = new(HttpMethod.Put, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/entries/{Uri.EscapeDataString(playlistEntryId)}/api-move-entry")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
moveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
moveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
moveRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return moveRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.RemovePlaylistEntry;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.RemovePlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RemovePlaylistEntryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemovePlaylistEntryEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemovePlaylistEntryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public RemovePlaylistEntryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemovePlaylistEntry_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheDeleteAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
Guid playlistEntryId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(playlistId.ToString(), playlistEntryId.ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
Assert.Equal([expectedEndpoint], GetRemoveEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemovePlaylistEntry_WhenTheEntryDoesNotExist_ShouldReturnNotFoundEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
Guid playlistEntryId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(playlistId.ToString(), playlistEntryId.ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemovePlaylistEntry_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetRemoveEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemovePlaylistEntry_WhenRouteIdsAreNotGuids_ShouldForwardTheEmptyGuids()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest("not-a-guid", "also-not-a-guid", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedEndpoint], GetRemoveEndpointCalls());
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", GetRemoveEndpointCalls()), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemovePlaylistEntry_WhenRouteIdsAreUppercaseGuids_ShouldForwardThemInLowercase()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB");
|
||||
Guid playlistEntryId = Guid.Parse("FEDCBAFE-DCBA-FEDC-BAFE-DCBAFEDCBAFE");
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(
|
||||
playlistId.ToString().ToUpperInvariant(),
|
||||
playlistEntryId.ToString().ToUpperInvariant(),
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> removeEndpoints = GetRemoveEndpointCalls();
|
||||
Assert.Equal([expectedEndpoint], removeEndpoints);
|
||||
Assert.DoesNotContain(playlistEntryId.ToString().ToUpperInvariant(), string.Join(",", removeEndpoints), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the remove entry endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream remove entry endpoints that were called.</returns>
|
||||
private List<string> GetRemoveEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal)
|
||||
&& endpoint.Contains("/entries/", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the remove entry request for the specified route values.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="playlistEntryId">The value of the playlist entry identifier route segment.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured remove entry request.</returns>
|
||||
private static HttpRequestMessage CreateRemoveRequest(string playlistId, string playlistEntryId, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage removeRequest = new(HttpMethod.Delete, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/entries/{Uri.EscapeDataString(playlistEntryId)}/api-remove-entry")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
removeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
removeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
removeRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return removeRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.UpdatePlaylist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.UpdatePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdatePlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdatePlaylistEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdatePlaylistRequestFixture _updatePlaylistRequestFixture = new();
|
||||
private readonly PlaylistDetailsDtoFixture _playlistDetailsDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdatePlaylistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaylist_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheDetailsAndReturnThePlaylist()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(
|
||||
name: "Renamed playlist",
|
||||
description: "Updated description.");
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}";
|
||||
PlaylistDetailsDto expectedResult = _playlistDetailsDtoFixture.Create(
|
||||
id: playlistId,
|
||||
name: request.Name!,
|
||||
description: request.Description!,
|
||||
type: PlaylistType.Music);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, expectedResult);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = CreateUpdateRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(expectedResult.Id, data.GetProperty("id").GetGuid());
|
||||
Assert.Equal(expectedResult.Name, data.GetProperty("name").GetString());
|
||||
Assert.Equal(expectedResult.Description, data.GetProperty("description").GetString());
|
||||
Assert.Equal(nameof(PlaylistType.Music), data.GetProperty("type").GetString());
|
||||
Assert.Equal(expectedResult.UpdatedOnUtc, data.GetProperty("updatedOnUtc").GetDateTime());
|
||||
List<(string Endpoint, object? Data)> updateRequests = GetUpdateRequests();
|
||||
(string Endpoint, object? Data) updateRequestCall = Assert.Single(updateRequests);
|
||||
Assert.Equal(expectedEndpoint, updateRequestCall.Endpoint);
|
||||
UpdatePlaylistRequest forwardedPayload = Assert.IsType<UpdatePlaylistRequest>(updateRequestCall.Data);
|
||||
Assert.Equal(request.Name, forwardedPayload.Name);
|
||||
Assert.Equal(request.Description, forwardedPayload.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaylist_WhenNoDescriptionIsProvided_ShouldForwardTheNullDescription()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: "Cleared description", includeDescription: false);
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, _playlistDetailsDtoFixture.Create(id: playlistId, includeDescription: false));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = CreateUpdateRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
(string Endpoint, object? Data) updateRequestCall = Assert.Single(GetUpdateRequests());
|
||||
UpdatePlaylistRequest forwardedPayload = Assert.IsType<UpdatePlaylistRequest>(updateRequestCall.Data);
|
||||
Assert.Null(forwardedPayload.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaylist_WhenApiRejectsTheDetails_ShouldReturnAFailureEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(includeName: false);
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}";
|
||||
_apiFactory.ApiClientStub.RegisterPutException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Validation", detail: "PlaylistNameCannotBeEmpty"),
|
||||
HttpStatusCode.UnprocessableEntity,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = CreateUpdateRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains("<b>", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaylist_WhenPlaylistDoesNotExist_ShouldReturnNotFoundEnvelope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}";
|
||||
_apiFactory.ApiClientStub.RegisterPutException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = CreateUpdateRequest(playlistId.ToString(), request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaylist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = CreateUpdateRequest(playlistId.ToString(), request, antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetUpdateRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaylist_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create();
|
||||
string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, _playlistDetailsDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = CreateUpdateRequest("not-a-guid", request, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedEndpoint], GetUpdateRequests().Select(updateRequestCall => updateRequestCall.Endpoint));
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", GetUpdateRequests().Select(updateRequestCall => updateRequestCall.Endpoint)), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the update playlist requests that were sent upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream update playlist requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetUpdateRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PutRequests
|
||||
.Where(putRequest => putRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the update playlist request for the specified route value.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="request">The request payload to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured update playlist request.</returns>
|
||||
private static HttpRequestMessage CreateUpdateRequest(string playlistId, UpdatePlaylistRequest request, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/api-update-playlist")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return updateRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetPlaybackState;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings.GetPlaybackState;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPlaybackStateEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaybackStateEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaybackStateDtoFixture _playbackStateDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackStateEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPlaybackStateEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackState_WhenCalledByAuthenticatedUser_ShouldReturnPlaybackStateFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
PlaybackStateDto expectedState = _playbackStateDtoFixture.Create(volume: 0.35, isMuted: true);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("users/me/settings/playback-state", expectedState);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-playback-state");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(0.35, data.GetProperty("volume").GetDouble());
|
||||
Assert.True(data.GetProperty("isMuted").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "users/me/settings/playback-state");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackState_WhenApiReturnsTheDefaultState_ShouldReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
PlaybackStateDto expectedState = _playbackStateDtoFixture.Create(volume: 1.0, isMuted: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("users/me/settings/playback-state", expectedState);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-playback-state");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(1.0, data.GetProperty("volume").GetDouble());
|
||||
Assert.False(data.GetProperty("isMuted").GetBoolean());
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Common.Requests.Common;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdatePlaybackState;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings.UpdatePlaybackState;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdatePlaybackStateEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdatePlaybackStateEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaybackStateDtoFixture _playbackStateDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePlaybackStateEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdatePlaybackStateEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenCalledByAuthenticatedUser_ShouldUpdatePlaybackState()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings/playback-state", _ => new EmptyRequest());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
PlaybackStateDto state = _playbackStateDtoFixture.Create(volume: 0.35, isMuted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateUpdatePlaybackStateRequest(state, webClient.AntiforgeryToken));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(json.RootElement.GetProperty("data").GetProperty("isUpdated").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings/playback-state");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenCalledByAuthenticatedUser_ShouldForwardTheStateToApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings/playback-state", _ => new EmptyRequest());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
PlaybackStateDto state = _playbackStateDtoFixture.Create(volume: 0.0, isMuted: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateUpdatePlaybackStateRequest(state, webClient.AntiforgeryToken));
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
(string Endpoint, object? Data) putRequest = Assert.Single(
|
||||
_apiFactory.ApiClientStub.PutRequests,
|
||||
request => request.Endpoint == "users/me/settings/playback-state");
|
||||
PlaybackStateDto forwardedState = Assert.IsType<PlaybackStateDto>(putRequest.Data);
|
||||
Assert.Equal(0.0, forwardedState.Volume);
|
||||
Assert.False(forwardedState.IsMuted);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the update request that sends the given <paramref name="state"/> to the update playback state endpoint.
|
||||
/// </summary>
|
||||
/// <param name="state">The playback state to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured update request.</returns>
|
||||
private static HttpRequestMessage CreateUpdatePlaybackStateRequest(PlaybackStateDto state, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-playback-state")
|
||||
{
|
||||
Content = JsonContent.Create(state)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return updateRequest;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user