mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 15:11:10 +00:00
Adds the music library album test suite
This commit is contained in:
1 parent
ffe79221fe
commit
5d3e430dd1
57 files changed
+16761
-24
No files matched your search
+735
@@ -0,0 +1,735 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AlbumRepository"/> class, exercising it against a real SQLite database.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumRepositoryTests
|
||||
{
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly AlbumContributorEntityFixture _albumContributorEntityFixture = new();
|
||||
private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new();
|
||||
private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new();
|
||||
private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new();
|
||||
private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenCalledWithAValidAlbum_ShouldPersistTheAlbumAndItsAggregate()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = BuildFullAlbum(artist.Id, libraryId, "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
AlbumEntity? storedAlbum = await context.Albums
|
||||
.AsNoTracking()
|
||||
.Include(candidate => candidate.Ratings)
|
||||
.Include(candidate => candidate.Tags)
|
||||
.Include(candidate => candidate.Genres)
|
||||
.Include(candidate => candidate.Contributors)
|
||||
.Include(candidate => candidate.Tracks)
|
||||
.ThenInclude(candidate => candidate.Moods)
|
||||
.AsSplitQuery()
|
||||
.FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
|
||||
Assert.NotNull(storedAlbum);
|
||||
Assert.Equal("A Night at the Opera", storedAlbum!.Title);
|
||||
Assert.Single(storedAlbum.Ratings);
|
||||
Assert.Equal(2, storedAlbum.Tags.Count);
|
||||
Assert.Equal(2, storedAlbum.Genres.Count);
|
||||
Assert.Single(storedAlbum.Contributors);
|
||||
TrackEntity storedTrack = Assert.Single(storedAlbum.Tracks);
|
||||
Assert.Equal(2, storedTrack.Moods.Count);
|
||||
// Each tag and genre of the aggregate is stored exactly once.
|
||||
Assert.Single(await context.Set<TagEntity>().Where(tag => tag.Name == "album-tag-1").ToListAsync());
|
||||
Assert.Single(await context.Set<GenreEntity>().Where(genre => genre.Name == "album-genre-1").ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAlbumWithTheSameIdAlreadyExists_ShouldReturnAlbumAlreadyExists()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-id-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity existingAlbum = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(existingAlbum);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: existingAlbum.Id, artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenTwoTracksOfTheSameRequestShareAPath_ShouldReturnTrackAlreadyExists()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-duprequest-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
|
||||
album.Tracks =
|
||||
[
|
||||
_trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false),
|
||||
_trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false)
|
||||
];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenATrackPathIsAlreadyStoredInTheLibrary_ShouldReturnTrackAlreadyExists()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-storedpath-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity existingAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Existing");
|
||||
context.Tracks.Add(_trackEntityFixture.Create(
|
||||
albumId: existingAlbum.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldPersistTheAlbum()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-otherlibrary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid firstLibraryId = Guid.NewGuid();
|
||||
ArtistEntity firstArtist = await SeedArtistAsync(context, firstLibraryId);
|
||||
AlbumEntity firstAlbum = await SeedAlbumAsync(context, firstLibraryId, firstArtist.Id, "First");
|
||||
context.Tracks.Add(_trackEntityFixture.Create(
|
||||
albumId: firstAlbum.Id, libraryId: firstLibraryId, path: "/music/queen/we-are-the-champions.flac", includeMetadata: false));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
Guid secondLibraryId = Guid.NewGuid();
|
||||
ArtistEntity secondArtist = await SeedArtistAsync(context, secondLibraryId);
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: secondArtist.Id, libraryId: secondLibraryId, includeTracks: false, includeMetadata: false);
|
||||
album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: secondLibraryId, path: "/music/queen/we-are-the-champions.flac", includeMetadata: false)];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
|
||||
Assert.NotNull(storedAlbum);
|
||||
Assert.Equal(secondLibraryId, storedAlbum!.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenTagsAndGenresAlreadyExistByName_ShouldReuseTheStoredRows()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-reuse-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
context.Set<TagEntity>().Add(_tagEntityFixture.Create(name: "ExistingTag"));
|
||||
context.Set<GenreEntity>().Add(_genreEntityFixture.Create(name: "ExistingGenre"));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
album.Tags = [_tagEntityFixture.Create(name: "ExistingTag")];
|
||||
album.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")];
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, includeMetadata: false);
|
||||
track.Tags = [_tagEntityFixture.Create(name: "ExistingTag")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")];
|
||||
album.Tracks = [track];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
// The shared rows are reused instead of being duplicated.
|
||||
Assert.Single(await context.Set<TagEntity>().Where(tag => tag.Name == "ExistingTag").ToListAsync());
|
||||
Assert.Single(await context.Set<GenreEntity>().Where(genre => genre.Name == "ExistingGenre").ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenANewTagAndGenreNameIsSharedBetweenTheAlbumAndItsTracks_ShouldPersistItOnce()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-shared-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
|
||||
album.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")];
|
||||
album.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")];
|
||||
track.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")];
|
||||
album.Tracks = [track];
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(album, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
// The name shared by the album and its tracks is persisted exactly once.
|
||||
Assert.Single(await context.Set<TagEntity>().Where(tag => tag.Name == "SharedNewTag").ToListAsync());
|
||||
Assert.Single(await context.Set<GenreEntity>().Where(genre => genre.Name == "SharedNewGenre").ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeAnyAuditColumn()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
Guid userId = Guid.NewGuid();
|
||||
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = await SeedFullAlbumAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
Guid contributorId = album.Contributors[0].Id;
|
||||
DateTime contributorCreatedOnUtc = album.Contributors[0].CreatedOnUtc;
|
||||
// Detach the seeded graph, so that the update must load the tracked album through its include chain instead of returning the already populated seeded instance.
|
||||
context.ChangeTracker.Clear();
|
||||
AlbumEntity incoming = await LoadDetachedAlbumAsync(context, album.Id);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
|
||||
Assert.NotNull(storedAlbum);
|
||||
Assert.Null(storedAlbum!.UpdatedOnUtc);
|
||||
AlbumContributorEntity storedContributor = Assert.Single(storedAlbum.Contributors);
|
||||
Assert.Equal(contributorId, storedContributor.Id);
|
||||
Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc);
|
||||
Assert.Single(await context.Set<TagEntity>().Where(tag => tag.Name == "album-tag-1").ToListAsync());
|
||||
Assert.Single(await context.Set<GenreEntity>().Where(genre => genre.Name == "album-genre-1").ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenOnlyTheScalarValuesChanged_ShouldStampTheAlbumAndPreserveArtistAndLibrary()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-scalars-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
Guid userId = Guid.NewGuid();
|
||||
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = await SeedFullAlbumAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
AlbumEntity incoming = await LoadDetachedAlbumAsync(context, album.Id);
|
||||
incoming.Title = "A Night at the Opera (Remastered)";
|
||||
incoming.ArtistId = Guid.NewGuid();
|
||||
incoming.LibraryId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
|
||||
Assert.NotNull(storedAlbum);
|
||||
Assert.Equal("A Night at the Opera (Remastered)", storedAlbum!.Title);
|
||||
// The stored identity is preserved and only the actual edit is stamped.
|
||||
Assert.Equal(artist.Id, storedAlbum.ArtistId);
|
||||
Assert.Equal(libraryId, storedAlbum.LibraryId);
|
||||
Assert.Equal(utcNow, storedAlbum.UpdatedOnUtc);
|
||||
Assert.Equal(userId, storedAlbum.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenRatingsAndContributorsChange_ShouldReconcileThem()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-owned-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
Guid keptMediaContributorId = Guid.NewGuid();
|
||||
Guid removedMediaContributorId = Guid.NewGuid();
|
||||
Guid addedMediaContributorId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
album.Ratings =
|
||||
[
|
||||
_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
|
||||
_audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10),
|
||||
_audioRatingEntityFixture.Create(value: 2, maxValue: 5, source: AudioRatingSource.LastFm, voteCount: 20)
|
||||
];
|
||||
album.Contributors =
|
||||
[
|
||||
_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer),
|
||||
_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Composer)
|
||||
];
|
||||
context.Albums.Add(album);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
AlbumEntity incoming = await LoadDetachedAlbumAsync(context, album.Id);
|
||||
incoming.Ratings =
|
||||
[
|
||||
_audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
|
||||
_audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10),
|
||||
_audioRatingEntityFixture.Create(value: 1, maxValue: 5, source: AudioRatingSource.Discogs, voteCount: 5)
|
||||
];
|
||||
incoming.Contributors =
|
||||
[
|
||||
_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer),
|
||||
_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: addedMediaContributorId, role: MediaContributorRole.Vocals)
|
||||
];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity? storedAlbum = await context.Albums
|
||||
.AsNoTracking()
|
||||
.Include(candidate => candidate.Ratings)
|
||||
.Include(candidate => candidate.Contributors)
|
||||
.FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
|
||||
Assert.NotNull(storedAlbum);
|
||||
Assert.Equal(3, storedAlbum!.Ratings.Count);
|
||||
Assert.Contains(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.MusicBrainz && rating.Value == 3M);
|
||||
Assert.Contains(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.User && rating.Value == 5M);
|
||||
Assert.Contains(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.Discogs && rating.Value == 1M);
|
||||
Assert.DoesNotContain(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.LastFm);
|
||||
Assert.Equal(2, storedAlbum.Contributors.Count);
|
||||
Assert.DoesNotContain(storedAlbum.Contributors, contributor => contributor.MediaContributorId == removedMediaContributorId);
|
||||
Assert.Contains(storedAlbum.Contributors, contributor => contributor.MediaContributorId == addedMediaContributorId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenAlbumExists_ShouldIncludeTheNavigationProperties()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = await SeedFullAlbumAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
Result<AlbumEntity?> result = await sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumEntity retrievedAlbum = result.Value!;
|
||||
Assert.NotNull(retrievedAlbum.Artist);
|
||||
Assert.Equal(artist.Id, retrievedAlbum.Artist!.Id);
|
||||
Assert.Single(retrievedAlbum.Ratings);
|
||||
Assert.Equal(2, retrievedAlbum.Tags.Count);
|
||||
Assert.Equal(2, retrievedAlbum.Genres.Count);
|
||||
Assert.Single(retrievedAlbum.Contributors);
|
||||
TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks);
|
||||
Assert.Single(retrievedTrack.Ratings);
|
||||
Assert.Equal(2, retrievedTrack.Genres.Count);
|
||||
Assert.Equal(2, retrievedTrack.Moods.Count);
|
||||
Assert.Equal(2, retrievedTrack.Isrcs.Count);
|
||||
Assert.Single(retrievedTrack.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnAnUntrackedAlbum()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(album);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<AlbumEntity?> result = await sut.GetByIdAsync(
|
||||
album.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(context.ChangeTracker.Entries<AlbumEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumsLiteByArtistIdAsync_WhenCalled_ShouldNotTrackTheEntities()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(album);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<AlbumLiteRow>> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value.Data);
|
||||
Assert.Empty(context.ChangeTracker.Entries<AlbumEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByArtistIdAsync_WhenCalled_ShouldReturnTheArtistAlbumsOrderedWithTheirCollections()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyartist-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity betaAlbum = await SeedFullAlbumAsync(context, libraryId, artist.Id, "Beta");
|
||||
AlbumEntity alphaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Alpha");
|
||||
ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(
|
||||
artistId: otherArtist.Id, libraryId: libraryId, title: "Gamma", includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(albumOfAnotherArtist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<AlbumEntity>> result = await sut.GetByArtistIdAsync(artist.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal([alphaAlbum.Id, betaAlbum.Id], result.Value.Select(album => album.Id));
|
||||
AlbumEntity retrievedAlbum = result.Value.Single(album => album.Id == betaAlbum.Id);
|
||||
Assert.Single(retrievedAlbum.Ratings);
|
||||
Assert.Equal(2, retrievedAlbum.Tags.Count);
|
||||
Assert.Equal(2, retrievedAlbum.Genres.Count);
|
||||
Assert.Single(retrievedAlbum.Contributors);
|
||||
TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks);
|
||||
Assert.Equal(2, retrievedTrack.Moods.Count);
|
||||
Assert.Single(retrievedTrack.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumsLiteByArtistIdAsync_WhenPaginationDataIsNull_ShouldReturnAllArtistAlbumsOrdered()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-null-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity betaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Beta");
|
||||
AlbumEntity alphaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Alpha");
|
||||
ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId);
|
||||
AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(
|
||||
artistId: otherArtist.Id, libraryId: libraryId, title: "Gamma", includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(albumOfAnotherArtist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<AlbumLiteRow>> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal([alphaAlbum.Id, betaAlbum.Id], result.Value.Data.Select(row => row.Id));
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Equal(1, result.Value.CurrentPage);
|
||||
Assert.Equal(2, result.Value.PerPage);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, 2, 1, 2)] // The first page is fully returned.
|
||||
[InlineData(2, 2, 2, 2)] // A middle page is fully returned.
|
||||
[InlineData(3, 2, 3, 1)] // The last page is partially returned.
|
||||
[InlineData(99, 2, 3, 1)] // A page beyond the last one is clamped to the last page.
|
||||
public async Task GetAlbumsLiteByArtistIdAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage(int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount)
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-page-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
AlbumRepository sut = CreateAlbumRepository(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
|
||||
List<AlbumEntity> albums = _albumEntityFixture.CreateMany(5);
|
||||
for (int index = 0; index < albums.Count; index++)
|
||||
{
|
||||
albums[index].ArtistId = artist.Id;
|
||||
albums[index].LibraryId = libraryId;
|
||||
albums[index].Title = $"Album {index}";
|
||||
albums[index].Tracks = [];
|
||||
}
|
||||
context.Albums.AddRange(albums);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<AlbumLiteRow>> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, paginationData, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(5, result.Value.Count);
|
||||
Assert.Equal(3, result.Value.NumberOfPages);
|
||||
Assert.Equal(expectedCurrentPage, result.Value.CurrentPage);
|
||||
Assert.Equal(perPage, result.Value.PerPage);
|
||||
Assert.Equal(expectedRowCount, result.Value.Data.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an album repository backed by the provided context, wiring the real track repository.
|
||||
/// </summary>
|
||||
/// <param name="context">The context the repository operates on.</param>
|
||||
/// <returns>The created repository.</returns>
|
||||
private static AlbumRepository CreateAlbumRepository(LuminaDbContext context)
|
||||
{
|
||||
return new AlbumRepository(context, new TrackRepository(context));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist with no albums or contributors, so that the required foreign key of an album is satisfied.
|
||||
/// </summary>
|
||||
/// <param name="context">The context the artist is persisted through.</param>
|
||||
/// <param name="libraryId">The Id of the library that owns the artist.</param>
|
||||
/// <returns>The persisted artist.</returns>
|
||||
private async Task<ArtistEntity> SeedArtistAsync(LuminaDbContext context, Guid libraryId)
|
||||
{
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
|
||||
context.Artists.Add(artist);
|
||||
await context.SaveChangesAsync();
|
||||
return artist;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album that belongs to the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="context">The context the album is persisted through.</param>
|
||||
/// <param name="libraryId">The Id of the library that owns the album.</param>
|
||||
/// <param name="artistId">The Id of the artist that owns the album.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The persisted album.</returns>
|
||||
private async Task<AlbumEntity> SeedAlbumAsync(LuminaDbContext context, Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, title: title, includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(album);
|
||||
await context.SaveChangesAsync();
|
||||
return album;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album with one track, including every related collection deterministically.
|
||||
/// </summary>
|
||||
/// <param name="context">The context the album is persisted through.</param>
|
||||
/// <param name="libraryId">The Id of the library that owns the album.</param>
|
||||
/// <param name="artistId">The Id of the artist that owns the album.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The persisted album.</returns>
|
||||
private async Task<AlbumEntity> SeedFullAlbumAsync(LuminaDbContext context, Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
AlbumEntity album = BuildFullAlbum(artistId, libraryId, title);
|
||||
context.Albums.Add(album);
|
||||
await context.SaveChangesAsync();
|
||||
return album;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds an album with one track, including every related collection deterministically, without persisting it.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The Id of the artist that owns the album.</param>
|
||||
/// <param name="libraryId">The Id of the library that owns the album.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The created album.</returns>
|
||||
private AlbumEntity BuildFullAlbum(Guid artistId, Guid libraryId, string title)
|
||||
{
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, title: title, includeTracks: false, includeMetadata: false);
|
||||
album.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
|
||||
album.Tags = [_tagEntityFixture.Create(name: "album-tag-1"), _tagEntityFixture.Create(name: "album-tag-2")];
|
||||
album.Genres = [_genreEntityFixture.Create(name: "album-genre-1"), _genreEntityFixture.Create(name: "album-genre-2")];
|
||||
album.Contributors = [_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)];
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
|
||||
track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.User, voteCount: 10)];
|
||||
track.Tags = [_tagEntityFixture.Create(name: "track-tag-1"), _tagEntityFixture.Create(name: "track-tag-2")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "track-genre-1"), _genreEntityFixture.Create(name: "track-genre-2")];
|
||||
track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")];
|
||||
track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")];
|
||||
track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
|
||||
album.Tracks = [track];
|
||||
return album;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads a detached copy of a stored album with the whole aggregate, so that it can be handed to the repository as the desired state of an edit.
|
||||
/// </summary>
|
||||
/// <param name="context">The context that tracks the stored album.</param>
|
||||
/// <param name="albumId">The Id of the album to load.</param>
|
||||
/// <returns>The detached copy of the album.</returns>
|
||||
private static async Task<AlbumEntity> LoadDetachedAlbumAsync(LuminaDbContext context, Guid albumId)
|
||||
{
|
||||
return await context.Albums
|
||||
.AsNoTracking()
|
||||
.Include(album => album.Ratings)
|
||||
.Include(album => album.Tags)
|
||||
.Include(album => album.Genres)
|
||||
.Include(album => album.Contributors)
|
||||
.Include(album => album.Tracks)
|
||||
.ThenInclude(track => track.Ratings)
|
||||
.Include(album => album.Tracks)
|
||||
.ThenInclude(track => track.Genres)
|
||||
.Include(album => album.Tracks)
|
||||
.ThenInclude(track => track.Tags)
|
||||
.Include(album => album.Tracks)
|
||||
.ThenInclude(track => track.Moods)
|
||||
.Include(album => album.Tracks)
|
||||
.ThenInclude(track => track.Isrcs)
|
||||
.Include(album => album.Tracks)
|
||||
.ThenInclude(track => track.Contributors)
|
||||
.AsSplitQuery()
|
||||
.FirstAsync(album => album.Id == albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
|
||||
/// </summary>
|
||||
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
|
||||
/// <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>The created context.</returns>
|
||||
private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow)
|
||||
{
|
||||
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
|
||||
currentUserService.UserId.Returns(userId);
|
||||
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
dateTimeProvider.UtcNow.Returns(utcNow);
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseSqlite(anchorConnection.ConnectionString)
|
||||
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
|
||||
.Options);
|
||||
context.Database.EnsureCreated();
|
||||
return context;
|
||||
}
|
||||
}
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddAlbumEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenCalledWithValidData_ShouldAddAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(
|
||||
metadata: _albumMetadataDtoFixture.Create(title: "News of the World"),
|
||||
contributors: [],
|
||||
ratings: [],
|
||||
tracks: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AlbumResponse? albumResponse = JsonSerializer.Deserialize<AlbumResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(albumResponse);
|
||||
Assert.Equal(artistId, albumResponse!.ArtistId);
|
||||
Assert.Equal(libraryId, albumResponse.LibraryId);
|
||||
Assert.Equal("News of the World", albumResponse.Metadata.Title);
|
||||
|
||||
Assert.NotNull(response.Headers.Location);
|
||||
Assert.EndsWith($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumResponse.Id}", response.Headers.Location!.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenMetadataIsMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(includeMetadata: false, contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Metadata.MetadataCannotBeNull.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenTitleIsMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(
|
||||
metadata: _albumMetadataDtoFixture.Create(includeTitle: false),
|
||||
contributors: [],
|
||||
ratings: [],
|
||||
tracks: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Music.AlbumTitleCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutDisclosingIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
Guid otherLibraryId = Guid.NewGuid();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{artistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(otherLibraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{artistId}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Library.LibraryIdCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Music.ArtistIdCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAlbum_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
|
||||
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request, cts.Token));
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist that owns a single album, both belonging to <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistWithAlbumAsync(Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+336
@@ -0,0 +1,336 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteAlbumEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumBelongsToAnOwnedArtist_ShouldDeleteTheAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid otherAlbumId) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Null(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId));
|
||||
// The sibling album of the artist is preserved.
|
||||
Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == otherAlbumId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _, _) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumRequestedThroughDifferentArtist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId, _) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId, Guid albumId, _) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, _) = await SeedLibraryArtistWithTwoAlbumsAsync(otherUserId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist that owns two albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and the two albums.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid otherAlbumId)> SeedLibraryArtistWithTwoAlbumsAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid otherAlbumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
AlbumEntity otherAlbum = _albumEntityFixture.Create(id: otherAlbumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album, otherAlbum], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, otherAlbumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+335
@@ -0,0 +1,335 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAlbumEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumBelongsToAnOwnedLibrary_ShouldReturnAlbumDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AlbumResponse? album = JsonSerializer.Deserialize<AlbumResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(album);
|
||||
Assert.Equal(albumId, album!.Id);
|
||||
Assert.Equal(artistId, album.ArtistId);
|
||||
Assert.Equal(libraryId, album.LibraryId);
|
||||
Assert.Equal("A Night at the Opera", album.Metadata.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumRequestedThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
// The route artist id is enforced, so an album of another artist is reported as not found, without disclosing that it exists.
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumRequestedThroughDifferentLibrary_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId, "News of the World");
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbum_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="albumTitle">The title of the seeded album.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAlbumTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAlbumTracksEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumHasTracks_ShouldReturnTrackDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TrackResponse>? tracks = await response.Content.ReadFromJsonAsync<List<TrackResponse>>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
TrackResponse track = Assert.Single(tracks!);
|
||||
Assert.Equal("Bohemian Rhapsody", track.Metadata.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumHasNoTracks_ShouldReturnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TrackResponse>? tracks = await response.Content.ReadFromJsonAsync<List<TrackResponse>>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Empty(tracks!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumRequestedThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid/tracks";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="albumTitle">The title of the seeded album.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist, one of its albums and one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/bohemian-rhapsody-{Guid.NewGuid():N}.flac", title: "Bohemian Rhapsody", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAlbumTracksLiteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksLiteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAlbumTracksLiteEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumHasTracks_ShouldReturnTrackLiteDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<TrackLiteResponse>? tracks = await response.Content.ReadFromJsonAsync<PaginatedResponse<TrackLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Equal(1, tracks!.Count);
|
||||
TrackLiteResponse track = Assert.Single(tracks.Data);
|
||||
Assert.Equal("Bohemian Rhapsody", track.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumHasNoTracks_ShouldReturnEmptyPaginatedResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<TrackLiteResponse>? tracks = await response.Content.ReadFromJsonAsync<PaginatedResponse<TrackLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Empty(tracks!.Data);
|
||||
Assert.Equal(0, tracks.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracksLite_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid/tracks/lite";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="albumTitle">The title of the seeded album.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist, one of its albums and one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/bohemian-rhapsody-{Guid.NewGuid():N}.flac", title: "Bohemian Rhapsody", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+344
@@ -0,0 +1,344 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly UpdateAlbumRequestFixture _updateAlbumRequestFixture = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateAlbumEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenCalledByOwnerWithValidData_ShouldUpdateAlbumAndPersistChanges()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(
|
||||
metadata: _albumMetadataDtoFixture.Create(title: "Updated Album"),
|
||||
contributors: [],
|
||||
ratings: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AlbumResponse? albumResponse = JsonSerializer.Deserialize<AlbumResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(albumResponse);
|
||||
Assert.Equal(albumId, albumResponse!.Id);
|
||||
Assert.Equal("Updated Album", albumResponse.Metadata.Title);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
AlbumEntity storedAlbum = dbContext.Albums.Single(album => album.Id == albumId);
|
||||
Assert.Equal("Updated Album", storedAlbum.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "AlbumNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertNotFoundAsync(response, "ArtistNotFound", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId, "News of the World");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenMetadataIsMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(includeMetadata: false, contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "MetadataCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbum_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
|
||||
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
|
||||
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="albumTitle">The title of the seeded album.</param>
|
||||
/// <returns>The Ids of the seeded library, artist and album.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, artistId, albumId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user