mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 05:01:10 +00:00
Implements tests for commit 525ac1348d
Covers the favorites feature and the playlist and favorite pagination changes with unit, integration and security tests, and fixtures for the new request, response, DTO and entity types. Also fixes the issues found while covering the commit: declares FavoriteMediaKind.None as the default value and rejects it in every favorite operation; queues the favorite added domain event only after the persisted favorite is read back; and preserves the private, no-store cache header on view pages after the antiforgery and session middlewares overwrite it.
This commit is contained in:
1 parent
468f1846f1
commit
394f6b510c
135 files changed
+19167
-13
No files matched your search
+1172
File diff suppressed because it is too large.
Load diff
+385
@@ -13,6 +13,8 @@ using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.Repositories.Playlists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -41,6 +43,7 @@ public class PlaylistRepositoryTests
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenNoEditableValueChanged_ShouldNotModifyTheStoredPlaylist()
|
||||
@@ -422,6 +425,388 @@ public class PlaylistRepositoryTests
|
||||
Assert.False(await context.PlaylistEntries.AsNoTracking().AnyAsync(entry => entry.Id == firstEntry.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenThePlaylistDoesNotExist_ShouldReturnSuccessWithNull()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-missing-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(Guid.NewGuid(), Guid.NewGuid(), paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenThePlaylistBelongsToAnotherUser_ShouldReturnSuccessWithNull()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-other-user-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid ownerUserId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: ownerUserId));
|
||||
(PlaylistEntity playlist, _) = await SeedOrderedPlaylistAsync(context, ownerUserId, entryCount: 2);
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlist.Id, Guid.NewGuid(), paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenNoPaginationIsRequested_ShouldReturnEveryEntryWithDenseDisplayPositions()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-all-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(PlaylistEntity playlist, List<PlaylistEntryEntity> entries) = await SeedOrderedPlaylistAsync(context, userId, entryCount: 3);
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlist.Id, userId, paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal([0, 1, 2], result.Value!.Entries.Data.Select(entry => entry.DisplayPosition));
|
||||
Assert.Equal(entries.Select(entry => entry.Id), result.Value.Entries.Data.Select(entry => entry.Entry.Id));
|
||||
Assert.Equal(1, result.Value.Entries.CurrentPage);
|
||||
Assert.Equal(3, result.Value.Entries.PerPage);
|
||||
Assert.Equal(3, result.Value.Entries.Count);
|
||||
Assert.Equal(1, result.Value.Entries.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenAPageIsRequested_ShouldReturnOnlyThatPageWithDenseDisplayPositions()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-page-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(PlaylistEntity playlist, List<PlaylistEntryEntity> entries) = await SeedOrderedPlaylistAsync(context, userId, entryCount: 5);
|
||||
PaginationDataDto firstPage = new() { CurrentPage = 1, PerPage = 2 };
|
||||
PaginationDataDto secondPage = new() { CurrentPage = 2, PerPage = 2 };
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> firstPageResult = await sut.GetDetailsForUserAsync(playlist.Id, userId, firstPage, CancellationToken.None);
|
||||
Result<PlaylistDetailsDto?> secondPageResult = await sut.GetDetailsForUserAsync(playlist.Id, userId, secondPage, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(firstPageResult.IsFailure);
|
||||
Assert.NotNull(firstPageResult.Value);
|
||||
Assert.Equal([0, 1], firstPageResult.Value!.Entries.Data.Select(entry => entry.DisplayPosition));
|
||||
Assert.Equal([entries[0].Id, entries[1].Id], firstPageResult.Value.Entries.Data.Select(entry => entry.Entry.Id));
|
||||
Assert.Equal(1, firstPageResult.Value.Entries.CurrentPage);
|
||||
Assert.Equal(2, firstPageResult.Value.Entries.PerPage);
|
||||
Assert.Equal(5, firstPageResult.Value.Entries.Count);
|
||||
Assert.Equal(3, firstPageResult.Value.Entries.NumberOfPages);
|
||||
|
||||
Assert.False(secondPageResult.IsFailure);
|
||||
Assert.NotNull(secondPageResult.Value);
|
||||
// The display positions continue from the offset of the page, so the second page starts at 2 and not at 0.
|
||||
Assert.Equal([2, 3], secondPageResult.Value!.Entries.Data.Select(entry => entry.DisplayPosition));
|
||||
Assert.Equal([entries[2].Id, entries[3].Id], secondPageResult.Value.Entries.Data.Select(entry => entry.Entry.Id));
|
||||
Assert.Equal(2, secondPageResult.Value.Entries.CurrentPage);
|
||||
Assert.Equal(5, secondPageResult.Value.Entries.Count);
|
||||
Assert.Equal(3, secondPageResult.Value.Entries.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenTheRequestedPageExceedsTheLastPage_ShouldClampToTheLastPage()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-clamp-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(PlaylistEntity playlist, List<PlaylistEntryEntity> entries) = await SeedOrderedPlaylistAsync(context, userId, entryCount: 5);
|
||||
PaginationDataDto beyondLastPage = new() { CurrentPage = 99, PerPage = 2 };
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlist.Id, userId, beyondLastPage, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(3, result.Value!.Entries.CurrentPage);
|
||||
PlaylistEntryDto lastEntry = Assert.Single(result.Value.Entries.Data);
|
||||
Assert.Equal(entries[4].Id, lastEntry.Entry.Id);
|
||||
Assert.Equal(4, lastEntry.DisplayPosition);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenThePlaylistIsEmptyAndAPageIsRequested_ShouldReturnAnEmptyPage()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-empty-page-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(PlaylistEntity playlist, _) = await SeedOrderedPlaylistAsync(context, userId, entryCount: 0);
|
||||
PaginationDataDto paginationData = new() { CurrentPage = 2, PerPage = 3 };
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlist.Id, userId, paginationData, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value!.Entries.Data);
|
||||
Assert.Equal(0, result.Value.Entries.Count);
|
||||
Assert.Equal(0, result.Value.Entries.NumberOfPages);
|
||||
Assert.Equal(1, result.Value.Entries.CurrentPage);
|
||||
Assert.Equal(3, result.Value.Entries.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenThePlaylistIsEmptyAndNoPaginationIsRequested_ShouldReturnAnEmptyResultWithOnePage()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(PlaylistEntity playlist, _) = await SeedOrderedPlaylistAsync(context, userId, entryCount: 0);
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlist.Id, userId, paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value!.Entries.Data);
|
||||
Assert.Equal(0, result.Value.Entries.PerPage);
|
||||
Assert.Equal(0, result.Value.Entries.Count);
|
||||
Assert.Equal(1, result.Value.Entries.NumberOfPages);
|
||||
Assert.Equal(1, result.Value.Entries.CurrentPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenAnEntryReferencesAMissingTrack_ShouldKeepTheEntryWithoutDisplayData()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-missing-track-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(_, _, TrackEntity track) = await SeedTrackAsync(context, libraryId, artistName: "Existing Artist", albumTitle: "Existing Album", trackTitle: "Existing Track", coverFileName: "existing-cover.jpg");
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
PlaylistEntryEntity existingEntry = _playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: track.Id,
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
position: 1_000_000_000L);
|
||||
PlaylistEntryEntity missingEntry = _playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
position: 2_000_000_000L);
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
type: PlaylistType.Music,
|
||||
entries: [existingEntry, missingEntry],
|
||||
entryCount: 2,
|
||||
version: 0);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlistId, userId, paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(2, result.Value!.Entries.Data.Count);
|
||||
PlaylistEntryDto missingItem = Assert.Single(result.Value.Entries.Data, entry => entry.Entry.Id == missingEntry.Id);
|
||||
Assert.Null(missingItem.Display);
|
||||
PlaylistEntryDto existingItem = Assert.Single(result.Value.Entries.Data, entry => entry.Entry.Id == existingEntry.Id);
|
||||
Assert.NotNull(existingItem.Display);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenTheEntriesReferenceMusicTracks_ShouldMapTheirDisplayData()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-display-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
string coverFileName = "album-cover.jpg";
|
||||
(ArtistEntity artist, AlbumEntity album, TrackEntity track) = await SeedTrackAsync(
|
||||
context,
|
||||
libraryId,
|
||||
artistName: "Display Artist",
|
||||
albumTitle: "Display Album",
|
||||
trackTitle: "Display Track",
|
||||
coverFileName: coverFileName);
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
PlaylistEntryEntity entry = _playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: track.Id,
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
position: 1_000_000_000L);
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
type: PlaylistType.Music,
|
||||
entries: [entry],
|
||||
entryCount: 1,
|
||||
version: 0);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlistId, userId, paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
PlaylistEntryDto item = Assert.Single(result.Value!.Entries.Data);
|
||||
Assert.NotNull(item.Display);
|
||||
Assert.Equal(track.Id, item.Display!.TrackId);
|
||||
Assert.Equal("Display Track", item.Display.TrackTitle);
|
||||
Assert.Equal(track.DurationInSeconds, item.Display.DurationInSeconds);
|
||||
Assert.Equal(libraryId, item.Display.LibraryId);
|
||||
Assert.Equal(album.Id, item.Display.AlbumId);
|
||||
Assert.Equal("Display Album", item.Display.AlbumTitle);
|
||||
Assert.Equal(artist.Id, item.Display.ArtistId);
|
||||
Assert.Equal("Display Artist", item.Display.ArtistName);
|
||||
Assert.Equal(coverFileName, item.Display.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenAnEntryReferencesANonMusicMediaItem_ShouldReturnNoDisplayData()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-video-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(_, _, TrackEntity track) = await SeedTrackAsync(context, libraryId, artistName: "Video Artist", albumTitle: "Video Album", trackTitle: "Video Track", coverFileName: "video-cover.jpg");
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
// The media item Id belongs to a real track, so a null display proves the entry type is what excludes it, not a missing row.
|
||||
PlaylistEntryEntity entry = _playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: track.Id,
|
||||
mediaItemType: PlaylistMediaItemType.VideoFile,
|
||||
position: 1_000_000_000L);
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
type: PlaylistType.Music,
|
||||
entries: [entry],
|
||||
entryCount: 1,
|
||||
version: 0);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlistId, userId, paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
PlaylistEntryDto item = Assert.Single(result.Value!.Entries.Data);
|
||||
Assert.Null(item.Display);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a playlist of the given user with the requested number of entries, each referencing a different generated media item.
|
||||
/// </summary>
|
||||
/// <param name="context">The context to seed.</param>
|
||||
/// <param name="userId">The Id of the user that owns the playlist.</param>
|
||||
/// <param name="entryCount">The number of entries the playlist receives.</param>
|
||||
/// <returns>The seeded playlist and its entries, in position order.</returns>
|
||||
private async Task<(PlaylistEntity Playlist, List<PlaylistEntryEntity> Entries)> SeedOrderedPlaylistAsync(LuminaDbContext context, Guid userId, int entryCount)
|
||||
{
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
List<PlaylistEntryEntity> entries = [.. Enumerable.Range(0, entryCount).Select(index => _playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
position: (index + 1) * 1_000_000_000L))];
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
type: PlaylistType.Music,
|
||||
entries: entries,
|
||||
entryCount: entries.Count,
|
||||
version: 0);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
return (playlist, entries);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds one artist, one album of that artist and one track of that album, together with the cover artwork of the album.
|
||||
/// </summary>
|
||||
/// <param name="context">The context to seed.</param>
|
||||
/// <param name="libraryId">The Id of the library the catalogue belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="coverFileName">The file name of the cover artwork of the album.</param>
|
||||
/// <returns>The seeded artist, album and track.</returns>
|
||||
private async Task<(ArtistEntity Artist, AlbumEntity Album, TrackEntity Track)> SeedTrackAsync(
|
||||
LuminaDbContext context,
|
||||
Guid libraryId,
|
||||
string artistName,
|
||||
string albumTitle,
|
||||
string trackTitle,
|
||||
string coverFileName)
|
||||
{
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false);
|
||||
context.Artists.Add(artist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(album);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: trackTitle, includeMetadata: false);
|
||||
context.Tracks.Add(track);
|
||||
context.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album,
|
||||
ownerId: album.Id,
|
||||
artworkType: ArtworkType.Cover,
|
||||
ordinal: 0,
|
||||
fileName: coverFileName));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
return (artist, album, track);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
|
||||
/// </summary>
|
||||
|
||||
+178
@@ -1,12 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -25,6 +35,8 @@ public class UnitOfWorkTests
|
||||
{
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task BeginTransactionAsync_WhenCalled_ShouldBeginTransactionOnTheDatabase()
|
||||
@@ -216,6 +228,150 @@ public class UnitOfWorkTests
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FavoriteRepository_WhenAccessedRepeatedly_ShouldReturnTheSameCachedInstance()
|
||||
{
|
||||
// Arrange
|
||||
(SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext();
|
||||
using (anchorConnection)
|
||||
{
|
||||
using (dbContext)
|
||||
{
|
||||
UnitOfWork sut = new(dbContext);
|
||||
|
||||
// Act
|
||||
IFavoriteRepository firstRepository = sut.FavoriteRepository;
|
||||
IFavoriteRepository secondRepository = sut.FavoriteRepository;
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(firstRepository);
|
||||
Assert.Same(firstRepository, secondRepository);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveChangesAsync_WhenInsertingTwoFavoritesForTheSameUserKindAndMediaItem_ShouldReturnUniqueConstraintViolationError()
|
||||
{
|
||||
// Arrange
|
||||
(SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext();
|
||||
using (anchorConnection)
|
||||
{
|
||||
using (dbContext)
|
||||
{
|
||||
UnitOfWork sut = new(dbContext);
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
Result<Success> userSaveResult = await sut.SaveChangesAsync(CancellationToken.None);
|
||||
Assert.False(userSaveResult.IsFailure);
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
FavoriteEntity firstFavorite = _favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: FavoriteMediaKind.MusicArtist,
|
||||
mediaItemId: mediaItemId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false);
|
||||
_ = await sut.FavoriteRepository.InsertAsync(firstFavorite, CancellationToken.None);
|
||||
Result<Success> firstSaveResult = await sut.SaveChangesAsync(CancellationToken.None);
|
||||
Assert.False(firstSaveResult.IsFailure);
|
||||
|
||||
// stage a duplicate directly through the repository, bypassing the application level existence check, so that the unique index of the storage medium is the one that rejects it
|
||||
FavoriteEntity duplicateFavorite = _favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: FavoriteMediaKind.MusicArtist,
|
||||
mediaItemId: mediaItemId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false);
|
||||
_ = await sut.FavoriteRepository.InsertAsync(duplicateFavorite, CancellationToken.None);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await sut.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearTrackedEntities_WhenEntitiesAreTracked_ShouldDetachEveryEntity()
|
||||
{
|
||||
// Arrange
|
||||
(SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext();
|
||||
using (anchorConnection)
|
||||
{
|
||||
using (dbContext)
|
||||
{
|
||||
UnitOfWork sut = new(dbContext);
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId);
|
||||
FavoriteEntity favorite = _favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: FavoriteMediaKind.MusicTrack,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false);
|
||||
dbContext.Users.Add(user);
|
||||
dbContext.Favorites.Add(favorite);
|
||||
await dbContext.SaveChangesAsync();
|
||||
Assert.Equal(2, dbContext.ChangeTracker.Entries().Count());
|
||||
|
||||
// Act
|
||||
sut.ClearTrackedEntities();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(dbContext.ChangeTracker.Entries());
|
||||
Assert.Equal(EntityState.Detached, dbContext.Entry(favorite).State);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveChangesAsync_WhenInsertingAValidFavorite_ShouldPersistEveryFieldThroughTheAuditInterceptor()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
(SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateAuditedSqliteContext(userId, utcNow);
|
||||
using (anchorConnection)
|
||||
{
|
||||
using (dbContext)
|
||||
{
|
||||
UnitOfWork sut = new(dbContext);
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
// The fixture populates the update audit columns, so the test also proves the interceptor owns them on insert.
|
||||
FavoriteEntity favorite = _favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: FavoriteMediaKind.Book,
|
||||
mediaItemId: mediaItemId,
|
||||
createdOnUtc: DateTime.MinValue,
|
||||
createdBy: Guid.Empty,
|
||||
updatedOnUtc: DateTime.MaxValue,
|
||||
updatedBy: Guid.NewGuid(),
|
||||
includeUpdatedOnUtc: true,
|
||||
includeUpdatedBy: true);
|
||||
Result<Created> insertResult = await sut.FavoriteRepository.InsertAsync(favorite, CancellationToken.None);
|
||||
Assert.False(insertResult.IsFailure);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await sut.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
dbContext.ChangeTracker.Clear();
|
||||
FavoriteEntity storedFavorite = await dbContext.Favorites.AsNoTracking().SingleAsync(candidate => candidate.Id == favorite.Id);
|
||||
Assert.Equal(userId, storedFavorite.UserId);
|
||||
Assert.Equal(FavoriteMediaKind.Book, storedFavorite.MediaKind);
|
||||
Assert.Equal(mediaItemId, storedFavorite.MediaItemId);
|
||||
Assert.Equal(utcNow, storedFavorite.CreatedOnUtc);
|
||||
Assert.Equal(userId, storedFavorite.CreatedBy);
|
||||
Assert.Null(storedFavorite.UpdatedOnUtc);
|
||||
Assert.Null(storedFavorite.UpdatedBy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite in-memory context, kept alive by an anchor connection, because transactions are not supported by the in-memory provider.
|
||||
/// </summary>
|
||||
@@ -228,4 +384,26 @@ public class UnitOfWorkTests
|
||||
dbContext.Database.EnsureCreated();
|
||||
return (anchorConnection, dbContext);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite in-memory context with the auditing interceptor attached, so that audit columns behave exactly like in production.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user reported as the current user.</param>
|
||||
/// <param name="utcNow">The current UTC time reported by the time provider.</param>
|
||||
/// <returns>A tuple containing the anchor connection and the database context.</returns>
|
||||
private static (SqliteConnection AnchorConnection, LuminaDbContext Context) CreateAuditedSqliteContext(Guid userId, DateTime utcNow)
|
||||
{
|
||||
SqliteConnection anchorConnection = new($"Data Source=luminadataccess-unitofwork-audit-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
|
||||
currentUserService.UserId.Returns(userId);
|
||||
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
dateTimeProvider.UtcNow.Returns(utcNow);
|
||||
LuminaDbContext dbContext = new(new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseSqlite(anchorConnection.ConnectionString)
|
||||
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
|
||||
.Options);
|
||||
dbContext.Database.EnsureCreated();
|
||||
return (anchorConnection, dbContext);
|
||||
}
|
||||
}
|
||||
+568
@@ -0,0 +1,568 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.AddFavorite;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Favorites.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private const string PATH = "/api/v1/users/me/favorites";
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededMediaContributorIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddFavoriteEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist)] // a favorite of an artist of a music library
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum)] // a favorite of an album of a music library
|
||||
[InlineData(FavoriteMediaKind.MusicTrack)] // a favorite of a track of a music library
|
||||
[InlineData(FavoriteMediaKind.Book)] // a favorite of a book of a book library
|
||||
public async Task AddFavorite_WhenMediaItemExists_ShouldReturnTheFavoriteAndStoreOneRowForTheCaller(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Dictionary<FavoriteMediaKind, Guid> mediaItemIds = await SeedCatalogueAsync(userId);
|
||||
Guid mediaItemId = mediaItemIds[mediaKind];
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = mediaKind.ToString(), mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
FavoriteResponse? favorite = await DeserializeAsync<FavoriteResponse>(response);
|
||||
Assert.NotNull(favorite);
|
||||
Assert.NotEqual(Guid.Empty, favorite!.Id);
|
||||
Assert.Equal(mediaKind, favorite.MediaKind);
|
||||
Assert.Equal(mediaItemId, favorite.MediaItemId);
|
||||
Assert.NotEqual(default, favorite.FavoritedOnUtc);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<FavoriteEntity> rows = await dbContext.Favorites
|
||||
.AsNoTracking()
|
||||
.Where(candidate => candidate.UserId == userId && candidate.MediaKind == mediaKind && candidate.MediaItemId == mediaItemId)
|
||||
.ToListAsync();
|
||||
FavoriteEntity row = Assert.Single(rows);
|
||||
Assert.Equal(favorite.Id, row.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenTheSameItemIsAddedTwice_ShouldReturnTheSameFavoriteAndKeepASingleRow()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = await SeedTrackAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = mediaItemId });
|
||||
HttpResponseMessage secondResponse = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
|
||||
FavoriteResponse? firstFavorite = await DeserializeAsync<FavoriteResponse>(firstResponse);
|
||||
FavoriteResponse? secondFavorite = await DeserializeAsync<FavoriteResponse>(secondResponse);
|
||||
Assert.NotNull(firstFavorite);
|
||||
Assert.NotNull(secondFavorite);
|
||||
Assert.Equal(firstFavorite!.Id, secondFavorite!.Id);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.Favorites.CountAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist, "ArtistNotFound")] // a missing artist is reported with the artist detail
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum, "AlbumNotFound")] // a missing album is reported with the album detail
|
||||
[InlineData(FavoriteMediaKind.MusicTrack, "TrackNotFound")] // a missing track is reported with the track detail
|
||||
[InlineData(FavoriteMediaKind.Book, "BookNotFound")] // a missing book is reported with the book detail
|
||||
public async Task AddFavorite_WhenMediaItemDoesNotExist_ShouldReturnNotFoundWithTheKindSpecificDetail(FavoriteMediaKind mediaKind, string expectedDetail)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = mediaKind.ToString(), mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, PATH);
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.Video)] // video libraries are not catalogued yet
|
||||
[InlineData(FavoriteMediaKind.Photo)] // photo libraries are not catalogued yet
|
||||
public async Task AddFavorite_WhenMediaKindIsPlanned_ShouldReturnValidationProblem(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = mediaKind.ToString(), mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsNotSupported");
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenMediaKindIsMissing_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = (string?)null, mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = nameof(FavoriteMediaKind.None), mediaItemId });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenMediaItemIdIsEmpty_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = Guid.Empty });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdCannotBeEmpty");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == Guid.Empty));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenTheBodyIsEmpty_ShouldReturnBothValidationProblems()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsInvalid", "FavoriteMediaItemIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenMediaItemBelongsToAnotherUsersLibrary_ShouldReturnTheSameNotFoundAsAMissingItem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherTrackId = await SeedTrackAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = otherTrackId });
|
||||
|
||||
// Assert
|
||||
// The response is indistinguishable from the one of a missing item, so it cannot be used to probe another user's library.
|
||||
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", PATH);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.MediaItemId == otherTrackId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds one artist, one album, one track and one book owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the seeded libraries.</param>
|
||||
/// <returns>The Ids of the seeded media items, keyed by their kind.</returns>
|
||||
private async Task<Dictionary<FavoriteMediaKind, Guid>> SeedCatalogueAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Favorite Artist");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Favorite Album");
|
||||
Guid trackId = await SeedTrackAsync(musicLibraryId, albumId, "Favorite Track");
|
||||
await SeedAlbumCoverAsync(albumId, "favorite-cover.jpg");
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook);
|
||||
Guid bookId = await SeedBookAsync(bookLibraryId, "Favorite Book", "Favorite Author");
|
||||
|
||||
return new Dictionary<FavoriteMediaKind, Guid>
|
||||
{
|
||||
[FavoriteMediaKind.MusicArtist] = artistId,
|
||||
[FavoriteMediaKind.MusicAlbum] = albumId,
|
||||
[FavoriteMediaKind.MusicTrack] = trackId,
|
||||
[FavoriteMediaKind.Book] = bookId
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/> with one track, and returns the Id of that track.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the seeded library.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Single Artist");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Single Album");
|
||||
return await SeedTrackAsync(musicLibraryId, albumId, "Single Track");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library of the given type owned by <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the media library.</param>
|
||||
/// <param name="libraryType">The type of the media library.</param>
|
||||
/// <returns>The Id of the seeded media library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId, userId: userId, title: $"Library-{Guid.NewGuid():N}", libraryType: libraryType, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(
|
||||
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Albums.Add(album);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the cover artwork of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="albumId">The Id of the album that owns the artwork.</param>
|
||||
/// <param name="fileName">The file name of the stored cover.</param>
|
||||
private async Task SeedAlbumCoverAsync(Guid albumId, string fileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album,
|
||||
ownerId: albumId,
|
||||
artworkType: ArtworkType.Cover,
|
||||
ordinal: 0,
|
||||
fileName: fileName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of the library identified by <paramref name="libraryId"/>, with one author.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the book belongs to.</param>
|
||||
/// <param name="title">The title of the book.</param>
|
||||
/// <param name="authorName">The display name of the author of the book.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string title, string authorName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid contributorId = Guid.NewGuid();
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(id: bookId, libraryId: libraryId, title: title, includeMetadata: false));
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId, displayName: authorName));
|
||||
dbContext.BookContributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId, role: MediaContributorRole.Author));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededMediaContributorIds.Add(contributorId);
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a problem details document with the expected status, title and detail.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedStatus">The expected HTTP status.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private static async Task AssertProblemAsync(HttpResponseMessage response, HttpStatusCode expectedStatus, string expectedTitle, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(expectedStatus, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)expectedStatus, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a validation problem details document carrying exactly the expected error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present, in order.</param>
|
||||
private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(422, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Equal(expectedErrorCodes, errors!["General.Validation"]);
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||
List<Guid> albumIds = await dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)).Select(album => album.Id).ToListAsync();
|
||||
List<Guid> bookIds = await dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)).Select(book => book.Id).ToListAsync();
|
||||
dbContext.MusicArtwork.RemoveRange(dbContext.MusicArtwork.Where(artwork => albumIds.Contains(artwork.OwnerId)));
|
||||
dbContext.BookContributors.RemoveRange(dbContext.BookContributors.Where(contributor => bookIds.Contains(contributor.BookId)));
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId)));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId)));
|
||||
dbContext.Books.RemoveRange(dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||
dbContext.MediaContributors.RemoveRange(dbContext.MediaContributors.Where(contributor => _seededMediaContributorIds.Contains(contributor.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFavoriteStatusEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private const string PATH = "/api/v1/users/me/favorites/status";
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededFavoriteIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetFavoriteStatusEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenSomeOfTheRequestedItemsAreFavorites_ShouldReturnExactlyThoseIdsOfTheCallerAndKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid favoritedTrackId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid notFavoritedId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, favoritedTrackId);
|
||||
// The book is a favorite of the caller, but of another kind, so it must not be reported for a MusicTrack query.
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.Book, bookId);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserTrackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(otherUserId, FavoriteMediaKind.MusicTrack, otherUserTrackId);
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&mediaItemIds={favoritedTrackId}&mediaItemIds={bookId}&mediaItemIds={otherUserTrackId}&mediaItemIds={notFavoritedId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
FavoriteStatusResponse? status = await DeserializeAsync<FavoriteStatusResponse>(response);
|
||||
Assert.NotNull(status);
|
||||
Guid favoritedId = Assert.Single(status!.FavoritedMediaItemIds);
|
||||
Assert.Equal(favoritedTrackId, favoritedId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTheSameIdIsRequestedTwice_ShouldReturnItOnce()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid favoritedTrackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, favoritedTrackId);
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&mediaItemIds={favoritedTrackId}&mediaItemIds={favoritedTrackId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
FavoriteStatusResponse? status = await DeserializeAsync<FavoriteStatusResponse>(response);
|
||||
Assert.NotNull(status);
|
||||
Guid favoritedId = Assert.Single(status!.FavoritedMediaItemIds);
|
||||
Assert.Equal(favoritedTrackId, favoritedId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenOneHundredIdsAreRequested_ShouldAcceptThem()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> requestedIds = [.. Enumerable.Range(0, 100).Select(_ => Guid.NewGuid())];
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&{string.Join("&", requestedIds.Select(requestedId => $"mediaItemIds={requestedId}"))}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
FavoriteStatusResponse? status = await DeserializeAsync<FavoriteStatusResponse>(response);
|
||||
Assert.NotNull(status);
|
||||
Assert.Empty(status!.FavoritedMediaItemIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenMoreThanOneHundredIdsAreRequested_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> requestedIds = [.. Enumerable.Range(0, 101).Select(_ => Guid.NewGuid())];
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&{string.Join("&", requestedIds.Select(requestedId => $"mediaItemIds={requestedId}"))}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdsExceedMaximumCount");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenNoMediaItemIdsAreProvided_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdsCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTheEmptyGuidIsRequested_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack&mediaItemIds={Guid.Empty}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTheMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid favoritedTrackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, favoritedTrackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind={nameof(FavoriteMediaKind.None)}&mediaItemIds={favoritedTrackId}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsInvalid");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(favoritedTrackId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTheMediaKindIsNotAMemberName_ShouldNotReturnAnyId()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid favoritedTrackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, favoritedTrackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=NotAMediaKind&mediaItemIds={favoritedTrackId}");
|
||||
|
||||
// Assert
|
||||
// The request binds the media kind as an enumeration, so an unparseable value is answered by the generic exception handler
|
||||
// with the sanitized problem before the handler runs, and no favorite status is disclosed.
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(favoritedTrackId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <returns>The Id of the seeded favorite.</returns>
|
||||
private async Task<Guid> SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid favoriteId = Guid.NewGuid();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
id: favoriteId,
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededFavoriteIds.Add(favoriteId);
|
||||
return favoriteId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a validation problem details document carrying the expected error code.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCode">The expected validation error code.</param>
|
||||
private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(422, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Favorites.RemoveRange(dbContext.Favorites.Where(favorite => _seededFavoriteIds.Contains(favorite.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+638
@@ -0,0 +1,638 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavorites;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Favorites.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFavoritesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private const string PATH = "/api/v1/users/me/favorites";
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededMediaContributorIds = [];
|
||||
private readonly List<Guid> _seededFavoriteIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetFavoritesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenFavoritesOfSeveralKindsExist_ShouldReturnOnlyTheCallersFavorites()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Caller Artist");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Caller Album");
|
||||
Guid trackId = await SeedTrackAsync(musicLibraryId, albumId, "Caller Track");
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook);
|
||||
Guid bookId = await SeedBookAsync(bookLibraryId, "Caller Book", "Caller Author");
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.Book, bookId);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherTrackId = await SeedTrackAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
Assert.Equal(2, favorites!.Count);
|
||||
Assert.Equal(2, favorites.Data.Count);
|
||||
Assert.Contains(favorites.Data, favorite => favorite.MediaKind == FavoriteMediaKind.MusicTrack && favorite.MediaItemId == trackId);
|
||||
Assert.Contains(favorites.Data, favorite => favorite.MediaKind == FavoriteMediaKind.Book && favorite.MediaItemId == bookId);
|
||||
Assert.DoesNotContain(favorites.Data, favorite => favorite.MediaItemId == otherTrackId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenNoPaginationIsRequested_ShouldReturnEveryFavoriteInOnePageFromTheMostRecent()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstFavoriteId = await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, Guid.NewGuid());
|
||||
Guid secondFavoriteId = await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, Guid.NewGuid());
|
||||
Guid thirdFavoriteId = await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, Guid.NewGuid());
|
||||
DateTime now = DateTime.UtcNow;
|
||||
// The auditing interceptor stamps the creation time of an added row, so the favoriting order is restored after the insert.
|
||||
await SetCreatedOnUtcAsync(firstFavoriteId, now.AddMinutes(-30));
|
||||
await SetCreatedOnUtcAsync(secondFavoriteId, now.AddMinutes(-20));
|
||||
await SetCreatedOnUtcAsync(thirdFavoriteId, now.AddMinutes(-10));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
Assert.Equal(1, favorites!.CurrentPage);
|
||||
Assert.Equal(3, favorites.PerPage);
|
||||
Assert.Equal(3, favorites.Count);
|
||||
Assert.Equal(1, favorites.NumberOfPages);
|
||||
FavoriteEntity thirdFavorite = await GetFavoriteAsync(thirdFavoriteId);
|
||||
FavoriteEntity secondFavorite = await GetFavoriteAsync(secondFavoriteId);
|
||||
FavoriteEntity firstFavorite = await GetFavoriteAsync(firstFavoriteId);
|
||||
Assert.Equal(
|
||||
new[] { thirdFavorite.MediaItemId, secondFavorite.MediaItemId, firstFavorite.MediaItemId },
|
||||
favorites.Data.Select(favorite => favorite.MediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenAPageIsRequested_ShouldReturnDisjointRowsAndThePaginationMetadata()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
for (int index = 0; index < 5; index++)
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, Guid.NewGuid());
|
||||
string firstPageUrl = $"{PATH}?currentPage=1&perPage=2";
|
||||
string secondPageUrl = $"{PATH}?currentPage=2&perPage=2";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstPageResponse = await _client.GetAsync(firstPageUrl);
|
||||
HttpResponseMessage secondPageResponse = await _client.GetAsync(secondPageUrl);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, firstPageResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, secondPageResponse.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? firstPage = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(firstPageResponse);
|
||||
PaginatedResponse<FavoriteItemResponse>? secondPage = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(secondPageResponse);
|
||||
Assert.NotNull(firstPage);
|
||||
Assert.NotNull(secondPage);
|
||||
Assert.Equal(1, firstPage!.CurrentPage);
|
||||
Assert.Equal(2, firstPage.PerPage);
|
||||
Assert.Equal(5, firstPage.Count);
|
||||
Assert.Equal(3, firstPage.NumberOfPages);
|
||||
Assert.Equal(2, firstPage.Data.Count);
|
||||
Assert.Equal(2, secondPage!.CurrentPage);
|
||||
Assert.Equal(2, secondPage.PerPage);
|
||||
Assert.Equal(5, secondPage.Count);
|
||||
Assert.Equal(3, secondPage.NumberOfPages);
|
||||
Assert.Equal(2, secondPage.Data.Count);
|
||||
Assert.Empty(firstPage.Data.Select(favorite => favorite.MediaItemId).Intersect(secondPage.Data.Select(favorite => favorite.MediaItemId)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenAMediaKindIsRequested_ShouldReturnOnlyThatKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.Book, bookId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.Equal(FavoriteMediaKind.MusicTrack, favorite.MediaKind);
|
||||
Assert.Equal(trackId, favorite.MediaItemId);
|
||||
Assert.Equal(1, favorites.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenAFavoritedTrackExists_ShouldReturnTheAlbumAsTheCollectionAndTheArtistAsTheCreator()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "A Night at the Opera");
|
||||
Guid trackId = await SeedTrackAsync(musicLibraryId, albumId, "Bohemian Rhapsody");
|
||||
await SeedAlbumCoverAsync(albumId, "a-night-at-the-opera-cover.jpg");
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.True(favorite.IsAvailable);
|
||||
Assert.Equal(musicLibraryId, favorite.LibraryId);
|
||||
Assert.Equal("Bohemian Rhapsody", favorite.Title);
|
||||
Assert.Equal(albumId, favorite.CollectionId);
|
||||
Assert.Equal("A Night at the Opera", favorite.CollectionTitle);
|
||||
Assert.Equal(artistId, favorite.CreatorId);
|
||||
Assert.Equal("Queen", favorite.CreatorName);
|
||||
Assert.Equal("a-night-at-the-opera-cover.jpg", favorite.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenAFavoritedBookExists_ShouldReturnTheAuthorAsTheCreatorAndNoCollection()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook);
|
||||
Guid bookId = await SeedBookAsync(bookLibraryId, "The Fellowship of the Ring", "J. R. R. Tolkien");
|
||||
Guid authorId = _seededMediaContributorIds[^1];
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.Book, bookId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=Book");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.True(favorite.IsAvailable);
|
||||
Assert.Equal(bookLibraryId, favorite.LibraryId);
|
||||
Assert.Equal("The Fellowship of the Ring", favorite.Title);
|
||||
Assert.Equal(Guid.Empty, favorite.CollectionId);
|
||||
Assert.Equal(string.Empty, favorite.CollectionTitle);
|
||||
Assert.Equal(authorId, favorite.CreatorId);
|
||||
Assert.Equal("J. R. R. Tolkien", favorite.CreatorName);
|
||||
Assert.Null(favorite.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenTheFavoritedItemWasDeleted_ShouldReturnTheRowAsUnavailableWithEmptyDisplayFields()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid deletedItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, deletedItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.Equal(deletedItemId, favorite.MediaItemId);
|
||||
Assert.False(favorite.IsAvailable);
|
||||
Assert.Equal(Guid.Empty, favorite.LibraryId);
|
||||
Assert.Equal(string.Empty, favorite.Title);
|
||||
Assert.Equal(Guid.Empty, favorite.CollectionId);
|
||||
Assert.Equal(string.Empty, favorite.CollectionTitle);
|
||||
Assert.Equal(Guid.Empty, favorite.CreatorId);
|
||||
Assert.Equal(string.Empty, favorite.CreatorName);
|
||||
Assert.Null(favorite.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenTheFavoritedItemBelongsToAnInaccessibleLibrary_ShouldStillReturnTheRowAsUnavailable()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherMusicLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music);
|
||||
Guid otherArtistId = await SeedArtistAsync(otherMusicLibraryId, "Other Artist");
|
||||
Guid otherAlbumId = await SeedAlbumAsync(otherMusicLibraryId, otherArtistId, "Other Album");
|
||||
Guid otherTrackId = await SeedTrackAsync(otherMusicLibraryId, otherAlbumId, "Other Track");
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, otherTrackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.Equal(otherTrackId, favorite.MediaItemId);
|
||||
Assert.False(favorite.IsAvailable);
|
||||
Assert.Equal(Guid.Empty, favorite.LibraryId);
|
||||
Assert.Equal(string.Empty, favorite.Title);
|
||||
Assert.Equal(Guid.Empty, favorite.CollectionId);
|
||||
Assert.Equal(Guid.Empty, favorite.CreatorId);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Other Track", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Other Artist", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Other Album", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenTheMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind={nameof(FavoriteMediaKind.None)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal(422, problemDetails.RootElement.GetProperty("status").GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("FavoriteMediaKindIsInvalid", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(trackId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenTheMediaKindIsNotAMemberName_ShouldNotReturnAnyFavorite()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=NotAMediaKind");
|
||||
|
||||
// Assert
|
||||
// The request binds the media kind as an enumeration, so an unparseable value is answered by the generic exception handler
|
||||
// with the sanitized problem before the handler runs, and no favorite is disclosed.
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(trackId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library of the given type owned by <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the media library.</param>
|
||||
/// <param name="libraryType">The type of the media library.</param>
|
||||
/// <returns>The Id of the seeded media library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId, userId: userId, title: $"Library-{Guid.NewGuid():N}", libraryType: libraryType, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(
|
||||
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Albums.Add(album);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/> with one track, and returns the Id of that track.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the seeded library.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Other Artist");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Other Album");
|
||||
return await SeedTrackAsync(musicLibraryId, albumId, "Other Track");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the cover artwork of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="albumId">The Id of the album that owns the artwork.</param>
|
||||
/// <param name="fileName">The file name of the stored cover.</param>
|
||||
private async Task SeedAlbumCoverAsync(Guid albumId, string fileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album,
|
||||
ownerId: albumId,
|
||||
artworkType: ArtworkType.Cover,
|
||||
ordinal: 0,
|
||||
fileName: fileName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of the library identified by <paramref name="libraryId"/>, with one author.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the book belongs to.</param>
|
||||
/// <param name="title">The title of the book.</param>
|
||||
/// <param name="authorName">The display name of the author of the book.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string title, string authorName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid contributorId = Guid.NewGuid();
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(id: bookId, libraryId: libraryId, title: title, includeMetadata: false));
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId, displayName: authorName));
|
||||
dbContext.BookContributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId, role: MediaContributorRole.Author));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededMediaContributorIds.Add(contributorId);
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <returns>The Id of the seeded favorite.</returns>
|
||||
private async Task<Guid> SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid favoriteId = Guid.NewGuid();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
id: favoriteId,
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededFavoriteIds.Add(favoriteId);
|
||||
return favoriteId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Overrides the creation time of an already stored favorite, so the favoriting order of the test is deterministic.
|
||||
/// </summary>
|
||||
/// <param name="favoriteId">The Id of the favorite to update.</param>
|
||||
/// <param name="createdOnUtc">The creation time to store.</param>
|
||||
private async Task SetCreatedOnUtcAsync(Guid favoriteId, DateTime createdOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
await dbContext.Favorites
|
||||
.Where(favorite => favorite.Id == favoriteId)
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(favorite => favorite.CreatedOnUtc, createdOnUtc));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads an already stored favorite.
|
||||
/// </summary>
|
||||
/// <param name="favoriteId">The Id of the favorite to read.</param>
|
||||
/// <returns>The stored favorite.</returns>
|
||||
private async Task<FavoriteEntity> GetFavoriteAsync(Guid favoriteId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
return await dbContext.Favorites.AsNoTracking().FirstAsync(favorite => favorite.Id == favoriteId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||
List<Guid> albumIds = await dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)).Select(album => album.Id).ToListAsync();
|
||||
List<Guid> bookIds = await dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)).Select(book => book.Id).ToListAsync();
|
||||
dbContext.Favorites.RemoveRange(dbContext.Favorites.Where(favorite => _seededFavoriteIds.Contains(favorite.Id)));
|
||||
dbContext.MusicArtwork.RemoveRange(dbContext.MusicArtwork.Where(artwork => albumIds.Contains(artwork.OwnerId)));
|
||||
dbContext.BookContributors.RemoveRange(dbContext.BookContributors.Where(contributor => bookIds.Contains(contributor.BookId)));
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId)));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId)));
|
||||
dbContext.Books.RemoveRange(dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||
dbContext.MediaContributors.RemoveRange(dbContext.MediaContributors.Where(contributor => _seededMediaContributorIds.Contains(contributor.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RemoveFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededFavoriteIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RemoveFavoriteEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheFavoriteExists_ShouldDeleteTheCallersRowAndReturnOk()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/MusicTrack/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheFavoriteDoesNotExist_ShouldReturnOkAndChangeNothing()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid otherMediaItemId = Guid.NewGuid();
|
||||
Guid seededFavoriteId = await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, otherMediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/MusicTrack/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.Favorites.CountAsync(favorite => favorite.UserId == userId));
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.Id == seededFavoriteId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenAnotherUserFavoritedTheSameItem_ShouldRemoveOnlyTheCallersRow()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherFavoriteId = await SeedFavoriteAsync(otherUserId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/MusicTrack/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId));
|
||||
FavoriteEntity otherFavorite = await dbContext.Favorites.AsNoTracking().FirstAsync(favorite => favorite.Id == otherFavoriteId);
|
||||
Assert.Equal(otherUserId, otherFavorite.UserId);
|
||||
Assert.Equal(mediaItemId, otherFavorite.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/{nameof(FavoriteMediaKind.None)}/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "FavoriteMediaKindIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheMediaKindIsNotAName_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/NotAMediaKind/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "FavoriteMediaKindIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheMediaItemIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/favorites/MusicTrack/not-a-guid");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "FavoriteMediaItemIdCannotBeEmpty");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenBothRouteValuesAreInvalid_ShouldReturnBothValidationProblems()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/NotAMediaKind/{Guid.Empty}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "FavoriteMediaKindIsInvalid", "FavoriteMediaItemIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <returns>The Id of the seeded favorite.</returns>
|
||||
private async Task<Guid> SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid favoriteId = Guid.NewGuid();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
id: favoriteId,
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededFavoriteIds.Add(favoriteId);
|
||||
return favoriteId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a validation problem details document carrying the expected error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present, in order.</param>
|
||||
private static async Task AssertValidationProblemAsync(HttpResponseMessage response, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(422, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Equal(expectedErrorCodes, errors!["General.Validation"]);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Favorites.RemoveRange(dbContext.Favorites.Where(favorite => _seededFavoriteIds.Contains(favorite.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+530
@@ -0,0 +1,530 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylist;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Playlists.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private const string PATH = "/api/v1/users/me/playlists";
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly PlaylistEntityFixture _playlistEntityFixture = new();
|
||||
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededPlaylistIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPlaylistEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistExists_ShouldReturnItWithItsPageOfEntriesAndDensePositions()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Innuendo");
|
||||
Guid firstTrackId = await SeedTrackAsync(musicLibraryId, albumId, "Innuendo", 393);
|
||||
Guid secondTrackId = await SeedTrackAsync(musicLibraryId, albumId, "The Show Must Go On", 262);
|
||||
await SeedAlbumCoverAsync(albumId, "innuendo-cover.jpg");
|
||||
Guid deletedTrackId = Guid.NewGuid();
|
||||
Guid playlistId = await SeedPlaylistAsync(userId, "Evening listening");
|
||||
// The stored order keys are sparse, so the response must expose dense zero based display positions instead.
|
||||
await SeedPlaylistEntryAsync(playlistId, firstTrackId, 0);
|
||||
await SeedPlaylistEntryAsync(playlistId, secondTrackId, 1_000_000_000L);
|
||||
await SeedPlaylistEntryAsync(playlistId, deletedTrackId, 2_000_000_000L);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
|
||||
Assert.NotNull(playlist);
|
||||
Assert.Equal(playlistId, playlist!.Id);
|
||||
Assert.Equal("Evening listening", playlist.Name);
|
||||
Assert.Equal(PlaylistType.Music, playlist.Type);
|
||||
Assert.Equal(3, playlist.Entries.Count);
|
||||
Assert.Equal(1, playlist.Entries.CurrentPage);
|
||||
Assert.Equal(3, playlist.Entries.PerPage);
|
||||
Assert.Equal(1, playlist.Entries.NumberOfPages);
|
||||
Assert.Equal([0, 1, 2], playlist.Entries.Data.Select(entry => entry.Position));
|
||||
|
||||
PlaylistEntryResponse firstEntry = playlist.Entries.Data[0];
|
||||
Assert.Equal(firstTrackId, firstEntry.MediaItemId);
|
||||
Assert.Equal(PlaylistMediaItemType.MusicTrack, firstEntry.MediaItemType);
|
||||
Assert.Equal(musicLibraryId, firstEntry.LibraryId);
|
||||
Assert.Equal("Innuendo", firstEntry.MediaItemTitle);
|
||||
Assert.Equal(albumId, firstEntry.CollectionId);
|
||||
Assert.Equal("Innuendo", firstEntry.CollectionTitle);
|
||||
Assert.Equal(artistId, firstEntry.CreatorId);
|
||||
Assert.Equal("Queen", firstEntry.CreatorName);
|
||||
Assert.Equal(393, firstEntry.DurationInSeconds);
|
||||
Assert.Equal("innuendo-cover.jpg", firstEntry.CoverPath);
|
||||
|
||||
PlaylistEntryResponse deletedEntry = playlist.Entries.Data[2];
|
||||
Assert.Equal(deletedTrackId, deletedEntry.MediaItemId);
|
||||
Assert.Equal(Guid.Empty, deletedEntry.LibraryId);
|
||||
Assert.Equal(string.Empty, deletedEntry.MediaItemTitle);
|
||||
Assert.Equal(Guid.Empty, deletedEntry.CollectionId);
|
||||
Assert.Equal(Guid.Empty, deletedEntry.CreatorId);
|
||||
Assert.Equal(0, deletedEntry.DurationInSeconds);
|
||||
Assert.Null(deletedEntry.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistIsEmpty_ShouldReturnAnEmptyPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid playlistId = await SeedPlaylistAsync(userId, "Nothing yet");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
|
||||
Assert.NotNull(playlist);
|
||||
Assert.Empty(playlist!.Entries.Data);
|
||||
Assert.Equal(0, playlist.Entries.Count);
|
||||
Assert.Equal(1, playlist.Entries.CurrentPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenNoPaginationIsRequested_ShouldReturnEveryEntryInOnePage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid playlistId = await SeedPlaylistAsync(userId, "Every entry");
|
||||
for (int index = 0; index < 4; index++)
|
||||
await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), index * 1_000_000_000L);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
|
||||
Assert.NotNull(playlist);
|
||||
Assert.Equal(1, playlist!.Entries.CurrentPage);
|
||||
Assert.Equal(4, playlist.Entries.PerPage);
|
||||
Assert.Equal(4, playlist.Entries.Count);
|
||||
Assert.Equal(1, playlist.Entries.NumberOfPages);
|
||||
Assert.Equal([0, 1, 2, 3], playlist.Entries.Data.Select(entry => entry.Position));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenAPageIsRequested_ShouldReturnOnlyThatPageWithThePaginationMetadata()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid playlistId = await SeedPlaylistAsync(userId, "Paged playlist");
|
||||
for (int index = 0; index < 3; index++)
|
||||
await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), index * 1_000_000_000L);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}?currentPage=2&perPage=2");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
|
||||
Assert.NotNull(playlist);
|
||||
Assert.Equal(2, playlist!.Entries.CurrentPage);
|
||||
Assert.Equal(2, playlist.Entries.PerPage);
|
||||
Assert.Equal(3, playlist.Entries.Count);
|
||||
Assert.Equal(2, playlist.Entries.NumberOfPages);
|
||||
PlaylistEntryResponse entry = Assert.Single(playlist.Entries.Data);
|
||||
// The display position stays dense across pages, so the only entry of the second page is the third entry of the playlist.
|
||||
Assert.Equal(2, entry.Position);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{otherPlaylistId}");
|
||||
|
||||
// Assert
|
||||
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", $"{PATH}/{otherPlaylistId}");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
|
||||
|
||||
// Assert
|
||||
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", $"{PATH}/{playlistId}");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/not-a-guid");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, $"{PATH}/not-a-guid", "PlaylistIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistIdIsEmpty_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{Guid.Empty}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, $"{PATH}/{Guid.Empty}", "PlaylistIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the media library.</param>
|
||||
/// <returns>The Id of the seeded media library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId, userId: userId, title: $"Library-{Guid.NewGuid():N}", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(
|
||||
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Albums.Add(album);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <param name="durationInSeconds">The duration of the track in seconds.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title, int durationInSeconds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
track.DurationInSeconds = durationInSeconds;
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the cover artwork of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="albumId">The Id of the album that owns the artwork.</param>
|
||||
/// <param name="fileName">The file name of the stored cover.</param>
|
||||
private async Task SeedAlbumCoverAsync(Guid albumId, string fileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album,
|
||||
ownerId: albumId,
|
||||
artworkType: ArtworkType.Cover,
|
||||
ordinal: 0,
|
||||
fileName: fileName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the playlist.</param>
|
||||
/// <param name="name">The name of the playlist.</param>
|
||||
/// <returns>The Id of the seeded playlist.</returns>
|
||||
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
dbContext.Playlists.Add(_playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
name: name,
|
||||
type: PlaylistType.Music,
|
||||
entryCount: 0,
|
||||
version: 0,
|
||||
createdBy: userId));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededPlaylistIds.Add(playlistId);
|
||||
return playlistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an entry of the playlist identified by <paramref name="playlistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist the entry belongs to.</param>
|
||||
/// <param name="mediaItemId">The Id of the referenced media item.</param>
|
||||
/// <param name="position">The sparse order key of the entry.</param>
|
||||
private async Task SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: mediaItemId,
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
position: position));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a problem details document with the expected status, title and detail.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedStatus">The expected HTTP status.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private static async Task AssertProblemAsync(HttpResponseMessage response, HttpStatusCode expectedStatus, string expectedTitle, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(expectedStatus, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)expectedStatus, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a validation problem details document carrying the expected error code.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCode">The expected validation error code.</param>
|
||||
private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(422, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||
List<Guid> playlistIds = [.. _seededPlaylistIds];
|
||||
List<Guid> albumIds = await dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)).Select(album => album.Id).ToListAsync();
|
||||
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
|
||||
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
|
||||
dbContext.MusicArtwork.RemoveRange(dbContext.MusicArtwork.Where(artwork => albumIds.Contains(artwork.OwnerId)));
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId)));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId)));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.AddFavorite;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
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.Favorites.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-add-favorite";
|
||||
private const string UPSTREAM_ENDPOINT = "users/me/favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FavoriteDtoFixture _favoriteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddFavoriteEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheFavoriteAndReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
FavoriteDto expectedFavorite = _favoriteDtoFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(UPSTREAM_ENDPOINT, expectedFavorite);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(FavoriteMediaKind.MusicTrack, mediaItemId, 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(expectedFavorite.Id, data.GetProperty("id").GetGuid());
|
||||
Assert.Equal(nameof(FavoriteMediaKind.MusicTrack), data.GetProperty("mediaKind").GetString());
|
||||
Assert.Equal(mediaItemId, data.GetProperty("mediaItemId").GetGuid());
|
||||
Assert.Equal(expectedFavorite.FavoritedOnUtc, data.GetProperty("favoritedOnUtc").GetDateTime());
|
||||
List<(string Endpoint, object? Data)> addRequests = GetAddRequests();
|
||||
(string Endpoint, object? Data) addRequestCall = Assert.Single(addRequests);
|
||||
Assert.Equal(UPSTREAM_ENDPOINT, addRequestCall.Endpoint);
|
||||
AddFavoriteRequest forwardedPayload = Assert.IsType<AddFavoriteRequest>(addRequestCall.Data);
|
||||
Assert.Equal(FavoriteMediaKind.MusicTrack, forwardedPayload.MediaKind);
|
||||
Assert.Equal(mediaItemId, forwardedPayload.MediaItemId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the add favorite requests that were sent upstream, excluding the login request performed to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream add favorite requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetAddRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PostRequests
|
||||
.Where(postRequest => postRequest.Endpoint == UPSTREAM_ENDPOINT)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the add favorite request for the specified media item.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The kind of the media item to favorite.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to favorite.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured add favorite request.</returns>
|
||||
private static HttpRequestMessage CreateAddRequest(FavoriteMediaKind mediaKind, Guid mediaItemId, string antiforgeryToken)
|
||||
{
|
||||
string payload = $"{{\"mediaKind\":\"{mediaKind}\",\"mediaItemId\":\"{mediaItemId}\"}}";
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, WEB_ROUTE)
|
||||
{
|
||||
Content = new StringContent(payload, Encoding.UTF8, "application/json")
|
||||
};
|
||||
// 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"));
|
||||
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);
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFavoriteStatusEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-get-favorite-status";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FavoriteStatusDtoFixture _favoriteStatusDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetFavoriteStatusEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenCalledWithMediaKindAndIds_ShouldForwardThemAndSurfaceTheFavoritedIds()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
List<Guid> mediaItemIds = [Guid.NewGuid(), Guid.NewGuid()];
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/status?mediaKind=MusicTrack&mediaItemIds={mediaItemIds[0]}&mediaItemIds={mediaItemIds[1]}";
|
||||
FavoriteStatusDto expectedStatus = _favoriteStatusDtoFixture.Create(favoritedMediaItemIds: [mediaItemIds[1]]);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedUpstreamEndpoint, expectedStatus);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(
|
||||
$"{WEB_ROUTE}?mediaKind=MusicTrack&mediaItemIds={mediaItemIds[0]}&mediaItemIds={mediaItemIds[1]}");
|
||||
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<Guid> favoritedIds = [.. json.RootElement.GetProperty("data").GetProperty("favoritedMediaItemIds").EnumerateArray().Select(element => element.GetGuid())];
|
||||
Assert.Equal(expectedStatus.FavoritedMediaItemIds, favoritedIds);
|
||||
Assert.Equal([expectedUpstreamEndpoint], GetFavoriteStatusEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenMediaKindAndIdsAreOmitted_ShouldForwardTheBareStatusRoute()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_ENDPOINT = "users/me/favorites/status";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_ENDPOINT, _favoriteStatusDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([EXPECTED_UPSTREAM_ENDPOINT], GetFavoriteStatusEndpointCalls());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorite status endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream favorite status endpoints that were called.</returns>
|
||||
private List<string> GetFavoriteStatusEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites/status", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Favorites.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFavoritesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-get-favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedDtoFixture<FavoriteItemDto> _paginatedDtoFixture = new();
|
||||
private readonly FavoriteItemDtoFixture _favoriteItemDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetFavoritesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenCalledByAuthenticatedUser_ShouldSurfaceThePaginatedFavoritesUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
FavoriteItemDto expectedItem = _favoriteItemDtoFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicTrack,
|
||||
isAvailable: true,
|
||||
title: "Time",
|
||||
collectionTitle: "The Dark Side of the Moon",
|
||||
creatorName: "Pink Floyd",
|
||||
coverPath: "covers/dark-side-of-the-moon.jpg");
|
||||
PaginatedDto<FavoriteItemDto> expectedPage = _paginatedDtoFixture.Create(
|
||||
data: [expectedItem],
|
||||
currentPage: 1,
|
||||
perPage: 200,
|
||||
count: 1,
|
||||
numberOfPages: 1);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("users/me/favorites?currentPage=1&perPage=200", expectedPage);
|
||||
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);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(200, data.GetProperty("perPage").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("count").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("numberOfPages").GetInt32());
|
||||
JsonElement item = Assert.Single(data.GetProperty("data").EnumerateArray());
|
||||
Assert.Equal(nameof(FavoriteMediaKind.MusicTrack), item.GetProperty("mediaKind").GetString());
|
||||
Assert.Equal(expectedItem.MediaItemId, item.GetProperty("mediaItemId").GetGuid());
|
||||
Assert.True(item.GetProperty("isAvailable").GetBoolean());
|
||||
Assert.Equal(expectedItem.LibraryId, item.GetProperty("libraryId").GetGuid());
|
||||
Assert.Equal(expectedItem.Title, item.GetProperty("title").GetString());
|
||||
Assert.Equal(expectedItem.CollectionId, item.GetProperty("collectionId").GetGuid());
|
||||
Assert.Equal(expectedItem.CollectionTitle, item.GetProperty("collectionTitle").GetString());
|
||||
Assert.Equal(expectedItem.CreatorId, item.GetProperty("creatorId").GetGuid());
|
||||
Assert.Equal(expectedItem.CreatorName, item.GetProperty("creatorName").GetString());
|
||||
Assert.Equal(expectedItem.CoverPath, item.GetProperty("coverPath").GetString());
|
||||
Assert.Equal(["users/me/favorites?currentPage=1&perPage=200"], GetFavoritesEndpointCalls());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("", "users/me/favorites?currentPage=1&perPage=200")] // neither the page nor the size is supplied
|
||||
[InlineData("?currentPage=3", "users/me/favorites?currentPage=3&perPage=200")] // only the page is supplied
|
||||
[InlineData("?perPage=25", "users/me/favorites?currentPage=1&perPage=25")] // only the size is supplied
|
||||
[InlineData("?currentPage=2&perPage=50", "users/me/favorites?currentPage=2&perPage=50")] // both the page and the size are supplied
|
||||
public async Task GetFavorites_WhenCalledWithPagination_ShouldForwardTheDocumentedUpstreamUrl(string queryString, string expectedUpstreamEndpoint)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedUpstreamEndpoint, _paginatedDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}{queryString}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedUpstreamEndpoint], GetFavoritesEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenMediaKindIsSupplied_ShouldAppendItToTheUpstreamUrl()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_ENDPOINT = "users/me/favorites?currentPage=1&perPage=200&mediaKind=MusicTrack";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_ENDPOINT, _paginatedDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([EXPECTED_UPSTREAM_ENDPOINT], GetFavoritesEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenMediaItemIsUnavailable_ShouldPassTheEmptyDisplayDataThroughUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
FavoriteItemDto unavailableItem = _favoriteItemDtoFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.Book,
|
||||
isAvailable: false,
|
||||
libraryId: Guid.Empty,
|
||||
title: string.Empty,
|
||||
collectionId: Guid.Empty,
|
||||
collectionTitle: string.Empty,
|
||||
creatorId: Guid.Empty,
|
||||
creatorName: string.Empty,
|
||||
includeCoverPath: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(
|
||||
"users/me/favorites?currentPage=1&perPage=200",
|
||||
_paginatedDtoFixture.Create(data: [unavailableItem], currentPage: 1, perPage: 200, count: 1, numberOfPages: 1));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
JsonElement item = Assert.Single(json.RootElement.GetProperty("data").GetProperty("data").EnumerateArray());
|
||||
Assert.False(item.GetProperty("isAvailable").GetBoolean());
|
||||
Assert.Equal(Guid.Empty, item.GetProperty("libraryId").GetGuid());
|
||||
Assert.Equal(string.Empty, item.GetProperty("title").GetString());
|
||||
Assert.Equal(Guid.Empty, item.GetProperty("collectionId").GetGuid());
|
||||
Assert.Equal(string.Empty, item.GetProperty("collectionTitle").GetString());
|
||||
Assert.Equal(Guid.Empty, item.GetProperty("creatorId").GetGuid());
|
||||
Assert.Equal(string.Empty, item.GetProperty("creatorName").GetString());
|
||||
Assert.Equal(JsonValueKind.Null, item.GetProperty("coverPath").ValueKind);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorites endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream favorites endpoints that were called.</returns>
|
||||
private List<string> GetFavoritesEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.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.Favorites.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="FavoritesIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoritesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FavoritesIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public FavoritesIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FavoritesIndexView_WhenCalledByAuthenticatedUser_ShouldRenderTheFavoritesPage()
|
||||
{
|
||||
// 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("favorites-container", content, StringComparison.Ordinal);
|
||||
Assert.Contains("favorites-kind-filter", content, StringComparison.Ordinal);
|
||||
Assert.Contains("no-favorites", content, StringComparison.Ordinal);
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FavoritesIndexView_WhenCalledByAuthenticatedUser_ShouldRenderTheAntiforgeryTokenAndTheLocalizedStrings()
|
||||
{
|
||||
// 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("__RequestVerificationToken", content, StringComparison.Ordinal);
|
||||
Assert.Contains("Favorites", content, StringComparison.Ordinal);
|
||||
Assert.Contains("You have no favorites yet.", content, StringComparison.Ordinal);
|
||||
Assert.Contains("Load more", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
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.Favorites.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RemoveFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteEndpointTests : 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="RemoveFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public RemoveFavoriteEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheNormalizedDeleteAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/MusicTrack/{mediaItemId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(nameof(FavoriteMediaKind.MusicTrack), mediaItemId.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.Equal([expectedUpstreamEndpoint], GetRemoveEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenMediaKindAndIdAreCasedDifferently_ShouldForwardTheCanonicalValuesOnly()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB");
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/MusicTrack/{mediaItemId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest("musictrack", mediaItemId.ToString().ToUpperInvariant(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> removeEndpoints = GetRemoveEndpointCalls();
|
||||
Assert.Equal([expectedUpstreamEndpoint], removeEndpoints);
|
||||
Assert.DoesNotContain(mediaItemId.ToString().ToUpperInvariant(), string.Join(",", removeEndpoints), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenRouteValuesAreCrafted_ShouldForwardTheSanitizedPlaceholders()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/Invalid/{ZERO_GUID}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest("notamediakind", "not-a-guid", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> removeEndpoints = GetRemoveEndpointCalls();
|
||||
Assert.Equal([expectedUpstreamEndpoint], removeEndpoints);
|
||||
Assert.DoesNotContain("notamediakind", string.Join(",", removeEndpoints), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", removeEndpoints), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the remove favorite endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream remove favorite endpoints that were called.</returns>
|
||||
private List<string> GetRemoveEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the remove favorite request for the specified route values.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The value of the media kind route segment.</param>
|
||||
/// <param name="mediaItemId">The value of the media item identifier route segment.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured remove favorite request.</returns>
|
||||
private static HttpRequestMessage CreateRemoveRequest(string mediaKind, string mediaItemId, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage removeRequest = new(HttpMethod.Delete, $"/en-us/favorites/{Uri.EscapeDataString(mediaKind)}/{Uri.EscapeDataString(mediaItemId)}/api-remove-favorite")
|
||||
{
|
||||
// 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"));
|
||||
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);
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylist;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaylistDtoFixture _playlistDtoFixture = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<PlaylistEntryDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPlaylistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenCalledByAuthenticatedUser_ShouldForwardTheDocumentedUpstreamUrlAndSurfaceThePlaylist()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
PlaylistEntryDto expectedEntry = _playlistEntryDtoFixture.Create(
|
||||
position: 0,
|
||||
mediaItemTitle: "First track",
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack);
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create(
|
||||
id: playlistId,
|
||||
name: "Evening listening",
|
||||
description: "Quiet tracks for the end of the day.",
|
||||
entries: _paginatedDtoFixture.Create(
|
||||
data: [expectedEntry],
|
||||
currentPage: 1,
|
||||
perPage: 200,
|
||||
count: 1,
|
||||
numberOfPages: 1),
|
||||
createdOnUtc: new DateTime(2026, 10, 19, 18, 0, 0, DateTimeKind.Utc),
|
||||
updatedOnUtc: new DateTime(2026, 10, 19, 19, 30, 0, DateTimeKind.Utc));
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedPlaylist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{playlistId}/api-get-playlist");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType!.MediaType);
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(content);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = jsonDocument.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());
|
||||
Assert.Equal(expectedPlaylist.CreatedOnUtc, data.GetProperty("createdOnUtc").GetDateTime());
|
||||
Assert.Equal(expectedPlaylist.UpdatedOnUtc, data.GetProperty("updatedOnUtc").GetDateTime());
|
||||
JsonElement entries = data.GetProperty("entries");
|
||||
Assert.Equal(expectedPlaylist.Entries.CurrentPage, entries.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(expectedPlaylist.Entries.PerPage, entries.GetProperty("perPage").GetInt32());
|
||||
Assert.Equal(expectedPlaylist.Entries.Count, entries.GetProperty("count").GetInt32());
|
||||
Assert.Equal(expectedPlaylist.Entries.NumberOfPages, entries.GetProperty("numberOfPages").GetInt32());
|
||||
JsonElement entry = Assert.Single(entries.GetProperty("data").EnumerateArray());
|
||||
Assert.Equal(expectedEntry.Id, entry.GetProperty("id").GetGuid());
|
||||
Assert.Equal(expectedEntry.MediaItemTitle, entry.GetProperty("mediaItemTitle").GetString());
|
||||
Assert.Equal([expectedEndpoint], GetPlaylistEndpointCalls());
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenPageParametersAreProvided_ShouldForwardThemToTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=2&perPage=50";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _playlistDtoFixture.Create(id: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{playlistId}/api-get-playlist?currentPage=2&perPage=50");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedEndpoint], GetPlaylistEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenPlaylistIdIsAnUppercaseGuid_ShouldForwardItInLowercase()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB");
|
||||
string uppercasePlaylistId = playlistId.ToString().ToUpperInvariant();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _playlistDtoFixture.Create(id: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{uppercasePlaylistId}/api-get-playlist");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.DoesNotContain(uppercasePlaylistId, string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _playlistDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/item/not-a-guid/api-get-playlist");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <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.StartsWith("users/me/playlists/", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.Item;
|
||||
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.Item;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddPlaylistViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddPlaylistViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/playlists/item";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddPlaylistViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistView_WhenCalledByAuthenticatedUser_ShouldRenderTheCreatePlaylistPage()
|
||||
{
|
||||
// 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("playlist-details-form", content, StringComparison.Ordinal);
|
||||
Assert.Contains("playlist-title", content, StringComparison.Ordinal);
|
||||
Assert.Contains("Create playlist", content, StringComparison.Ordinal);
|
||||
Assert.Contains("__RequestVerificationToken", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/me/playlists", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistView_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);
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.Item;
|
||||
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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.Item;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="PlaylistItemViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistItemViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaylistDtoFixture _playlistDtoFixture = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<PlaylistEntryDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaylistItemViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public PlaylistItemViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistItemView_WhenCalledByAuthenticatedUser_ShouldForwardTheDocumentedUpstreamUrlAndRenderThePlaylist()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
PlaylistEntryDto expectedEntry = _playlistEntryDtoFixture.Create(
|
||||
position: 0,
|
||||
mediaItemTitle: "First track",
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack);
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create(
|
||||
id: playlistId,
|
||||
name: "Evening listening",
|
||||
description: "Quiet tracks for the end of the day.",
|
||||
entries: _paginatedDtoFixture.Create(
|
||||
data: [expectedEntry],
|
||||
currentPage: 1,
|
||||
perPage: 200,
|
||||
count: 1,
|
||||
numberOfPages: 1));
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedPlaylist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{playlistId}");
|
||||
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("playlist-details-form", content, StringComparison.Ordinal);
|
||||
Assert.Contains(expectedPlaylist.Name, content, StringComparison.Ordinal);
|
||||
Assert.Contains(expectedPlaylist.Description!, content, StringComparison.Ordinal);
|
||||
Assert.Contains(expectedEntry.MediaItemTitle, content, StringComparison.Ordinal);
|
||||
Assert.Equal([expectedEndpoint], GetPlaylistEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistItemView_WhenCalledByAuthenticatedUser_ShouldReturnANonStorablePage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _playlistDtoFixture.Create(id: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{playlistId}");
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistItemView_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _playlistDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/item/not-a-guid");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <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.StartsWith("users/me/playlists/", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user