mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +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
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ShuffleTrackRowDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTrackRowFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ShuffleTrackRowDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="trackId">Optional. The Id of the track.</param>
|
||||
/// <param name="title">Optional. The title of the track.</param>
|
||||
/// <param name="durationInSeconds">Optional. The duration of the track in seconds.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
|
||||
/// <param name="albumTitle">Optional. The title of the album the track belongs to.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the album belongs to.</param>
|
||||
/// <param name="coverPath">Optional. The path of the cover of the album.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="ShuffleTrackRowDto"/>.</returns>
|
||||
public ShuffleTrackRowDto Create(
|
||||
Guid? trackId = null,
|
||||
string? title = null,
|
||||
int? durationInSeconds = null,
|
||||
Guid? albumId = null,
|
||||
string? albumTitle = null,
|
||||
Guid? artistId = null,
|
||||
string? coverPath = null,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new ShuffleTrackRowDto(
|
||||
trackId ?? _faker.Random.Guid(),
|
||||
title ?? _faker.Lorem.Sentence(),
|
||||
durationInSeconds ?? _faker.Random.Int(1, 7200),
|
||||
albumId ?? _faker.Random.Guid(),
|
||||
albumTitle ?? _faker.Lorem.Sentence(),
|
||||
artistId ?? _faker.Random.Guid(),
|
||||
includeCoverPath ? (coverPath ?? _faker.System.FileName("jpg")) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="ShuffleTrackRowDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ShuffleTrackRowDto"/> instances.</returns>
|
||||
public List<ShuffleTrackRowDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ShuffleTracksQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ShuffleTracksQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the tracks are sampled from, taken from the route.</param>
|
||||
/// <param name="count">Optional. 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>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeExcludedTrackIds">Whether the excluded track Ids should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="ShuffleTracksQuery"/>.</returns>
|
||||
public ShuffleTracksQuery Create(
|
||||
string? libraryId = null,
|
||||
int? count = null,
|
||||
Guid? artistId = null,
|
||||
Guid? albumId = null,
|
||||
IReadOnlyList<Guid>? excludedTrackIds = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeArtistId = true,
|
||||
bool includeAlbumId = true,
|
||||
bool includeExcludedTrackIds = true)
|
||||
{
|
||||
return new ShuffleTracksQuery(
|
||||
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
|
||||
count ?? Random.Shared.Next(1, 501),
|
||||
includeArtistId ? (artistId ?? Guid.NewGuid()) : null,
|
||||
includeAlbumId ? (albumId ?? Guid.NewGuid()) : null,
|
||||
includeExcludedTrackIds
|
||||
? (excludedTrackIds ?? [.. Enumerable.Range(0, Random.Shared.Next(0, 3)).Select(_ => Guid.NewGuid())])
|
||||
: null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="ShuffleTracksQuery"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ShuffleTracksQuery"/> instances.</returns>
|
||||
public List<ShuffleTracksQuery> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ShuffleTracksRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ShuffleTracksRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">Optional. 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>
|
||||
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeExcludedTrackIds">Whether the excluded track Ids should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="ShuffleTracksRequest"/>.</returns>
|
||||
public ShuffleTracksRequest Create(
|
||||
int? count = null,
|
||||
Guid? artistId = null,
|
||||
Guid? albumId = null,
|
||||
List<Guid>? excludedTrackIds = null,
|
||||
bool includeArtistId = true,
|
||||
bool includeAlbumId = true,
|
||||
bool includeExcludedTrackIds = true)
|
||||
{
|
||||
return new ShuffleTracksRequest(
|
||||
count ?? Random.Shared.Next(1, 501),
|
||||
includeArtistId ? (artistId ?? Guid.NewGuid()) : null,
|
||||
includeAlbumId ? (albumId ?? Guid.NewGuid()) : null,
|
||||
includeExcludedTrackIds
|
||||
? (excludedTrackIds ?? [.. Enumerable.Range(0, Random.Shared.Next(0, 3)).Select(_ => Guid.NewGuid())])
|
||||
: null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="ShuffleTracksRequest"/> records with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ShuffleTracksRequest"/> records.</returns>
|
||||
public List<ShuffleTracksRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ShuffleTrackResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTrackResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ShuffleTrackResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="trackId">Optional. The Id of the track.</param>
|
||||
/// <param name="title">Optional. The title of the track.</param>
|
||||
/// <param name="durationInSeconds">Optional. The duration of the track in seconds.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
|
||||
/// <param name="albumTitle">Optional. The title of the album the track belongs to.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the album belongs to.</param>
|
||||
/// <param name="coverPath">Optional. The path of the cover of the album.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="ShuffleTrackResponse"/>.</returns>
|
||||
public ShuffleTrackResponse Create(
|
||||
Guid? trackId = null,
|
||||
string? title = null,
|
||||
int? durationInSeconds = null,
|
||||
Guid? albumId = null,
|
||||
string? albumTitle = null,
|
||||
Guid? artistId = null,
|
||||
string? coverPath = null,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new ShuffleTrackResponse(
|
||||
trackId ?? _faker.Random.Guid(),
|
||||
title ?? _faker.Lorem.Sentence(),
|
||||
durationInSeconds ?? _faker.Random.Int(1, 7200),
|
||||
albumId ?? _faker.Random.Guid(),
|
||||
albumTitle ?? _faker.Lorem.Sentence(),
|
||||
artistId ?? _faker.Random.Guid(),
|
||||
includeCoverPath ? (coverPath ?? _faker.System.FileName("jpg")) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="ShuffleTrackResponse"/> records with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ShuffleTrackResponse"/> records.</returns>
|
||||
public List<ShuffleTrackResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicShuffleTrackDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicShuffleTrackDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MusicShuffleTrackDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="trackId">Optional. The Id of the track.</param>
|
||||
/// <param name="title">Optional. The title of the track.</param>
|
||||
/// <param name="durationInSeconds">Optional. The duration of the track in seconds.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
|
||||
/// <param name="albumTitle">Optional. The title of the album the track belongs to.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist the album belongs to.</param>
|
||||
/// <param name="coverPath">Optional. The path of the cover of the album.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="MusicShuffleTrackDto"/> instance.</returns>
|
||||
public MusicShuffleTrackDto Create(
|
||||
Guid? trackId = null,
|
||||
string? title = null,
|
||||
int? durationInSeconds = null,
|
||||
Guid? albumId = null,
|
||||
string? albumTitle = null,
|
||||
Guid? artistId = null,
|
||||
string? coverPath = null,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new MusicShuffleTrackDto
|
||||
{
|
||||
TrackId = trackId ?? _faker.Random.Guid(),
|
||||
Title = title ?? _faker.Lorem.Sentence(),
|
||||
DurationInSeconds = durationInSeconds ?? _faker.Random.Int(1, 7200),
|
||||
AlbumId = albumId ?? _faker.Random.Guid(),
|
||||
AlbumTitle = albumTitle ?? _faker.Lorem.Sentence(),
|
||||
ArtistId = artistId ?? _faker.Random.Guid(),
|
||||
CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FileName("jpg")) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MusicShuffleTrackDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicShuffleTrackDto"/> instances.</returns>
|
||||
public List<MusicShuffleTrackDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ShuffleTracksRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ShuffleTracksRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the tracks are sampled from.</param>
|
||||
/// <param name="count">Optional. 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>
|
||||
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeExcludedTrackIds">Whether the excluded track Ids should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="ShuffleTracksRequest"/>.</returns>
|
||||
public ShuffleTracksRequest Create(
|
||||
Guid? libraryId = null,
|
||||
int? count = null,
|
||||
Guid? artistId = null,
|
||||
Guid? albumId = null,
|
||||
List<Guid>? excludedTrackIds = null,
|
||||
bool includeArtistId = true,
|
||||
bool includeAlbumId = true,
|
||||
bool includeExcludedTrackIds = true)
|
||||
{
|
||||
return new ShuffleTracksRequest(
|
||||
libraryId ?? Guid.NewGuid(),
|
||||
count ?? Random.Shared.Next(1, 501),
|
||||
includeArtistId ? (artistId ?? Guid.NewGuid()) : null,
|
||||
includeAlbumId ? (albumId ?? Guid.NewGuid()) : null,
|
||||
includeExcludedTrackIds
|
||||
? (excludedTrackIds ?? [.. Enumerable.Range(0, Random.Shared.Next(0, 3)).Select(_ => Guid.NewGuid())])
|
||||
: null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="ShuffleTracksRequest"/> records with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ShuffleTracksRequest"/> records.</returns>
|
||||
public List<ShuffleTracksRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+353
@@ -0,0 +1,353 @@
|
||||
#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.Tracks.ShuffleTracks;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
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.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="ShuffleTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Rate limiting is not exercised because the shuffle route does not declare a rate limiter policy, unlike the authentication and track streaming routes,
|
||||
/// so there is no configured limit to exceed. Token and claim correctness does not apply, because the route issues no token. Timing attack resistance does not
|
||||
/// apply either, because the route performs no credential comparison.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
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();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ShuffleTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ShuffleTracksEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// A unique X-Forwarded-For isolates rate limiting state per test.
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, new { count = 10 });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, 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(url, problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task ShuffleTracks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/tracks/shuffle", new { count = 10 });
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInCount_ShouldNotCorruptOrLeakData(string maliciousCount)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = maliciousCount });
|
||||
|
||||
// Assert
|
||||
// The endpoint opts into DontCatchExceptions(), so a body value that cannot be bound is answered by the generic exception handler with the sanitized 500 problem.
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
await AssertSanitizedProblemAsync(response, maliciousCount);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = 10, artistId = maliciousArtistId });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
await AssertSanitizedProblemAsync(response, maliciousArtistId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = 10, albumId = maliciousAlbumId });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
await AssertSanitizedProblemAsync(response, maliciousAlbumId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInExcludedTrackIds_ShouldNotCorruptOrLeakData(string maliciousTrackId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = 10, excludedTrackIds = new[] { maliciousTrackId } });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
await AssertSanitizedProblemAsync(response, maliciousTrackId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid otherUserId = 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, "Hidden Song");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{libraryId}/tracks/shuffle", new { count = 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(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Hidden Song", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the sanitized generic API problem and never echoes the payload or leaks database details.
|
||||
/// </summary>
|
||||
/// <param name="response">The response to inspect.</param>
|
||||
/// <param name="payload">The malicious payload that must not be echoed.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private static async Task AssertSanitizedProblemAsync(HttpResponseMessage response, string payload)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("InternalServerError", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, problemDetails.RootElement.GetProperty("status").GetInt32());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded other user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>.
|
||||
/// </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();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(
|
||||
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Albums.Add(album);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
path: $"/music/shuffle-{Guid.NewGuid():N}.flac",
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
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.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
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.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="ShuffleTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The shuffle route declares no rate limiter policy, so rate limiting is not exercised here. Token and claim correctness does not apply, because the Web
|
||||
/// layer issues no token for this route, and timing attack resistance does not apply either, because the route performs no credential comparison.
|
||||
/// </remarks>
|
||||
[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 ProblemDetailsDtoFixture _problemDetailsDtoFixture = 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_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(CreateShuffleRequest(request));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => IsShuffleCall(postRequest.Endpoint));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInLibraryId_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateRawShuffleRequest(
|
||||
$"{{\"libraryId\": {JsonSerializer.Serialize(payload)}, \"count\": 10}}"));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
AssertRejectedWithoutLeak(content, payload);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInCount_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateRawShuffleRequest(
|
||||
$"{{\"libraryId\": \"{Guid.NewGuid()}\", \"count\": {JsonSerializer.Serialize(payload)}}}"));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
AssertRejectedWithoutLeak(content, payload);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInExcludedTrackIds_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateRawShuffleRequest(
|
||||
$"{{\"libraryId\": \"{Guid.NewGuid()}\", \"count\": 10, \"excludedTrackIds\": [{JsonSerializer.Serialize(payload)}]}}"));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
AssertRejectedWithoutLeak(content, payload);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenApiRejectsTheRequest_ShouldReturnACleanErrorWithoutLeakingData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(libraryId: libraryId);
|
||||
string expectedEndpoint = ApiRoutes.Music.SHUFFLE_TRACKS.Replace("{libraryId}", libraryId.ToString());
|
||||
_apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Unauthorized", detail: "NotAuthorized"),
|
||||
HttpStatusCode.Forbidden,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateShuffleRequest(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The Web layer answers programmatic callers with a sanitized JSON error instead of forwarding the upstream problem details verbatim.
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains("not authorized", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == expectedEndpoint);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a request rejected before reaching the API was answered with a sanitized JSON error that does not echo the payload.
|
||||
/// </summary>
|
||||
/// <param name="content">The body of the response.</param>
|
||||
/// <param name="payload">The malicious payload that must not be echoed.</param>
|
||||
private void AssertRejectedWithoutLeak(string content, string payload)
|
||||
{
|
||||
// The Web layer reports binding failures to programmatic callers as a JSON error with the success flag cleared, and never forwards the request upstream.
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => IsShuffleCall(postRequest.Endpoint));
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the specified upstream endpoint is the shuffle endpoint.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The upstream endpoint to check.</param>
|
||||
/// <returns><see langword="true"/> when the endpoint is the shuffle endpoint, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsShuffleCall(string endpoint)
|
||||
{
|
||||
return endpoint.EndsWith("/tracks/shuffle", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the Web shuffle request that posts the given raw JSON body.
|
||||
/// </summary>
|
||||
/// <param name="jsonBody">The raw JSON body to send.</param>
|
||||
/// <returns>The configured Web request.</returns>
|
||||
private static HttpRequestMessage CreateRawShuffleRequest(string jsonBody)
|
||||
{
|
||||
HttpRequestMessage shuffleRequest = new(HttpMethod.Post, SHUFFLE_TRACKS_PATH)
|
||||
{
|
||||
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
|
||||
};
|
||||
shuffleRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
shuffleRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return shuffleRequest;
|
||||
}
|
||||
}
|
||||
+21
@@ -27,6 +27,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.
|
||||
public class AlbumEntityMappingTests
|
||||
{
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
@@ -252,6 +253,7 @@ public class AlbumEntityMappingTests
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity entity = _albumEntityFixture.Create();
|
||||
entity.Artist = _artistEntityFixture.Create(name: "Queen");
|
||||
|
||||
// Act
|
||||
AlbumResponse result = entity.ToResponse();
|
||||
@@ -260,6 +262,7 @@ public class AlbumEntityMappingTests
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(entity.Id, result.Id);
|
||||
Assert.Equal(entity.ArtistId, result.ArtistId);
|
||||
Assert.Equal("Queen", result.ArtistName);
|
||||
Assert.Equal(entity.LibraryId, result.LibraryId);
|
||||
// No cover path is supplied by default, so the response exposes none.
|
||||
Assert.Null(result.CoverPath);
|
||||
@@ -299,6 +302,21 @@ public class AlbumEntityMappingTests
|
||||
Assert.Equal(entity.Tracks.Select(track => track.Id), result.Tracks!.Select(track => track.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenAlbumHasNoArtist_ShouldMapAnEmptyArtistName()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity entity = _albumEntityFixture.Create();
|
||||
entity.Artist = null;
|
||||
|
||||
// Act
|
||||
AlbumResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
// The response contract always carries an artist name, so an album loaded without its artist exposes an empty one instead of null.
|
||||
Assert.Equal(string.Empty, result.ArtistName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenLanguageSubpropertiesAreBlank_ShouldMapLanguagesToNull()
|
||||
{
|
||||
@@ -335,6 +353,8 @@ public class AlbumEntityMappingTests
|
||||
{
|
||||
// Arrange
|
||||
List<AlbumEntity> entities = _albumEntityFixture.CreateMany(2);
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
entities[i].Artist = _artistEntityFixture.Create(name: $"Artist {i}");
|
||||
|
||||
// Act
|
||||
IReadOnlyList<AlbumResponse> results = entities.ToResponses();
|
||||
@@ -346,6 +366,7 @@ public class AlbumEntityMappingTests
|
||||
{
|
||||
Assert.Equal(entities[i].Id, results[i].Id);
|
||||
Assert.Equal(entities[i].Title, results[i].Metadata.Title);
|
||||
Assert.Equal($"Artist {i}", results[i].ArtistName);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ShuffleTrackRowDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTrackRowDtoMappingTests
|
||||
{
|
||||
private readonly ShuffleTrackRowFixture _shuffleTrackRowFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingTrackWithCoverPath_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTrackRowDto readModel = _shuffleTrackRowFixture.Create(
|
||||
title: "Bohemian Rhapsody",
|
||||
durationInSeconds: 355,
|
||||
albumTitle: "A Night at the Opera",
|
||||
coverPath: "a-night-at-the-opera-cover.jpg");
|
||||
|
||||
// Act
|
||||
ShuffleTrackResponse result = readModel.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(readModel.TrackId, result.TrackId);
|
||||
Assert.Equal(readModel.Title, result.Title);
|
||||
Assert.Equal(readModel.DurationInSeconds, result.DurationInSeconds);
|
||||
Assert.Equal(readModel.AlbumId, result.AlbumId);
|
||||
Assert.Equal(readModel.AlbumTitle, result.AlbumTitle);
|
||||
Assert.Equal(readModel.ArtistId, result.ArtistId);
|
||||
Assert.Equal("a-night-at-the-opera-cover.jpg", result.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenCoverPathIsMissing_ShouldMapNullCoverPath()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTrackRowDto readModel = _shuffleTrackRowFixture.Create(includeCoverPath: false);
|
||||
|
||||
// Act
|
||||
ShuffleTrackResponse result = readModel.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.CoverPath);
|
||||
Assert.Equal(readModel.TrackId, result.TrackId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleRows_ShouldMapEveryRowAndPreserveTheOrder()
|
||||
{
|
||||
// Arrange
|
||||
List<ShuffleTrackRowDto> readModels = _shuffleTrackRowFixture.CreateMany(4);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<ShuffleTrackResponse> results = readModels.ToResponses();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(results);
|
||||
Assert.Equal(readModels.Count, results.Count);
|
||||
Assert.Equal(readModels.Select(readModel => readModel.TrackId), results.Select(response => response.TrackId));
|
||||
Assert.Equal(readModels.Select(readModel => readModel.Title), results.Select(response => response.Title));
|
||||
Assert.Equal(readModels.Select(readModel => readModel.DurationInSeconds), results.Select(response => response.DurationInSeconds));
|
||||
Assert.Equal(readModels.Select(readModel => readModel.AlbumId), results.Select(response => response.AlbumId));
|
||||
Assert.Equal(readModels.Select(readModel => readModel.AlbumTitle), results.Select(response => response.AlbumTitle));
|
||||
Assert.Equal(readModels.Select(readModel => readModel.ArtistId), results.Select(response => response.ArtistId));
|
||||
Assert.Equal(readModels.Select(readModel => readModel.CoverPath), results.Select(response => response.CoverPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenInputIsEmpty_ShouldReturnAnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
IEnumerable<ShuffleTrackRowDto> readModels = [];
|
||||
|
||||
// Act
|
||||
IReadOnlyList<ShuffleTrackResponse> results = readModels.ToResponses();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(results);
|
||||
Assert.Empty(results);
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ShuffleTracksRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksRequestMappingTests
|
||||
{
|
||||
private readonly ShuffleTracksRequestFixture _shuffleTracksRequestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
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]);
|
||||
|
||||
// Act
|
||||
ShuffleTracksQuery result = request.ToQuery(libraryId.ToString());
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(libraryId.ToString(), result.LibraryId);
|
||||
Assert.Equal(25, result.Count);
|
||||
Assert.Equal(artistId, result.ArtistId);
|
||||
Assert.Equal(albumId, result.AlbumId);
|
||||
Assert.NotNull(result.ExcludedTrackIds);
|
||||
Assert.Equal(new[] { firstExcludedTrackId, secondExcludedTrackId }, result.ExcludedTrackIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenExcludedTrackIdsAreNull_ShouldKeepThemNull()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(includeExcludedTrackIds: false);
|
||||
|
||||
// Act
|
||||
ShuffleTracksQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.ExcludedTrackIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenOptionalScopeIsMissing_ShouldKeepTheScopeNull()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(includeArtistId: false, includeAlbumId: false);
|
||||
|
||||
// Act
|
||||
ShuffleTracksQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.ArtistId);
|
||||
Assert.Null(result.AlbumId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenLibraryIdArgumentIsNull_ShouldKeepItNull()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
ShuffleTracksQuery result = request.ToQuery(null);
|
||||
|
||||
// Assert
|
||||
// The route value is forwarded untouched, so that the query validator reports the missing identifier.
|
||||
Assert.Null(result.LibraryId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not-a-guid")] // a value that cannot be parsed
|
||||
[InlineData("' OR '1'='1")] // an injection payload
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // a destructive injection payload
|
||||
public void ToQuery_WhenLibraryIdArgumentIsNotParseable_ShouldPassItVerbatim(string libraryId)
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
ShuffleTracksQuery result = request.ToQuery(libraryId);
|
||||
|
||||
// Assert
|
||||
// The raw route value must reach the validator, which is the layer that decides it is not a valid identifier.
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
Assert.Equal(request.Count, result.Count);
|
||||
}
|
||||
}
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
|
||||
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ShuffleTracksQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ITrackRepository _mockTrackRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<ShuffleTracksQuery> _mockValidator;
|
||||
private readonly ShuffleTracksQueryHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly ShuffleTracksQueryFixture _shuffleTracksQueryFixture = new();
|
||||
private readonly ShuffleTrackRowFixture _shuffleTrackRowFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ShuffleTracksQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public ShuffleTracksQueryHandlerTests()
|
||||
{
|
||||
_mockTrackRepository = Substitute.For<ITrackRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<ShuffleTracksQuery>>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
// Default stubs: the current user is authenticated and the library ownership policy allows access.
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockValidator.Validate(Arg.Any<ShuffleTracksQuery>()).Returns([]);
|
||||
|
||||
_sut = new ShuffleTracksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRepositoryReturnsTracks_ShouldReturnMappedResponses()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create();
|
||||
Guid firstTrackId = Guid.NewGuid();
|
||||
Guid secondTrackId = Guid.NewGuid();
|
||||
Guid firstAlbumId = Guid.NewGuid();
|
||||
Guid secondAlbumId = Guid.NewGuid();
|
||||
Guid firstArtistId = Guid.NewGuid();
|
||||
Guid secondArtistId = Guid.NewGuid();
|
||||
List<ShuffleTrackRowDto> rows =
|
||||
[
|
||||
_shuffleTrackRowFixture.Create(
|
||||
trackId: firstTrackId,
|
||||
title: "Bohemian Rhapsody",
|
||||
durationInSeconds: 355,
|
||||
albumId: firstAlbumId,
|
||||
albumTitle: "A Night at the Opera",
|
||||
artistId: firstArtistId,
|
||||
coverPath: "a-night-at-the-opera-cover.jpg"),
|
||||
_shuffleTrackRowFixture.Create(
|
||||
trackId: secondTrackId,
|
||||
title: "Love of My Life",
|
||||
durationInSeconds: 219,
|
||||
albumId: secondAlbumId,
|
||||
albumTitle: "A Night at the Opera",
|
||||
artistId: secondArtistId,
|
||||
includeCoverPath: false)
|
||||
];
|
||||
_mockTrackRepository.GetShuffleTracksLiteAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<Guid?>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<ShuffleTrackRowDto>>(rows));
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Equal(firstTrackId, result.Value[0].TrackId);
|
||||
Assert.Equal("Bohemian Rhapsody", result.Value[0].Title);
|
||||
Assert.Equal(355, result.Value[0].DurationInSeconds);
|
||||
Assert.Equal(firstAlbumId, result.Value[0].AlbumId);
|
||||
Assert.Equal("A Night at the Opera", result.Value[0].AlbumTitle);
|
||||
Assert.Equal(firstArtistId, result.Value[0].ArtistId);
|
||||
Assert.Equal("a-night-at-the-opera-cover.jpg", result.Value[0].CoverPath);
|
||||
Assert.Equal(secondTrackId, result.Value[1].TrackId);
|
||||
Assert.Equal("Love of My Life", result.Value[1].Title);
|
||||
Assert.Equal(219, result.Value[1].DurationInSeconds);
|
||||
Assert.Equal(secondAlbumId, result.Value[1].AlbumId);
|
||||
Assert.Equal("A Night at the Opera", result.Value[1].AlbumTitle);
|
||||
Assert.Equal(secondArtistId, result.Value[1].ArtistId);
|
||||
Assert.Null(result.Value[1].CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTracksAreRequested_ShouldQueryRepositoryWithParsedLibraryScopeAndCount()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
count: 25,
|
||||
artistId: artistId,
|
||||
albumId: albumId,
|
||||
excludedTrackIds: [Guid.NewGuid(), Guid.NewGuid()]);
|
||||
CancellationToken cancellationToken = new();
|
||||
_mockTrackRepository.GetShuffleTracksLiteAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<Guid?>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<ShuffleTrackRowDto>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockTrackRepository.Received(1).GetShuffleTracksLiteAsync(
|
||||
libraryId,
|
||||
artistId,
|
||||
albumId,
|
||||
Arg.Is<IReadOnlyCollection<Guid>>(excludedIds => excludedIds.Count == 2),
|
||||
query.Count,
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenExcludedTrackIdsAreNull_ShouldQueryRepositoryWithAnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(includeExcludedTrackIds: false);
|
||||
_mockTrackRepository.GetShuffleTracksLiteAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<Guid?>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<ShuffleTrackRowDto>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockTrackRepository.Received(1).GetShuffleTracksLiteAsync(
|
||||
Arg.Any<Guid>(),
|
||||
Arg.Any<Guid?>(),
|
||||
Arg.Any<Guid?>(),
|
||||
Arg.Is<IReadOnlyCollection<Guid>>(excludedIds => excludedIds.Count == 0),
|
||||
Arg.Any<int>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenExcludedTrackIdsContainEmptyAndRepeatedIds_ShouldQueryRepositoryWithTheDistinctNonEmptyIds()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstTrackId = Guid.NewGuid();
|
||||
Guid secondTrackId = Guid.NewGuid();
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(
|
||||
excludedTrackIds: [firstTrackId, Guid.Empty, secondTrackId, firstTrackId]);
|
||||
_mockTrackRepository.GetShuffleTracksLiteAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<Guid?>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<ShuffleTrackRowDto>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockTrackRepository.Received(1).GetShuffleTracksLiteAsync(
|
||||
Arg.Any<Guid>(),
|
||||
Arg.Any<Guid?>(),
|
||||
Arg.Any<Guid?>(),
|
||||
Arg.Is<IReadOnlyCollection<Guid>>(excludedIds =>
|
||||
excludedIds.Count == 2 &&
|
||||
excludedIds.Contains(firstTrackId) &&
|
||||
excludedIds.Contains(secondTrackId) &&
|
||||
!excludedIds.Contains(Guid.Empty)),
|
||||
Arg.Any<int>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryIsEvaluated_ShouldUseTheParsedLibraryIdAndTheCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(libraryId: libraryId.ToString());
|
||||
_mockTrackRepository.GetShuffleTracksLiteAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<Guid?>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<ShuffleTrackRowDto>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId,
|
||||
Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<ShuffleTracksQuery>()).Returns([Errors.Music.ShuffleTrackCountMustBeGreaterThanZero]);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.ShuffleTrackCountMustBeGreaterThanZero, result.FirstError);
|
||||
await _mockTrackRepository.DidNotReceive().GetShuffleTracksLiteAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<Guid?>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockTrackRepository.DidNotReceive().GetShuffleTracksLiteAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<Guid?>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(libraryId: libraryId.ToString());
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId,
|
||||
Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockTrackRepository.DidNotReceive().GetShuffleTracksLiteAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<Guid?>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create();
|
||||
_mockTrackRepository.GetShuffleTracksLiteAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<Guid?>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRepositoryReturnsNoTracks_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create();
|
||||
_mockTrackRepository.GetShuffleTracksLiteAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<Guid?>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<ShuffleTrackRowDto>>([]));
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<ShuffleTrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ShuffleTracksQueryValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksQueryValidatorTests
|
||||
{
|
||||
private readonly ShuffleTracksQueryFixture _shuffleTracksQueryFixture = new();
|
||||
private readonly ShuffleTracksQueryValidator _validator = new();
|
||||
|
||||
[Theory]
|
||||
[InlineData(1)] // the smallest allowed selection
|
||||
[InlineData(500)] // the largest allowed selection
|
||||
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError(int count)
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(
|
||||
count: count,
|
||||
includeArtistId: false,
|
||||
includeAlbumId: false,
|
||||
includeExcludedTrackIds: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.Music.ShuffleTrackCountMustBeGreaterThanZero);
|
||||
result.ShouldNotHaveValidationError(Errors.Music.ShuffleTrackCountMustBeAtMost500);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData(" ")] // whitespace route value
|
||||
[InlineData("not-a-guid")] // non-Guid route value
|
||||
[InlineData("' OR '1'='1")] // injection payload that is not a Guid
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)] // no track is requested
|
||||
[InlineData(-1)] // a negative selection size
|
||||
[InlineData(-500)] // a large negative selection size
|
||||
public void Validate_WhenCountIsNotPositive_ShouldHaveValidationError(int count)
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(count: count);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.ShuffleTrackCountMustBeGreaterThanZero);
|
||||
result.ShouldNotHaveValidationError(Errors.Music.ShuffleTrackCountMustBeAtMost500);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(501)] // one more than the documented maximum
|
||||
[InlineData(1000)] // well above the documented maximum
|
||||
[InlineData(int.MaxValue)] // the largest possible value
|
||||
public void Validate_WhenCountExceedsMaximum_ShouldHaveValidationError(int count)
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(count: count);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.ShuffleTrackCountMustBeAtMost500);
|
||||
result.ShouldNotHaveValidationError(Errors.Music.ShuffleTrackCountMustBeGreaterThanZero);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenArtistIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(artistId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenArtistIdIsNull_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(includeArtistId: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenAlbumIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(albumId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenAlbumIdIsNull_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(includeAlbumId: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenExcludedTrackIdsAreNull_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(includeExcludedTrackIds: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
// The validator has no rule for the exclusion list, because excluding tracks can never make a valid selection invalid.
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenExcludedTrackIdsAreEmpty_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(excludedTrackIds: []);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenExcludedTrackIdsContainEmptyOrDuplicatedIds_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
Guid trackId = Guid.NewGuid();
|
||||
ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(excludedTrackIds: [trackId, Guid.Empty, trackId]);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
// The exclusion list is normalized by the handler instead, so the validator reports no error for empty or repeated entries.
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ShuffleTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<ShuffleTracksQuery, Result<IReadOnlyList<ShuffleTrackResponse>>> _mockHandler;
|
||||
private readonly ShuffleTracksEndpoint _sut;
|
||||
private readonly ShuffleTracksRequestFixture _shuffleTracksRequestFixture = new();
|
||||
private readonly ShuffleTrackResponseFixture _shuffleTrackResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ShuffleTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ShuffleTracksEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<ShuffleTracksQuery, Result<IReadOnlyList<ShuffleTrackResponse>>>>();
|
||||
_sut = FastEndpoints.Factory.Create<ShuffleTracksEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithTrackResponses()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<ShuffleTrackResponse> expectedResponse = _shuffleTrackResponseFixture.CreateMany(3);
|
||||
_mockHandler.HandleAsync(Arg.Any<ShuffleTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<ShuffleTrackResponse>>(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_shuffleTracksRequestFixture.Create(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<IReadOnlyList<ShuffleTrackResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<ShuffleTrackResponse>>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Errors.Music.ShuffleTrackCountMustBeAtMost500;
|
||||
_mockHandler.HandleAsync(Arg.Any<ShuffleTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_shuffleTracksRequestFixture.Create(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "ShuffleTrackCountMustBeAtMost500" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsForbiddenError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ShuffleTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Authorization.NotAuthorized);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_shuffleTracksRequestFixture.Create(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
|
||||
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnNotFoundProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ShuffleTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.NotFound("Library.NotFound", "LibraryNotFound"));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_shuffleTracksRequestFixture.Create(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
|
||||
Assert.Equal("Library.NotFound", problemDetailsBody.Title);
|
||||
Assert.Equal("LibraryNotFound", problemDetailsBody.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendQueryWithTheRouteAndRequestValues()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid excludedTrackId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(
|
||||
count: 25,
|
||||
artistId: artistId,
|
||||
albumId: albumId,
|
||||
excludedTrackIds: [excludedTrackId]);
|
||||
_mockHandler.HandleAsync(Arg.Any<ShuffleTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<ShuffleTrackResponse>>([]));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<ShuffleTracksQuery>(query =>
|
||||
query.LibraryId == libraryId.ToString() &&
|
||||
query.Count == 25 &&
|
||||
query.ArtistId == artistId &&
|
||||
query.AlbumId == albumId &&
|
||||
query.ExcludedTrackIds != null &&
|
||||
query.ExcludedTrackIds.Count == 1 &&
|
||||
query.ExcludedTrackIds[0] == excludedTrackId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ShuffleTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<ShuffleTrackResponse>>([]));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(_shuffleTracksRequestFixture.Create(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<ShuffleTracksQuery>(query => query.LibraryId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithTheRawRouteValue()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ShuffleTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<ShuffleTrackResponse>>([]));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "'; DROP TABLE Tracks; --";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(_shuffleTracksRequestFixture.Create(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<ShuffleTracksQuery>(query => query.LibraryId == "'; DROP TABLE Tracks; --"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<ShuffleTracksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From<IReadOnlyList<ShuffleTrackResponse>>(_shuffleTrackResponseFixture.CreateMany(2));
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(_shuffleTracksRequestFixture.Create(), cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
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 Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ShuffleTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly ShuffleTracksEndpoint _sut;
|
||||
private readonly ShuffleTracksRequestFixture _shuffleTracksRequestFixture = new();
|
||||
private readonly MusicShuffleTrackDtoFixture _musicShuffleTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ShuffleTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ShuffleTracksEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<ShuffleTracksEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsTracks_ShouldReturnSuccessJsonWithTheMappedTracks()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(libraryId: libraryId);
|
||||
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");
|
||||
_mockApiHttpClient.PostAsync<List<MusicShuffleTrackDto>, ShuffleTracksRequest>(Arg.Any<string>(), Arg.Any<ShuffleTracksRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns([expectedTrack]);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = jsonDocument.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());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsNoTracks_ShouldReturnAnEmptyDataArray()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
|
||||
_mockApiHttpClient.PostAsync<List<MusicShuffleTrackDto>, ShuffleTracksRequest>(Arg.Any<string>(), Arg.Any<ShuffleTracksRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = jsonDocument.RootElement.GetProperty("data");
|
||||
Assert.Equal(JsonValueKind.Array, data.ValueKind);
|
||||
Assert.Equal(0, data.GetArrayLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldPostTheRequestToTheLibraryShuffleEndpoint()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid firstExcludedTrackId = Guid.NewGuid();
|
||||
Guid secondExcludedTrackId = Guid.NewGuid();
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
count: 25,
|
||||
artistId: artistId,
|
||||
albumId: albumId,
|
||||
excludedTrackIds: [firstExcludedTrackId, secondExcludedTrackId]);
|
||||
string expectedEndpoint = ApiRoutes.Music.SHUFFLE_TRACKS.Replace("{libraryId}", libraryId.ToString());
|
||||
_mockApiHttpClient.PostAsync<List<MusicShuffleTrackDto>, ShuffleTracksRequest>(Arg.Any<string>(), Arg.Any<ShuffleTracksRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<List<MusicShuffleTrackDto>, ShuffleTracksRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Is<ShuffleTracksRequest>(forwarded =>
|
||||
forwarded.LibraryId == libraryId &&
|
||||
forwarded.Count == 25 &&
|
||||
forwarded.ArtistId == artistId &&
|
||||
forwarded.AlbumId == albumId &&
|
||||
forwarded.ExcludedTrackIds != null &&
|
||||
forwarded.ExcludedTrackIds.SequenceEqual(new[] { firstExcludedTrackId, secondExcludedTrackId })),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockApiHttpClient.PostAsync<List<MusicShuffleTrackDto>, ShuffleTracksRequest>(Arg.Any<string>(), Arg.Any<ShuffleTracksRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return new List<MusicShuffleTrackDto> { _musicShuffleTrackDtoFixture.Create() };
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cancellationTokenSource.Token);
|
||||
await operationStarted.Task;
|
||||
cancellationTokenSource.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user