mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 21:11:10 +00:00
Implements tests for commit 067e9a21d0
This commit is contained in:
1 parent
aeefa9487e
commit
a75447062f
18 files changed
+3156
No files matched your search
+416
@@ -17,6 +17,7 @@ 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 Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NSubstitute;
|
||||
@@ -46,6 +47,7 @@ public class TrackRepositoryTests
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
@@ -932,6 +934,348 @@ public class TrackRepositoryTests
|
||||
result.Value.Select(track => track.Id).OrderBy(id => id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShuffleTracksLiteAsync_WhenCalled_ShouldReturnOnlyTracksOfTheRequestedLibrary()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-library-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
|
||||
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
List<TrackEntity> libraryTracks = await SeedShuffleTracksAsync(context, album, libraryId, 3);
|
||||
Guid otherLibraryId = Guid.NewGuid();
|
||||
ArtistEntity otherArtist = await SeedArtistAsync(context, otherLibraryId, "ABBA");
|
||||
AlbumEntity otherAlbum = await SeedAlbumForArtistAsync(context, otherLibraryId, otherArtist.Id, "Arrival");
|
||||
List<TrackEntity> otherLibraryTracks = await SeedShuffleTracksAsync(context, otherAlbum, otherLibraryId, 3);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(
|
||||
libraryId, null, null, [], 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(libraryTracks.Count, result.Value.Count);
|
||||
Assert.All(result.Value, row => Assert.Contains(libraryTracks, track => track.Id == row.TrackId));
|
||||
Assert.DoesNotContain(result.Value, row => otherLibraryTracks.Exists(track => track.Id == row.TrackId));
|
||||
Assert.Equal(result.Value.Count, result.Value.Select(row => row.TrackId).Distinct().Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShuffleTracksLiteAsync_WhenArtistIdIsProvided_ShouldReturnOnlyTracksOfThatArtist()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-artist-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
|
||||
AlbumEntity artistAlbum = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
List<TrackEntity> artistTracks = await SeedShuffleTracksAsync(context, artistAlbum, libraryId, 2);
|
||||
ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId, "David Bowie");
|
||||
AlbumEntity otherArtistAlbum = await SeedAlbumForArtistAsync(context, libraryId, otherArtist.Id, "Heroes");
|
||||
List<TrackEntity> otherArtistTracks = await SeedShuffleTracksAsync(context, otherArtistAlbum, libraryId, 2);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(
|
||||
libraryId, artist.Id, null, [], 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(artistTracks.Count, result.Value.Count);
|
||||
Assert.All(result.Value, row => Assert.Contains(artistTracks, track => track.Id == row.TrackId));
|
||||
Assert.All(result.Value, row => Assert.Equal(artist.Id, row.ArtistId));
|
||||
Assert.DoesNotContain(result.Value, row => otherArtistTracks.Exists(track => track.Id == row.TrackId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShuffleTracksLiteAsync_WhenAlbumIdIsProvided_ShouldReturnOnlyTracksOfThatAlbum()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-album-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
|
||||
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
List<TrackEntity> albumTracks = await SeedShuffleTracksAsync(context, album, libraryId, 2);
|
||||
AlbumEntity otherAlbum = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "News of the World");
|
||||
List<TrackEntity> otherAlbumTracks = await SeedShuffleTracksAsync(context, otherAlbum, libraryId, 2);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(
|
||||
libraryId, null, album.Id, [], 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(albumTracks.Count, result.Value.Count);
|
||||
Assert.All(result.Value, row => Assert.Contains(albumTracks, track => track.Id == row.TrackId));
|
||||
Assert.All(result.Value, row => Assert.Equal(album.Id, row.AlbumId));
|
||||
Assert.DoesNotContain(result.Value, row => otherAlbumTracks.Exists(track => track.Id == row.TrackId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShuffleTracksLiteAsync_WhenArtistIdAndAlbumIdAreProvided_ShouldApplyBothFilters()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-bothfilters-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
|
||||
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
List<TrackEntity> albumTracks = await SeedShuffleTracksAsync(context, album, libraryId, 2);
|
||||
AlbumEntity otherAlbumOfArtist = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "News of the World");
|
||||
List<TrackEntity> otherAlbumOfArtistTracks = await SeedShuffleTracksAsync(context, otherAlbumOfArtist, libraryId, 2);
|
||||
ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId, "David Bowie");
|
||||
AlbumEntity otherArtistAlbum = await SeedAlbumForArtistAsync(context, libraryId, otherArtist.Id, "Heroes");
|
||||
List<TrackEntity> otherArtistAlbumTracks = await SeedShuffleTracksAsync(context, otherArtistAlbum, libraryId, 2);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(
|
||||
libraryId, artist.Id, album.Id, [], 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(albumTracks.Count, result.Value.Count);
|
||||
Assert.All(result.Value, row => Assert.Contains(albumTracks, track => track.Id == row.TrackId));
|
||||
Assert.DoesNotContain(result.Value, row => otherAlbumOfArtistTracks.Exists(track => track.Id == row.TrackId));
|
||||
Assert.DoesNotContain(result.Value, row => otherArtistAlbumTracks.Exists(track => track.Id == row.TrackId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShuffleTracksLiteAsync_WhenExcludedTrackIdsAreProvided_ShouldExcludeEveryOneOfThem()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-excluded-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
|
||||
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
List<TrackEntity> tracks = await SeedShuffleTracksAsync(context, album, libraryId, 4);
|
||||
Guid[] excludedTrackIds = [.. tracks.Take(3).Select(track => track.Id)];
|
||||
TrackEntity expectedTrack = tracks[3];
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(
|
||||
libraryId, null, null, excludedTrackIds, 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
ShuffleTrackRowDto row = Assert.Single(result.Value);
|
||||
Assert.Equal(expectedTrack.Id, row.TrackId);
|
||||
Assert.DoesNotContain(result.Value, candidate => excludedTrackIds.Contains(candidate.TrackId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShuffleTracksLiteAsync_WhenCountIsLowerThanTheAvailableTracks_ShouldReturnAtMostCount()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-count-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
|
||||
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
await SeedShuffleTracksAsync(context, album, libraryId, 5);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(
|
||||
libraryId, null, null, [], 2, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Equal(result.Value.Count, result.Value.Select(row => row.TrackId).Distinct().Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShuffleTracksLiteAsync_WhenTheLibraryHasFewerTracksThanCount_ShouldReturnEveryAvailableTrack()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-fewertracks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
|
||||
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
List<TrackEntity> tracks = await SeedShuffleTracksAsync(context, album, libraryId, 2);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(
|
||||
libraryId, null, null, [], 50, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(tracks.Count, result.Value.Count);
|
||||
Assert.All(result.Value, row => Assert.Contains(tracks, track => track.Id == row.TrackId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShuffleTracksLiteAsync_WhenNothingMatches_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-nomatch-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
|
||||
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
await SeedShuffleTracksAsync(context, album, libraryId, 2);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(
|
||||
libraryId, null, Guid.NewGuid(), [], 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShuffleTracksLiteAsync_WhenCalled_ShouldProjectEveryField()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-projection-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
|
||||
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
albumId: album.Id,
|
||||
libraryId: libraryId,
|
||||
path: "/music/queen/bohemian-rhapsody.flac",
|
||||
title: "Bohemian Rhapsody",
|
||||
includeMetadata: false);
|
||||
track.DurationInSeconds = 355;
|
||||
context.Tracks.Add(track);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(
|
||||
libraryId, null, null, [], 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
ShuffleTrackRowDto row = Assert.Single(result.Value);
|
||||
Assert.Equal(track.Id, row.TrackId);
|
||||
Assert.Equal("Bohemian Rhapsody", row.Title);
|
||||
Assert.Equal(355, row.DurationInSeconds);
|
||||
Assert.Equal(album.Id, row.AlbumId);
|
||||
Assert.Equal("A Night at the Opera", row.AlbumTitle);
|
||||
Assert.Equal(artist.Id, row.ArtistId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShuffleTracksLiteAsync_WhenTheAlbumHasACoverArtwork_ShouldProjectItsFileName()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-cover-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
|
||||
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
TrackEntity track = (await SeedShuffleTracksAsync(context, album, libraryId, 1))[0];
|
||||
await AddArtworkAsync(context, album.Id, ArtworkType.Cover, "a-night-at-the-opera-cover.jpg");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(
|
||||
libraryId, null, album.Id, [], 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
ShuffleTrackRowDto row = Assert.Single(result.Value);
|
||||
Assert.Equal(track.Id, row.TrackId);
|
||||
Assert.Equal("a-night-at-the-opera-cover.jpg", row.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShuffleTracksLiteAsync_WhenTheAlbumHasNoArtwork_ShouldProjectANullCoverPath()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-nocover-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
|
||||
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
await SeedShuffleTracksAsync(context, album, libraryId, 1);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(
|
||||
libraryId, null, album.Id, [], 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
ShuffleTrackRowDto row = Assert.Single(result.Value);
|
||||
Assert.Null(row.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShuffleTracksLiteAsync_WhenTheAlbumOnlyHasANonCoverArtwork_ShouldNotUseItAsTheCover()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-noncover-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
|
||||
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
await SeedShuffleTracksAsync(context, album, libraryId, 1);
|
||||
await AddArtworkAsync(context, album.Id, ArtworkType.Booklet, "booklet-page.jpg");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(
|
||||
libraryId, null, album.Id, [], 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
ShuffleTrackRowDto row = Assert.Single(result.Value);
|
||||
Assert.Null(row.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShuffleTracksLiteAsync_WhenOnlyAnotherAlbumHasACover_ShouldNotUseThatCover()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-othercover-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
|
||||
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
|
||||
await SeedShuffleTracksAsync(context, album, libraryId, 1);
|
||||
AlbumEntity otherAlbum = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "News of the World");
|
||||
await AddArtworkAsync(context, otherAlbum.Id, ArtworkType.Cover, "news-of-the-world-cover.jpg");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(
|
||||
libraryId, null, album.Id, [], 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
ShuffleTrackRowDto row = Assert.Single(result.Value);
|
||||
Assert.Null(row.CoverPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of tracks with distinct paths and empty metadata collections, so that the chunked lookup can be exercised without extra graph data.
|
||||
/// </summary>
|
||||
@@ -1032,4 +1376,76 @@ public class TrackRepositoryTests
|
||||
.Include(track => track.Isrcs)
|
||||
.FirstAsync(track => track.Id == trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="context">The context the artist is persisted through.</param>
|
||||
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The persisted artist.</returns>
|
||||
private async Task<ArtistEntity> SeedArtistAsync(LuminaDbContext context, Guid libraryId, string name)
|
||||
{
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false);
|
||||
context.Artists.Add(artist);
|
||||
await context.SaveChangesAsync();
|
||||
return artist;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of 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 the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The persisted album.</returns>
|
||||
private async Task<AlbumEntity> SeedAlbumForArtistAsync(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 a number of tracks of the album identified by <paramref name="album"/>, with distinct paths and no metadata collections.
|
||||
/// </summary>
|
||||
/// <param name="context">The context the tracks are persisted through.</param>
|
||||
/// <param name="album">The album that owns the tracks.</param>
|
||||
/// <param name="libraryId">The Id of the library that owns the tracks.</param>
|
||||
/// <param name="count">The number of tracks to seed.</param>
|
||||
/// <returns>The persisted tracks.</returns>
|
||||
private async Task<List<TrackEntity>> SeedShuffleTracksAsync(LuminaDbContext context, AlbumEntity album, Guid libraryId, int count)
|
||||
{
|
||||
List<TrackEntity> tracks = [.. Enumerable.Range(0, count).Select(index => _trackEntityFixture.Create(
|
||||
albumId: album.Id,
|
||||
libraryId: libraryId,
|
||||
path: $"/music/shuffle-{Guid.NewGuid():N}.flac",
|
||||
title: $"Shuffle Track {index}",
|
||||
includeMetadata: false))];
|
||||
context.Tracks.AddRange(tracks);
|
||||
await context.SaveChangesAsync();
|
||||
return tracks;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a piece of artwork of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="context">The context the artwork is persisted through.</param>
|
||||
/// <param name="albumId">The Id of the album that owns the artwork.</param>
|
||||
/// <param name="artworkType">The type of the artwork.</param>
|
||||
/// <param name="fileName">The relative file name of the stored artwork.</param>
|
||||
private async Task AddArtworkAsync(LuminaDbContext context, Guid albumId, ArtworkType artworkType, string fileName)
|
||||
{
|
||||
context.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album,
|
||||
ownerId: albumId,
|
||||
artworkType: artworkType,
|
||||
ordinal: 0,
|
||||
fileName: fileName,
|
||||
status: ArtworkStatus.Enriched));
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+483
@@ -0,0 +1,483 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.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.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ShuffleTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksEndpointTests : 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 MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ShuffleTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ShuffleTracksEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenLibraryHasTracks_ShouldReturnTheTracksWithAllTheirFields()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Queen Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
Guid trackId = await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
|
||||
Guid otherTrackId = await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219);
|
||||
await SeedAlbumCoverAsync(albumId, "a-night-at-the-opera-cover.jpg");
|
||||
// A second library proves that the response is scoped to the library in the route.
|
||||
Guid otherLibraryId = await SeedLibraryAsync(userId, "Other Library");
|
||||
Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "ABBA");
|
||||
Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Arrival");
|
||||
Guid otherLibraryTrackId = await SeedTrackAsync(otherLibraryId, otherAlbumId, "Dancing Queen", 231);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, 10);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<ShuffleTrackResponse>? tracks = JsonSerializer.Deserialize<List<ShuffleTrackResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Equal(2, tracks!.Count);
|
||||
Assert.All(tracks, track => Assert.Contains(track.TrackId, new[] { trackId, otherTrackId }));
|
||||
Assert.DoesNotContain(tracks, track => track.TrackId == otherLibraryTrackId);
|
||||
ShuffleTrackResponse foundTrack = Assert.Single(tracks, track => track.TrackId == trackId);
|
||||
Assert.Equal("Bohemian Rhapsody", foundTrack.Title);
|
||||
Assert.Equal(355, foundTrack.DurationInSeconds);
|
||||
Assert.Equal(albumId, foundTrack.AlbumId);
|
||||
Assert.Equal("A Night at the Opera", foundTrack.AlbumTitle);
|
||||
Assert.Equal(artistId, foundTrack.ArtistId);
|
||||
Assert.Equal("a-night-at-the-opera-cover.jpg", foundTrack.CoverPath);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenArtistIdIsProvided_ShouldReturnOnlyTracksOfAlbumsOfThatArtist()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Two Artists Library");
|
||||
Guid firstArtistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid firstAlbumId = await SeedAlbumAsync(libraryId, firstArtistId, "A Night at the Opera");
|
||||
await SeedTrackAsync(libraryId, firstAlbumId, "Bohemian Rhapsody", 355);
|
||||
await SeedTrackAsync(libraryId, firstAlbumId, "Love of My Life", 219);
|
||||
Guid secondArtistId = await SeedArtistAsync(libraryId, "David Bowie");
|
||||
Guid secondAlbumId = await SeedAlbumAsync(libraryId, secondArtistId, "Heroes");
|
||||
await SeedTrackAsync(libraryId, secondAlbumId, "Heroes", 371);
|
||||
await SeedTrackAsync(libraryId, secondAlbumId, "Beauty and the Beast", 212);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, 10, artistId: firstArtistId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<ShuffleTrackResponse>? tracks = JsonSerializer.Deserialize<List<ShuffleTrackResponse>>(
|
||||
await response.Content.ReadAsStringAsync(), _jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Equal(2, tracks!.Count);
|
||||
Assert.All(tracks, track => Assert.Equal(firstArtistId, track.ArtistId));
|
||||
Assert.All(tracks, track => Assert.Equal(firstAlbumId, track.AlbumId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenAlbumIdIsProvided_ShouldReturnOnlyTracksOfThatAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Two Albums Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
|
||||
await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219);
|
||||
Guid otherAlbumId = await SeedAlbumAsync(libraryId, artistId, "News of the World");
|
||||
await SeedTrackAsync(libraryId, otherAlbumId, "We Are the Champions", 179);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, 10, albumId: albumId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<ShuffleTrackResponse>? tracks = JsonSerializer.Deserialize<List<ShuffleTrackResponse>>(
|
||||
await response.Content.ReadAsStringAsync(), _jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Equal(2, tracks!.Count);
|
||||
Assert.All(tracks, track => Assert.Equal(albumId, track.AlbumId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenExcludedTrackIdsAreProvided_ShouldNeverReturnThem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Exclusion Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
Guid firstTrackId = await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
|
||||
Guid secondTrackId = await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219);
|
||||
Guid thirdTrackId = await SeedTrackAsync(libraryId, albumId, "The Prophet Song", 367);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(
|
||||
libraryId, 10, excludedTrackIds: [firstTrackId, secondTrackId]);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<ShuffleTrackResponse>? tracks = JsonSerializer.Deserialize<List<ShuffleTrackResponse>>(
|
||||
await response.Content.ReadAsStringAsync(), _jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
ShuffleTrackResponse track = Assert.Single(tracks!);
|
||||
Assert.Equal(thirdTrackId, track.TrackId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenCountIsLowerThanTheAvailableTracks_ShouldReturnAtMostCountTracks()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Count Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
for (int index = 0; index < 5; index++)
|
||||
await SeedTrackAsync(libraryId, albumId, $"Track {index}", 200 + index);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, 2);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<ShuffleTrackResponse>? tracks = JsonSerializer.Deserialize<List<ShuffleTrackResponse>>(
|
||||
await response.Content.ReadAsStringAsync(), _jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Equal(2, tracks!.Count);
|
||||
Assert.Equal(tracks.Count, tracks.Select(track => track.TrackId).Distinct().Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenCountIsLargerThanTheAvailableTracks_ShouldReturnEveryAvailableTrack()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Small Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
Guid firstTrackId = await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
|
||||
Guid secondTrackId = await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, 50);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<ShuffleTrackResponse>? tracks = JsonSerializer.Deserialize<List<ShuffleTrackResponse>>(
|
||||
await response.Content.ReadAsStringAsync(), _jsonOptions);
|
||||
Assert.NotNull(tracks);
|
||||
Assert.Equal(2, tracks!.Count);
|
||||
Assert.Contains(tracks, track => track.TrackId == firstTrackId);
|
||||
Assert.Contains(tracks, track => track.TrackId == secondTrackId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, "ShuffleTrackCountMustBeGreaterThanZero")] // no track is requested
|
||||
[InlineData(-1, "ShuffleTrackCountMustBeGreaterThanZero")] // a negative selection size
|
||||
[InlineData(501, "ShuffleTrackCountMustBeAtMost500")] // one more than the documented maximum
|
||||
public async Task ShuffleTracks_WhenCountIsInvalid_ShouldReturnUnprocessableEntityWithTheValidationError(int count, string expectedError)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Validation Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, count);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.Validation", problemDetails!["title"].GetString());
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails["status"].GetInt32());
|
||||
JsonElement errors = problemDetails["errors"];
|
||||
Assert.True(errors.TryGetProperty("General.Validation", out JsonElement validationErrors));
|
||||
Assert.Contains(validationErrors.EnumerateArray(), error => error.GetString() == expectedError);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenWithoutTrackData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, string otherUsername) = await SeedOtherUserAsync();
|
||||
Guid libraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
await SeedTrackAsync(libraryId, albumId, "Secret Song", 300);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostShuffleAsync(libraryId, 10);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Secret Song", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.False(string.IsNullOrWhiteSpace(otherUsername));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Posts a shuffle request for the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library whose tracks are shuffled.</param>
|
||||
/// <param name="count">The maximum number of tracks to return.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist whose tracks are sampled.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album whose tracks are sampled.</param>
|
||||
/// <param name="excludedTrackIds">Optional. The tracks that must not be returned.</param>
|
||||
/// <returns>The response of the API.</returns>
|
||||
private async Task<HttpResponseMessage> PostShuffleAsync(
|
||||
Guid libraryId,
|
||||
int count,
|
||||
Guid? artistId = null,
|
||||
Guid? albumId = null,
|
||||
IReadOnlyCollection<Guid>? excludedTrackIds = null)
|
||||
{
|
||||
return await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{libraryId}/tracks/shuffle",
|
||||
new { count, artistId, albumId, excludedTrackIds });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
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: title, libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(
|
||||
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Albums.Add(album);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <param name="durationInSeconds">The duration of the track in seconds.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title, int durationInSeconds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
path: $"/music/shuffle-{Guid.NewGuid():N}.flac",
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
track.DurationInSeconds = durationInSeconds;
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the cover artwork of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="albumId">The Id of the album that owns the artwork.</param>
|
||||
/// <param name="fileName">The file name of the stored cover.</param>
|
||||
private async Task SeedAlbumCoverAsync(Guid albumId, string fileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album,
|
||||
ownerId: albumId,
|
||||
artworkType: ArtworkType.Cover,
|
||||
ordinal: 0,
|
||||
fileName: fileName,
|
||||
status: ArtworkStatus.Enriched));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id and the username of the seeded user.</returns>
|
||||
private async Task<(Guid userId, string username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
foreach (Guid libraryId in _seededLibraryIds)
|
||||
{
|
||||
List<Guid> albumIds = await dbContext.Albums
|
||||
.Where(album => album.LibraryId == libraryId)
|
||||
.Select(album => album.Id)
|
||||
.ToListAsync();
|
||||
dbContext.MusicArtwork.RemoveRange(dbContext.MusicArtwork.Where(artwork => albumIds.Contains(artwork.OwnerId)));
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => track.LibraryId == libraryId));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => album.LibraryId == libraryId));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => artist.LibraryId == libraryId));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => library.Id == libraryId));
|
||||
}
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ShuffleTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private const string SHUFFLE_TRACKS_PATH = "/en-us/library/audio-library/music-library/tracks/api-shuffle-tracks";
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ShuffleTracksRequestFixture _shuffleTracksRequestFixture = new();
|
||||
private readonly MusicShuffleTrackDtoFixture _musicShuffleTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ShuffleTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ShuffleTracksEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenApiReturnsTracks_ShouldReturnTheMappedTracks()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid excludedTrackId = Guid.NewGuid();
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(
|
||||
count: 25, excludedTrackIds: [excludedTrackId]);
|
||||
MusicShuffleTrackDto expectedTrack = _musicShuffleTrackDtoFixture.Create(
|
||||
trackId: trackId,
|
||||
title: "Bohemian Rhapsody",
|
||||
durationInSeconds: 355,
|
||||
albumId: albumId,
|
||||
albumTitle: "A Night at the Opera",
|
||||
artistId: artistId,
|
||||
coverPath: "a-night-at-the-opera-cover.jpg");
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(ExpectedEndpoint(request.LibraryId), new List<MusicShuffleTrackDto> { expectedTrack });
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateShuffleRequest(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetArrayLength());
|
||||
JsonElement track = data[0];
|
||||
Assert.Equal(trackId, track.GetProperty("trackId").GetGuid());
|
||||
Assert.Equal("Bohemian Rhapsody", track.GetProperty("title").GetString());
|
||||
Assert.Equal(355, track.GetProperty("durationInSeconds").GetInt32());
|
||||
Assert.Equal(albumId, track.GetProperty("albumId").GetGuid());
|
||||
Assert.Equal("A Night at the Opera", track.GetProperty("albumTitle").GetString());
|
||||
Assert.Equal(artistId, track.GetProperty("artistId").GetGuid());
|
||||
Assert.Equal("a-night-at-the-opera-cover.jpg", track.GetProperty("coverPath").GetString());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenCalled_ShouldForwardTheRequestToTheLibraryShuffleEndpoint()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid firstExcludedTrackId = Guid.NewGuid();
|
||||
Guid secondExcludedTrackId = Guid.NewGuid();
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(
|
||||
count: 25,
|
||||
artistId: artistId,
|
||||
albumId: albumId,
|
||||
excludedTrackIds: [firstExcludedTrackId, secondExcludedTrackId]);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(ExpectedEndpoint(request.LibraryId), new List<MusicShuffleTrackDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateShuffleRequest(request));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
(string Endpoint, object? Data) forwardedRequest = Assert.Single(
|
||||
_apiFactory.ApiClientStub.PostRequests,
|
||||
postRequest => postRequest.Endpoint == ExpectedEndpoint(request.LibraryId));
|
||||
Assert.Equal($"libraries/{request.LibraryId}/tracks/shuffle", forwardedRequest.Endpoint);
|
||||
ShuffleTracksRequest forwarded = Assert.IsType<ShuffleTracksRequest>(forwardedRequest.Data);
|
||||
Assert.Equal(request.LibraryId, forwarded.LibraryId);
|
||||
Assert.Equal(25, forwarded.Count);
|
||||
Assert.Equal(artistId, forwarded.ArtistId);
|
||||
Assert.Equal(albumId, forwarded.AlbumId);
|
||||
Assert.NotNull(forwarded.ExcludedTrackIds);
|
||||
Assert.Equal(new[] { firstExcludedTrackId, secondExcludedTrackId }, forwarded.ExcludedTrackIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenApiReturnsNoTracks_ShouldReturnAnEmptyDataArray()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(ExpectedEndpoint(request.LibraryId), new List<MusicShuffleTrackDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateShuffleRequest(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(JsonValueKind.Array, data.ValueKind);
|
||||
Assert.Equal(0, data.GetArrayLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenBodyIsMalformed_ShouldNotLeakServerDetailsOrCallTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
StringContent body = new("{\"libraryId\": \"'; DROP TABLE Tracks; --\", \"count\": \"'; DROP TABLE Tracks; --\"}", Encoding.UTF8, "application/json");
|
||||
HttpRequestMessage shuffleRequest = new(HttpMethod.Post, SHUFFLE_TRACKS_PATH)
|
||||
{
|
||||
Content = body
|
||||
};
|
||||
shuffleRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
shuffleRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(shuffleRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The unbound request is rejected before the upstream API is reached, and the JSON error is sanitized.
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint.EndsWith("/tracks/shuffle", StringComparison.Ordinal));
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("'; DROP TABLE Tracks; --", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream API endpoint of the shuffle request for the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the tracks are sampled from.</param>
|
||||
/// <returns>The upstream endpoint.</returns>
|
||||
private static string ExpectedEndpoint(Guid libraryId)
|
||||
{
|
||||
return ApiRoutes.Music.SHUFFLE_TRACKS.Replace("{libraryId}", libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the Web shuffle request that posts the given <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The shuffle request to send.</param>
|
||||
/// <returns>The configured Web request.</returns>
|
||||
private static HttpRequestMessage CreateShuffleRequest(ShuffleTracksRequest request)
|
||||
{
|
||||
HttpRequestMessage shuffleRequest = new(HttpMethod.Post, SHUFFLE_TRACKS_PATH)
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
shuffleRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
shuffleRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return shuffleRequest;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user