Adds cover update endpoints for music artists and albums.

This commit is contained in:
BinaryAlley committed 2026-10-13 13:26:41 +03:00
1 parent 4f43bf352b
commit 4ceb8f7360
32 files changed
+4892

No files matched your search

@@ -0,0 +1,10 @@
PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/{{$guid}}/cover
Authorization: Bearer {{ACCESS_TOKEN}}
Content-Type: multipart/form-data; boundary=LuminaBoundary
--LuminaBoundary
Content-Disposition: form-data; name="cover"; filename="cover.jpg"
Content-Type: image/jpeg
< ./cover.jpg
--LuminaBoundary--
@@ -0,0 +1,10 @@
PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{{$guid}}/cover
Authorization: Bearer {{ACCESS_TOKEN}}
Content-Type: multipart/form-data; boundary=LuminaBoundary
--LuminaBoundary
Content-Disposition: form-data; name="cover"; filename="cover.jpg"
Content-Type: image/jpeg
< ./cover.jpg
--LuminaBoundary--
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
using System.IO;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
/// <summary>
/// Command for updating the cover image of an existing album.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library the album belongs to, taken from the route.</param>
/// <param name="ArtistId">The unique identifier of the artist the album belongs to, taken from the route.</param>
/// <param name="AlbumId">The unique identifier of the album whose cover image is updated, taken from the route.</param>
/// <param name="Cover">The stream of the uploaded cover image file.</param>
/// <param name="FileName">The name of the uploaded cover image file.</param>
[DebuggerDisplay("AlbumId: {AlbumId} FileName: {FileName}")]
public record UpdateAlbumCoverCommand(
string? LibraryId,
string? ArtistId,
string? AlbumId,
Stream? Cover,
string? FileName
) : ICommand;
@@ -0,0 +1,198 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.UoW;
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.Artwork;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
/// <summary>
/// Handler for the command to update the cover image of an existing album.
/// </summary>
public class UpdateAlbumCoverCommandHandler : ICommandHandler<UpdateAlbumCoverCommand, Result<UpdateAlbumCoverResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMusicArtworkService _musicArtworkService;
private readonly IPathService _pathService;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<UpdateAlbumCoverCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCoverCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="musicArtworkService">Injected service for storing the artwork of a music library item.</param>
/// <param name="pathService">Injected service for handling file system paths.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdateAlbumCoverCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService, IPathService pathService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<UpdateAlbumCoverCommand> validator)
{
_unitOfWork = unitOfWork;
_musicArtworkService = musicArtworkService;
_pathService = pathService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to update the cover image of an existing album.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the response carrying the relative path of the stored cover image, or an error message.
/// </returns>
public async Task<Result<UpdateAlbumCoverResponse>> HandleAsync(UpdateAlbumCoverCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifiers are non-empty Guids before this point.
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null)
return DomainErrors.Music.AlbumNotFound;
AlbumEntity existingAlbum = getAlbumResult.Value;
// Resource scoping: the album must belong to the library and the artist named by the route, so that an album can never be edited through
// another library's or artist's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere.
if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId)
return DomainErrors.Music.AlbumNotFound;
// Admins can update the albums of all libraries; for everyone else, only the albums of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(existingAlbum.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// The artwork is stored under the library and artist segments, so their names are resolved to keep the location consistent with the scanned artwork.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingAlbum.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
string libraryName = getLibraryResult.Value.Title;
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(existingAlbum.ArtistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getArtistResult.IsFailure)
return getArtistResult.Errors;
string artistName = getArtistResult.Value?.Name ?? string.Empty;
// The artwork of the album is stored under the directory of its release type, mirroring the structure of the scanned files, so that a
// re-uploaded cover replaces the cover stored for the album at its standardized location instead of writing a second copy elsewhere.
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
string? existingCoverPath = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault();
string? releaseTypeName = ExtractReleaseTypeDirectoryName(existingCoverPath, artistName)
?? (existingAlbum.ReleaseTypes.Count > 0 ? existingAlbum.ReleaseTypes[0].ReleaseType.ToString() : null);
Result<string> storeArtworkResult = await _musicArtworkService.SaveAlbumArtworkAsync(
existingAlbum.LibraryId,
existingAlbum.Id,
libraryName,
artistName,
existingAlbum.Title,
command.Cover!,
command.FileName!,
releaseTypeName,
cancellationToken).ConfigureAwait(false);
if (storeArtworkResult.IsFailure)
return storeArtworkResult.Errors;
// The stored cover of the album is replaced as a whole: when the new cover is stored under a different name than the previous one
// (for example a png replacing a jpg), the previous file is removed, so that no orphaned artwork is left on disk without a reference.
if (!string.IsNullOrWhiteSpace(existingCoverPath) && existingCoverPath != storeArtworkResult.Value)
{
Result<Deleted> deleteResult = _musicArtworkService.DeleteStoredArtwork(existingCoverPath);
if (deleteResult.IsFailure)
return deleteResult.Errors;
}
// Map the newly stored cover image onto the artwork of the album, replacing the existing cover or adding a new one.
Result<Updated> upsertResult = await _unitOfWork.MusicArtworkRepository.UpsertCoverAsync(
MusicArtworkOwnerType.Album, albumId, storeArtworkResult.Value, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return upsertResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return new UpdateAlbumCoverResponse(storeArtworkResult.Value);
}
/// <summary>
/// Resolves the name of the release type directory the artwork of an album is stored under, from the relative path of its existing cover.
/// </summary>
/// <param name="coverRelativePath">The relative path of the existing cover image of the album, or <see langword="null"/> when the album has no cover.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <returns>The name of the on-disk release type directory, or <see langword="null"/> when the album does not use one.</returns>
private string? ExtractReleaseTypeDirectoryName(string? coverRelativePath, string artistName)
{
if (string.IsNullOrWhiteSpace(coverRelativePath))
return null;
// The path is media/music/{library}/{artist}[/{releaseType}]/{album}/{file}, so the segment right before the album directory is the release
// type directory when the album uses one, and the artist directory otherwise. An artist whose name happens to match a release type, like
// "Live", must not be mistaken for one, so the segment is only accepted as a release type when it is not the directory of the artist.
string[] segments = coverRelativePath.Split(_pathService.PathSeparator, StringSplitOptions.RemoveEmptyEntries);
if (segments.Length < 3)
return null;
string candidate = segments[^3];
if (IsArtistDirectory(candidate, artistName))
return null;
return Enum.TryParse(candidate, ignoreCase: true, out MusicReleaseType releaseType) && Enum.IsDefined(releaseType) ? candidate : null;
}
/// <summary>
/// Checks whether the provided path segment is the artwork directory of the artist of the album.
/// </summary>
/// <param name="pathSegment">The path segment to be checked.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <returns><see langword="true"/> when the segment is the artwork directory of the artist, <see langword="false"/> otherwise.</returns>
private bool IsArtistDirectory(string pathSegment, string artistName)
{
if (string.IsNullOrWhiteSpace(artistName))
return false;
Result<PathSegment> artistSegmentResult = _pathService.SanitizeSegment(artistName);
return artistSegmentResult.IsSuccess
&& string.Equals(pathSegment, artistSegmentResult.Value.Name, StringComparison.OrdinalIgnoreCase);
}
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdateAlbumCoverCommand"/>.
/// </summary>
public class UpdateAlbumCoverCommandValidator : AbstractValidator<UpdateAlbumCoverCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCoverCommandValidator"/> class.
/// </summary>
public UpdateAlbumCoverCommandValidator()
{
// Validates the identifier of the media library the album belongs to, taken from the route.
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the identifier of the artist the album belongs to, taken from the route.
RuleFor(command => command.ArtistId)
.NotEmpty()
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
RuleFor(command => command.ArtistId)
.Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
.When(command => command.ArtistId is not null && command.ArtistId.Length > 0)
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
// Validates the identifier of the album whose cover image is updated, taken from the route.
RuleFor(command => command.AlbumId)
.NotEmpty()
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
RuleFor(command => command.AlbumId)
.Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty)
.When(command => command.AlbumId is not null && command.AlbumId.Length > 0)
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
// Validates the uploaded cover image.
RuleFor(command => command.Cover)
.NotNull()
.WithError(Errors.Music.CoverCannotBeNull);
RuleFor(command => command.FileName)
.NotEmpty()
.When(command => command.Cover is not null)
.WithError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
using System.IO;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
/// <summary>
/// Command for updating the cover image of an existing artist.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library this artist belongs to, taken from the route.</param>
/// <param name="ArtistId">The unique identifier of the artist whose cover image is updated, taken from the route.</param>
/// <param name="Cover">The stream of the uploaded cover image file.</param>
/// <param name="FileName">The name of the uploaded cover image file.</param>
[DebuggerDisplay("ArtistId: {ArtistId} FileName: {FileName}")]
public record UpdateArtistCoverCommand(
string? LibraryId,
string? ArtistId,
Stream? Cover,
string? FileName
) : ICommand;
@@ -0,0 +1,144 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.UoW;
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.Artwork;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
/// <summary>
/// Handler for the command to update the cover image of an existing artist.
/// </summary>
public class UpdateArtistCoverCommandHandler : ICommandHandler<UpdateArtistCoverCommand, Result<UpdateArtistCoverResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMusicArtworkService _musicArtworkService;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<UpdateArtistCoverCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCoverCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="musicArtworkService">Injected service for storing the artwork of a music library item.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdateArtistCoverCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<UpdateArtistCoverCommand> validator)
{
_unitOfWork = unitOfWork;
_musicArtworkService = musicArtworkService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to update the cover image of an existing artist.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the response carrying the relative path of the stored cover image, or an error message.
/// </returns>
public async Task<Result<UpdateArtistCoverResponse>> HandleAsync(UpdateArtistCoverCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifiers are non-empty Guids before this point.
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getArtistResult.IsFailure)
return getArtistResult.Errors;
if (getArtistResult.Value is null)
return DomainErrors.Music.ArtistNotFound;
ArtistEntity existingArtist = getArtistResult.Value;
// Resource scoping: the artist must belong to the library named by the route, so that an artist can never be edited through another
// library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library.
if (existingArtist.LibraryId != libraryId)
return DomainErrors.Music.ArtistNotFound;
// Admins can update the artists of all libraries; for everyone else, only the artists of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// The artwork is stored under the library and artist segments, so their names are resolved to keep the location consistent with the scanned artwork.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingArtist.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
string libraryName = getLibraryResult.Value.Title;
// The existing cover of the artist is looked up, so that the previous file can be replaced as a whole instead of being left orphaned on disk.
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
string? existingCoverPath = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault();
Result<string> storeArtworkResult = await _musicArtworkService.SaveArtistArtworkAsync(
existingArtist.LibraryId,
libraryName,
existingArtist.Name,
command.Cover!,
command.FileName!,
cancellationToken).ConfigureAwait(false);
if (storeArtworkResult.IsFailure)
return storeArtworkResult.Errors;
// The stored cover of the artist is replaced as a whole: when the new cover is stored under a different name than the previous one
// (for example a png replacing a jpg), the previous file is removed, so that no orphaned artwork is left on disk without a reference.
if (!string.IsNullOrWhiteSpace(existingCoverPath) && existingCoverPath != storeArtworkResult.Value)
{
Result<Deleted> deleteResult = _musicArtworkService.DeleteStoredArtwork(existingCoverPath);
if (deleteResult.IsFailure)
return deleteResult.Errors;
}
// Map the newly stored cover image onto the artwork of the artist, replacing the existing cover or adding a new one.
Result<Updated> upsertResult = await _unitOfWork.MusicArtworkRepository.UpsertCoverAsync(
MusicArtworkOwnerType.Artist, artistId, storeArtworkResult.Value, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return upsertResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return new UpdateArtistCoverResponse(storeArtworkResult.Value);
}
}
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdateArtistCoverCommand"/>.
/// </summary>
public class UpdateArtistCoverCommandValidator : AbstractValidator<UpdateArtistCoverCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCoverCommandValidator"/> class.
/// </summary>
public UpdateArtistCoverCommandValidator()
{
// Validates the identifier of the media library the artist belongs to, taken from the route.
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the identifier of the artist whose cover image is updated, taken from the route.
RuleFor(command => command.ArtistId)
.NotEmpty()
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
RuleFor(command => command.ArtistId)
.Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
.When(command => command.ArtistId is not null && command.ArtistId.Length > 0)
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
// Validates the uploaded cover image.
RuleFor(command => command.Cover)
.NotNull()
.WithError(Errors.Music.CoverCannotBeNull);
RuleFor(command => command.FileName)
.NotEmpty()
.When(command => command.Cover is not null)
.WithError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
}
}
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
/// <summary>
/// Represents a response of an update album cover operation.
/// </summary>
/// <param name="CoverPath">The relative path of the stored cover image.</param>
[DebuggerDisplay("CoverPath: {CoverPath}")]
public record UpdateAlbumCoverResponse(
string CoverPath
);
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
/// <summary>
/// Represents a response of an update artist cover operation.
/// </summary>
/// <param name="CoverPath">The relative path of the stored cover image.</param>
[DebuggerDisplay("CoverPath: {CoverPath}")]
public record UpdateArtistCoverResponse(
string CoverPath
);
@@ -65,5 +65,6 @@ public static partial class Errors
public static Error IsniValueCannotBeEmpty => Error.Validation(description: nameof(IsniValueCannotBeEmpty));
public static Error IsniValueMustBeMaximum20CharactersLong => Error.Validation(description: nameof(IsniValueMustBeMaximum20CharactersLong));
public static Error WorkTitleCannotBeEmpty => Error.Validation(description: nameof(WorkTitleCannotBeEmpty));
public static Error CoverCannotBeNull => Error.Validation(description: nameof(CoverCannotBeNull));
}
}
@@ -15,6 +15,7 @@ public static partial class ApiRoutes
public const string ADD_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums";
public const string GET_ALBUM_BY_ID = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
public const string UPDATE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
public const string UPDATE_ALBUM_COVER = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover";
public const string DELETE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
public const string GET_ALBUM_TRACKS = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks";
public const string GET_ALBUM_TRACKS_LITE = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite";
@@ -15,6 +15,7 @@ public static partial class ApiRoutes
public const string GET_ARTISTS_LITE = "/libraries/{libraryId}/artists/lite";
public const string ADD_ARTIST = "/libraries/{libraryId}/artists";
public const string UPDATE_ARTIST = "/libraries/{libraryId}/artists/{artistId}";
public const string UPDATE_ARTIST_COVER = "/libraries/{libraryId}/artists/{artistId}/cover";
public const string DELETE_ARTIST = "/libraries/{libraryId}/artists/{artistId}";
}
}
@@ -0,0 +1,82 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover</c> route.
/// </summary>
public class UpdateAlbumCoverEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
{
private readonly ICommandHandler<UpdateAlbumCoverCommand, Result<UpdateAlbumCoverResponse>> _updateAlbumCoverCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpoint"/> class.
/// </summary>
/// <param name="updateAlbumCoverCommandHandler">Injected service for handling update album cover commands.</param>
public UpdateAlbumCoverEndpoint(ICommandHandler<UpdateAlbumCoverCommand, Result<UpdateAlbumCoverResponse>> updateAlbumCoverCommandHandler)
{
_updateAlbumCoverCommandHandler = updateAlbumCoverCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.PUT);
Routes(ApiRoutes.Albums.UPDATE_ALBUM_COVER);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Updates the cover image of the album with the image uploaded in the multipart form of the request.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
{
// Take the identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString();
string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString();
IFormFile? cover = null;
if (HttpContext.Request.HasFormContentType)
{
try
{
// The cover is the first file of the multipart form; a multipart body without any file cannot be parsed as a form,
// so a malformed upload is treated as a missing cover, which the command validator reports.
cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null;
}
catch (InvalidDataException)
{
cover = null;
}
}
// The cover stream must stay open while the handler stores the image, and is disposed as soon as the handler returns.
UpdateAlbumCoverCommand command = new(libraryId, artistId, albumId, cover?.OpenReadStream(), cover?.FileName);
try
{
Result<UpdateAlbumCoverResponse> result = await _updateAlbumCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
finally
{
command.Cover?.Dispose();
}
}
}
@@ -0,0 +1,108 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
/// <summary>
/// Class used for providing a textual description for the <see cref="UpdateAlbumCoverEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateAlbumCoverEndpointSummary : Summary<UpdateAlbumCoverEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpointSummary"/> class.
/// </summary>
public UpdateAlbumCoverEndpointSummary()
{
Summary = "Updates the cover image of an album.";
Description = "Updates the cover image of the album identified by the route, with the image uploaded in the multipart form of the request.";
Response(200, "The relative path of the stored cover image is returned.",
example: new UpdateAlbumCoverResponse(
CoverPath: "/media/music/music-3f2504e0-4f89-41d3-9a0c-0305e82c3301/Queen-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/A Night at the Opera-7c1d2e3f-4a5b-6c7d-8e9f-0a1b2c3d4e5f/cover.jpg"
)
);
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Authentication failed",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover"
}
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the album or its media library does not exist.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "AlbumNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
}
);
Response(422, "The request did not pass validation checks, either on the request itself or while storing the uploaded cover image.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"ArtistIdCannotBeEmpty",
"AlbumIdCannotBeEmpty",
"CoverCannotBeNull",
"FileNameCannotBeEmpty",
"FileTooLarge",
"CoverFileMustBeAnImage"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,81 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/cover</c> route.
/// </summary>
public class UpdateArtistCoverEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
{
private readonly ICommandHandler<UpdateArtistCoverCommand, Result<UpdateArtistCoverResponse>> _updateArtistCoverCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpoint"/> class.
/// </summary>
/// <param name="updateArtistCoverCommandHandler">Injected service for handling update artist cover commands.</param>
public UpdateArtistCoverEndpoint(ICommandHandler<UpdateArtistCoverCommand, Result<UpdateArtistCoverResponse>> updateArtistCoverCommandHandler)
{
_updateArtistCoverCommandHandler = updateArtistCoverCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.PUT);
Routes(ApiRoutes.Artists.UPDATE_ARTIST_COVER);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Updates the cover image of the artist with the image uploaded in the multipart form of the request.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
{
// Take the identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString();
IFormFile? cover = null;
if (HttpContext.Request.HasFormContentType)
{
try
{
// The cover is the first file of the multipart form; a multipart body without any file cannot be parsed as a form,
// so a malformed upload is treated as a missing cover, which the command validator reports.
cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null;
}
catch (InvalidDataException)
{
cover = null;
}
}
// The cover stream must stay open while the handler stores the image, and is disposed as soon as the handler returns.
UpdateArtistCoverCommand command = new(libraryId, artistId, cover?.OpenReadStream(), cover?.FileName);
try
{
Result<UpdateArtistCoverResponse> result = await _updateArtistCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
finally
{
command.Cover?.Dispose();
}
}
}
@@ -0,0 +1,107 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
/// <summary>
/// Class used for providing a textual description for the <see cref="UpdateArtistCoverEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistCoverEndpointSummary : Summary<UpdateArtistCoverEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpointSummary"/> class.
/// </summary>
public UpdateArtistCoverEndpointSummary()
{
Summary = "Updates the cover image of an artist.";
Description = "Updates the cover image of the artist identified by the route, with the image uploaded in the multipart form of the request.";
Response(200, "The relative path of the stored cover image is returned.",
example: new UpdateArtistCoverResponse(
CoverPath: "/media/music/music-3f2504e0-4f89-41d3-9a0c-0305e82c3301/Queen-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg"
)
);
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Authentication failed",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover"
}
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the artist or its media library does not exist.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "ArtistNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
}
);
Response(422, "The request did not pass validation checks, either on the request itself or while storing the uploaded cover image.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"ArtistIdCannotBeEmpty",
"CoverCannotBeNull",
"FileNameCannotBeEmpty",
"FileTooLarge",
"CoverFileMustBeAnImage"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
+2
View File
@@ -265,6 +265,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "albums", "albums", "{B4DF8E
..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracks.http = ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracks.http
..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracksLite.http = ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracksLite.http
..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbum.http = ..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbum.http
..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbumCover.http = ..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbumCover.http
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "artists", "artists", "{F3818697-E304-491D-8BF3-4DAA1733B5F5}"
@@ -277,6 +278,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "artists", "artists", "{F381
..\docs\technical\requests\library\audio-library\music-library\artists\GetArtists.http = ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtists.http
..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistsLite.http = ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistsLite.http
..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtist.http = ..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtist.http
..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtistCover.http = ..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtistCover.http
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tracks", "tracks", "{B1B657B1-60DC-4E22-89D2-6212154D6BA8}"
@@ -0,0 +1,72 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
/// <summary>
/// Fixture class for the <see cref="UpdateAlbumCoverCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateAlbumCoverCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="UpdateAlbumCoverCommand"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the album belongs to.</param>
/// <param name="artistId">Optional. The Id of the artist the album belongs to.</param>
/// <param name="albumId">Optional. The Id of the album whose cover is updated.</param>
/// <param name="cover">Optional. The stream of the uploaded cover image file.</param>
/// <param name="fileName">Optional. The name of the uploaded cover image file.</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="includeCover">Whether the cover stream should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeFileName">Whether the file name should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="UpdateAlbumCoverCommand"/>.</returns>
public UpdateAlbumCoverCommand Create(
string? libraryId = null,
string? artistId = null,
string? albumId = null,
Stream? cover = null,
string? fileName = null,
bool includeLibraryId = true,
bool includeArtistId = true,
bool includeAlbumId = true,
bool includeCover = true,
bool includeFileName = true)
{
return new UpdateAlbumCoverCommand(
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null,
includeCover ? (cover ?? CreateCoverStream()) : null,
includeFileName ? (fileName ?? "cover.jpg") : null);
}
/// <summary>
/// Creates a list of <see cref="UpdateAlbumCoverCommand"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="UpdateAlbumCoverCommand"/> instances.</returns>
public List<UpdateAlbumCoverCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Creates an in-memory stream carrying a minimal file payload.
/// </summary>
/// <returns>A non-empty in-memory stream.</returns>
private static Stream CreateCoverStream()
{
byte[] payload = Encoding.UTF8.GetBytes("fake cover payload");
return new MemoryStream(payload);
}
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
/// <summary>
/// Fixture class for the <see cref="UpdateArtistCoverCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistCoverCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="UpdateArtistCoverCommand"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the artist belongs to.</param>
/// <param name="artistId">Optional. The Id of the artist whose cover is updated.</param>
/// <param name="cover">Optional. The stream of the uploaded cover image file.</param>
/// <param name="fileName">Optional. The name of the uploaded cover image file.</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="includeCover">Whether the cover stream should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeFileName">Whether the file name should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="UpdateArtistCoverCommand"/>.</returns>
public UpdateArtistCoverCommand Create(
string? libraryId = null,
string? artistId = null,
Stream? cover = null,
string? fileName = null,
bool includeLibraryId = true,
bool includeArtistId = true,
bool includeCover = true,
bool includeFileName = true)
{
return new UpdateArtistCoverCommand(
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
includeCover ? (cover ?? CreateCoverStream()) : null,
includeFileName ? (fileName ?? "cover.jpg") : null);
}
/// <summary>
/// Creates a list of <see cref="UpdateArtistCoverCommand"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="UpdateArtistCoverCommand"/> instances.</returns>
public List<UpdateArtistCoverCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Creates an in-memory stream carrying a minimal file payload.
/// </summary>
/// <returns>A non-empty in-memory stream.</returns>
private static Stream CreateCoverStream()
{
byte[] payload = Encoding.UTF8.GetBytes("fake cover payload");
return new MemoryStream(payload);
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
/// <summary>
/// Fixture class for the <see cref="UpdateAlbumCoverResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateAlbumCoverResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="UpdateAlbumCoverResponse"/>.
/// </summary>
/// <param name="coverPath">Optional. The relative path of the stored cover image.</param>
/// <returns>The created <see cref="UpdateAlbumCoverResponse"/>.</returns>
public UpdateAlbumCoverResponse Create(string? coverPath = null)
{
return new UpdateAlbumCoverResponse(
coverPath ?? _faker.System.FilePath()
);
}
/// <summary>
/// Creates a list of <see cref="UpdateAlbumCoverResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<UpdateAlbumCoverResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
/// <summary>
/// Fixture class for the <see cref="UpdateArtistCoverResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistCoverResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="UpdateArtistCoverResponse"/>.
/// </summary>
/// <param name="coverPath">Optional. The relative path of the stored cover image.</param>
/// <returns>The created <see cref="UpdateArtistCoverResponse"/>.</returns>
public UpdateArtistCoverResponse Create(string? coverPath = null)
{
return new UpdateArtistCoverResponse(
coverPath ?? _faker.System.FilePath()
);
}
/// <summary>
/// Creates a list of <see cref="UpdateArtistCoverResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<UpdateArtistCoverResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,382 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
/// <summary>
/// Contains integration tests for the <see cref="UpdateAlbumCoverEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateAlbumCoverEndpointTests : 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 MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateAlbumCoverEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task UpdateAlbumCover_WhenCalledByOwnerWithValidImage_ShouldReplaceTheStoredCover()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumWithCoverAsync(userId, "/media/music/old-cover.jpg");
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
string storedPath = JsonSerializer.Deserialize<UpdateAlbumCoverResponse>(content, _jsonOptions)!.CoverPath;
Assert.False(string.IsNullOrWhiteSpace(storedPath));
Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
MusicArtworkEntity coverArtwork = dbContext.MusicArtwork
.Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId && artwork.ArtworkType == ArtworkType.Cover);
Assert.Equal(storedPath, coverArtwork.FileName);
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
}
[Fact]
public async Task UpdateAlbumCover_WhenAlbumHasNoExistingCover_ShouldCreateACoverArtwork()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
string storedPath = JsonSerializer.Deserialize<UpdateAlbumCoverResponse>(content, _jsonOptions)!.CoverPath;
Assert.False(string.IsNullOrWhiteSpace(storedPath));
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
MusicArtworkEntity coverArtwork = dbContext.MusicArtwork
.Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId && artwork.ArtworkType == ArtworkType.Cover);
Assert.Equal(storedPath, coverArtwork.FileName);
}
[Fact]
public async Task UpdateAlbumCover_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId);
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/cover";
// Act
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
// Assert
await AssertNotFoundAsync(response, "AlbumNotFound", url);
}
[Fact]
public async Task UpdateAlbumCover_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
Guid otherLibraryId = Guid.NewGuid();
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{artistId}/albums/{albumId}/cover";
// Act
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
// Assert
await AssertNotFoundAsync(response, "AlbumNotFound", url);
}
[Fact]
public async Task UpdateAlbumCover_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId);
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/cover";
// Act
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
// Assert
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
}
[Fact]
public async Task UpdateAlbumCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover";
// Act
HttpResponseMessage response = await unauthenticatedClient.PutAsync(url, CreateCoverForm("cover.png"));
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task UpdateAlbumCover_WhenNoFileIsUploaded_ShouldReturnUnprocessableEntityWithCoverCannotBeNull()
{
// Arrange
MultipartFormDataContent form = [];
form.Add(new StringContent("unrelated-field"), "unrelated-field");
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover";
// Act
HttpResponseMessage response = await _client.PutAsync(url, form);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, url, "CoverCannotBeNull");
}
[Fact]
public async Task UpdateAlbumCover_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
{
// Arrange
string url = $"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{Guid.NewGuid()}/albums/not-a-guid/cover";
// Act
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
}
/// <summary>
/// Creates a multipart form carrying a minimal PNG-like payload.
/// </summary>
/// <param name="fileName">The name of the uploaded file.</param>
/// <returns>A configured <see cref="MultipartFormDataContent"/> instance.</returns>
private static MultipartFormDataContent CreateCoverForm(string fileName)
{
// The payload only needs to carry the PNG signature in its first bytes and exceed the header detection buffer.
byte[] payload = new byte[100];
payload[0] = 137;
payload[1] = 80;
payload[2] = 78;
payload[3] = 71;
payload[4] = 13;
payload[5] = 10;
payload[6] = 26;
payload[7] = 10;
MultipartFormDataContent form = [];
ByteArrayContent fileContent = new(payload);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, "cover", fileName);
return form;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums that has no cover yet.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist and album.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums that already has a cover.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="existingCoverFileName">The relative path of the existing cover of the album.</param>
/// <returns>The Ids of the seeded library, artist and album.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumWithCoverAsync(Guid userId, string existingCoverFileName)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Cover, ordinal: 0, fileName: existingCoverFileName, status: ArtworkStatus.Enriched));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
{
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
}
/// <summary>
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="statusCode">The expected HTTP status code.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedType">The expected problem type URI.</param>
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
{
Assert.Equal(statusCode, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
Assert.Equal(expectedType, problemDetails["type"].GetString());
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
/// <summary>
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
}
/// <summary>
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,391 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
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.Artists.UpdateArtistCover;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
/// <summary>
/// Contains integration tests for the <see cref="UpdateArtistCoverEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistCoverEndpointTests : 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 MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateArtistCoverEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task UpdateArtistCover_WhenCalledByOwnerWithValidImage_ShouldReplaceTheStoredCover()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistWithCoverAsync(userId, "/media/music/old-artist-cover.jpg");
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
string storedPath = JsonSerializer.Deserialize<UpdateArtistCoverResponse>(content, _jsonOptions)!.CoverPath;
Assert.False(string.IsNullOrWhiteSpace(storedPath));
Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
MusicArtworkEntity coverArtwork = dbContext.MusicArtwork
.Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId && artwork.ArtworkType == ArtworkType.Cover);
Assert.Equal(storedPath, coverArtwork.FileName);
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
}
[Fact]
public async Task UpdateArtistCover_WhenArtistHasNoExistingCover_ShouldCreateACoverArtwork()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId);
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
string storedPath = JsonSerializer.Deserialize<UpdateArtistCoverResponse>(content, _jsonOptions)!.CoverPath;
Assert.False(string.IsNullOrWhiteSpace(storedPath));
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
MusicArtworkEntity coverArtwork = dbContext.MusicArtwork
.Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId && artwork.ArtworkType == ArtworkType.Cover);
Assert.Equal(storedPath, coverArtwork.FileName);
}
[Fact]
public async Task UpdateArtistCover_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/cover";
// Act
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
// Assert
await AssertNotFoundAsync(response, "ArtistNotFound", url);
}
[Fact]
public async Task UpdateArtistCover_WhenArtistRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid artistId) = await SeedLibraryAndArtistAsync(userId);
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/cover";
// Act
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
// Assert
await AssertNotFoundAsync(response, "ArtistNotFound", url);
}
[Fact]
public async Task UpdateArtistCover_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
(Guid otherLibraryId, Guid otherArtistId) = await SeedLibraryAndArtistAsync(otherUserId);
string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/cover";
// Act
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
// Assert
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
}
[Fact]
public async Task UpdateArtistCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover";
// Act
HttpResponseMessage response = await unauthenticatedClient.PutAsync(url, CreateCoverForm("cover.png"));
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task UpdateArtistCover_WhenNoFileIsUploaded_ShouldReturnUnprocessableEntityWithCoverCannotBeNull()
{
// Arrange
MultipartFormDataContent form = [];
form.Add(new StringContent("unrelated-field"), "unrelated-field");
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover";
// Act
HttpResponseMessage response = await _client.PutAsync(url, form);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, url, "CoverCannotBeNull");
}
[Fact]
public async Task UpdateArtistCover_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
{
// Arrange
string url = $"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/not-a-guid/cover";
// Act
HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
}
/// <summary>
/// Creates a multipart form carrying a minimal PNG-like payload.
/// </summary>
/// <param name="fileName">The name of the uploaded file.</param>
/// <returns>A configured <see cref="MultipartFormDataContent"/> instance.</returns>
private static MultipartFormDataContent CreateCoverForm(string fileName)
{
// The payload only needs to carry the PNG signature in its first bytes and exceed the header detection buffer.
byte[] payload = new byte[100];
payload[0] = 137;
payload[1] = 80;
payload[2] = 78;
payload[3] = 71;
payload[4] = 13;
payload[5] = 10;
payload[6] = 26;
payload[7] = 10;
MultipartFormDataContent form = [];
ByteArrayContent fileContent = new(payload);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, "cover", fileName);
return form;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist that has no cover yet.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist that already has a cover.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="existingCoverFileName">The relative path of the existing cover of the artist.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistWithCoverAsync(Guid userId, string existingCoverFileName)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistId, artworkType: ArtworkType.Cover, ordinal: 0, fileName: existingCoverFileName, status: ArtworkStatus.Enriched));
await dbContext.SaveChangesAsync();
return (libraryId, artistId);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
{
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
}
/// <summary>
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="statusCode">The expected HTTP status code.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedType">The expected problem type URI.</param>
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
{
Assert.Equal(statusCode, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
Assert.Equal(expectedType, problemDetails["type"].GetString());
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
/// <summary>
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
}
/// <summary>
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,320 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
using Lumina.Presentation.Api.SecurityTests.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.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
/// <summary>
/// Contains security tests for the <see cref="UpdateAlbumCoverEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateAlbumCoverEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateAlbumCoverEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task UpdateAlbumCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
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("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", problemDetails["instance"].GetProperty("value").GetString());
}
[Fact]
public async Task UpdateAlbumCover_WhenUnauthorized_ShouldNotLeakSensitiveData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover", form);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task UpdateAlbumCover_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover", form);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty");
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task UpdateAlbumCover_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/cover", form);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty");
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task UpdateAlbumCover_WithSQLInjectionInAlbumRouteId_ShouldRemainSecure(string maliciousAlbumId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/cover", form);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousAlbumId, "AlbumIdCannotBeEmpty");
}
[Fact]
public async Task UpdateAlbumCover_WhenAlbumDoesNotExist_ShouldReturnNotFoundWithoutLeakingInternals()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("AlbumNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
}
[Fact]
public async Task UpdateAlbumCover_WithMaliciousFileName_ShouldNotCorruptOrLeakData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
MultipartFormDataContent form = CreateCoverForm("..\\..\\evil.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover", form);
// Assert
// The album does not exist, so the handler returns a clean not found response before the uploaded file name is used.
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task UpdateAlbumCover_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
_seededUsernames.Add(ownerUsername);
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(ownerId);
HttpClient requesterClient = _apiFactory.CreateClient();
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
_seededUsernames.Add(requesterUsername);
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await requesterClient.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
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());
}
[Fact]
public async Task UpdateAlbumCover_WhenResourceBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
(Guid ownLibraryId, _, _) = await SeedLibraryArtistAndAlbumAsync(actingUserId);
// The resource lives in a library owned by another user, and is referenced through the acting user's own library route.
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(_, Guid victimArtistId, Guid victimAlbumId) = await SeedLibraryArtistAndAlbumAsync(victimUserId);
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("AlbumNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
// The other user's album is untouched.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
AlbumEntity? storedAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId);
Assert.NotNull(storedAlbum);
Assert.Equal("News of the World", storedAlbum.Title);
}
/// <summary>
/// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload.
/// </summary>
/// <param name="response">The HTTP response to assert.</param>
/// <param name="injectedPayload">The injected payload that must never be echoed back.</param>
/// <param name="expectedErrorCode">The validation error code expected in the response.</param>
private static async Task AssertCleanValidationErrorAsync(HttpResponseMessage response, string injectedPayload, string expectedErrorCode)
{
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(injectedPayload, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains(expectedErrorCode, content, StringComparison.Ordinal);
}
/// <summary>
/// Creates a multipart form carrying a minimal cover payload with the specified file name.
/// </summary>
/// <param name="fileName">The name of the uploaded file.</param>
/// <returns>A configured <see cref="MultipartFormDataContent"/> instance.</returns>
private static MultipartFormDataContent CreateCoverForm(string fileName)
{
MultipartFormDataContent form = [];
ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, "cover", fileName);
return form;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist and album.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,298 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
using Lumina.Presentation.Api.SecurityTests.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.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
/// <summary>
/// Contains security tests for the <see cref="UpdateArtistCoverEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistCoverEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateArtistCoverEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task UpdateArtistCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
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("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", problemDetails["instance"].GetProperty("value").GetString());
}
[Fact]
public async Task UpdateArtistCover_WhenUnauthorized_ShouldNotLeakSensitiveData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover", form);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task UpdateArtistCover_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/cover", form);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty");
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task UpdateArtistCover_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/cover", form);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty");
}
[Fact]
public async Task UpdateArtistCover_WhenArtistDoesNotExist_ShouldReturnNotFoundWithoutLeakingInternals()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
}
[Fact]
public async Task UpdateArtistCover_WithMaliciousFileName_ShouldNotCorruptOrLeakData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
MultipartFormDataContent form = CreateCoverForm("..\\..\\evil.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover", form);
// Assert
// The artist does not exist, so the handler returns a clean not found response before the uploaded file name is used.
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task UpdateArtistCover_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
_seededUsernames.Add(ownerUsername);
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(ownerId);
HttpClient requesterClient = _apiFactory.CreateClient();
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
_seededUsernames.Add(requesterUsername);
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await requesterClient.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
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());
}
[Fact]
public async Task UpdateArtistCover_WhenArtistBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
(Guid ownLibraryId, _) = await SeedLibraryAndArtistAsync(actingUserId);
// The artist lives in a library owned by another user, and is referenced through the acting user's own library route.
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(_, Guid victimArtistId) = await SeedLibraryAndArtistAsync(victimUserId);
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
// The other user's artist is untouched.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
ArtistEntity? storedArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId);
Assert.NotNull(storedArtist);
Assert.Equal("Queen", storedArtist.Name);
}
/// <summary>
/// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload.
/// </summary>
/// <param name="response">The HTTP response to assert.</param>
/// <param name="injectedPayload">The injected payload that must never be echoed back.</param>
/// <param name="expectedErrorCode">The validation error code expected in the response.</param>
private static async Task AssertCleanValidationErrorAsync(HttpResponseMessage response, string injectedPayload, string expectedErrorCode)
{
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(injectedPayload, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains(expectedErrorCode, content, StringComparison.Ordinal);
}
/// <summary>
/// Creates a multipart form carrying a minimal cover payload with the specified file name.
/// </summary>
/// <param name="fileName">The name of the uploaded file.</param>
/// <returns>A configured <see cref="MultipartFormDataContent"/> instance.</returns>
private static MultipartFormDataContent CreateCoverForm(string fileName)
{
MultipartFormDataContent form = [];
ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, "cover", fileName);
return form;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,722 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
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.Albums.Commands.UpdateAlbumCover;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
/// <summary>
/// Contains unit tests for the <see cref="UpdateAlbumCoverCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateAlbumCoverCommandHandlerTests
{
private const string STORED_COVER_PATH = "/media/music/library/artist/Album/album/cover.jpg";
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IAlbumRepository _mockAlbumRepository;
private readonly IArtistRepository _mockArtistRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
private readonly IMusicArtworkService _mockMusicArtworkService;
private readonly IPathService _mockPathService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<UpdateAlbumCoverCommand> _mockValidator;
private readonly UpdateAlbumCoverCommandHandler _sut;
private readonly Guid _userId;
private readonly UpdateAlbumCoverCommandFixture _updateAlbumCoverCommandFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCoverCommandHandlerTests"/> class.
/// </summary>
public UpdateAlbumCoverCommandHandlerTests()
{
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
_mockMusicArtworkService = Substitute.For<IMusicArtworkService>();
_mockPathService = Substitute.For<IPathService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<UpdateAlbumCoverCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated, the library ownership policy allows access, the validator passes, the album has no artwork yet, and the artwork storage succeeds.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<UpdateAlbumCoverCommand>()).Returns([]);
// The stored artwork paths used by the tests are Unix separated, and sanitizing a name keeps it unchanged, as the real service does for valid names.
_mockPathService.PathSeparator.Returns('/');
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo => PathSegment.Create(callInfo.Arg<string>(), isDirectory: true, isDrive: false));
_mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([]));
_mockMusicArtworkRepository.UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockMusicArtworkService.SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(STORED_COVER_PATH));
_mockMusicArtworkService.DeleteStoredArtwork(Arg.Any<string>()).Returns(Result.From(Result.Deleted));
_sut = new UpdateAlbumCoverCommandHandler(_mockUnitOfWork, _mockMusicArtworkService, _mockPathService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutStoringArtwork()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
_mockValidator.Validate(Arg.Any<UpdateAlbumCoverCommand>()).Returns([Errors.Music.CoverCannotBeNull]);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.CoverCannotBeNull, result.FirstError);
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(null));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
// The stored album belongs to a different library than the one named by the route.
AlbumEntity existingAlbum = _albumEntityFixture.Create(id: Guid.Parse(command.AlbumId!), artistId: Guid.Parse(command.ArtistId!), libraryId: Guid.NewGuid());
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(existingAlbum));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
// The stored album belongs to a different artist than the one named by the route.
AlbumEntity existingAlbum = _albumEntityFixture.Create(id: Guid.Parse(command.AlbumId!), artistId: Guid.NewGuid(), libraryId: Guid.Parse(command.LibraryId!));
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(existingAlbum));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorWithoutStoringArtwork()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command);
SetupExistingLibrary(command);
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistDoesNotExist_ShouldPassEmptyArtistNameToArtworkService()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command);
SetupExistingLibrary(command);
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(null));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), string.Empty, Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkLookupFails_ShouldReturnFailureResultWithoutStoringArtwork()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command);
SetupExistingLibrary(command);
SetupExistingArtist(command);
_mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkStorageFails_ShouldReturnFailureResultWithoutUpsertingOrSaving()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command);
SetupExistingLibrary(command);
SetupExistingArtist(command);
_mockMusicArtworkService.SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Errors.FileSystemManagement.FileTooLarge);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenExistingCoverPathHasParseableReleaseType_ShouldPassThatReleaseTypeToArtworkService()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
// The album's release type is Album, but its stored cover already lives under an Ep directory, which wins.
SetupExistingAlbum(command, releaseType: MusicReleaseType.Album);
SetupExistingLibrary(command);
SetupExistingArtist(command);
SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/artist/Ep/album/cover.jpg"));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), "Ep", Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheSegmentBeforeTheAlbumDirectoryIsTheArtistDirectoryNamedLikeAReleaseType_ShouldNotTreatItAsAReleaseType()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
// The artist is named "Live", which is also a release type name, but the album uses no release type, so the segment right before the album
// directory is the artist directory and must not be mistaken for a release type directory.
SetupExistingAlbum(command, includeReleaseType: false);
SetupExistingLibrary(command);
SetupExistingArtist(command, name: "Live");
SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/Live/album/cover.jpg"));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), "Live", Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Is<string?>(releaseTypeName => releaseTypeName == null), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheSegmentBeforeTheAlbumDirectoryIsAReleaseTypeOfAnArtistNamedLikeAReleaseType_ShouldKeepIt()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
// The artist is named "Album" and its cover is stored under an "Ep" release type directory, which differs from the artist directory, so it is kept.
SetupExistingAlbum(command);
SetupExistingLibrary(command);
SetupExistingArtist(command, name: "Album");
SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/Album/Ep/album/cover.jpg"));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), "Album", Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), "Ep", Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenExistingCoverPathHasNonParseableReleaseType_ShouldFallBackToFirstReleaseType()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command, releaseType: MusicReleaseType.Single);
SetupExistingLibrary(command);
SetupExistingArtist(command);
SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/artist/NotAReleaseType/album/cover.jpg"));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), "Single", Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenExistingCoverPathHasTooFewSegments_ShouldFallBackToFirstReleaseType()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command, releaseType: MusicReleaseType.Single);
SetupExistingLibrary(command);
SetupExistingArtist(command);
// The stored cover path carries fewer than three segments, so it does not expose a release type directory.
SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "cover.jpg"));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), "Single", Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumHasNoExistingCover_ShouldUseFirstReleaseType()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command, releaseType: MusicReleaseType.Single);
SetupExistingLibrary(command);
SetupExistingArtist(command);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), "Single", Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumHasNoExistingCoverAndNoReleaseTypes_ShouldPassNullReleaseTypeToArtworkService()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command, includeReleaseType: false);
SetupExistingLibrary(command);
SetupExistingArtist(command);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Is<string?>(releaseTypeName => releaseTypeName == null), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenExistingCoverPathDiffersFromStoredPath_ShouldDeletePreviousArtwork()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command);
SetupExistingLibrary(command);
SetupExistingArtist(command);
SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/artist/Ep/album/old-cover.jpg"));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork("/media/music/library/artist/Ep/album/old-cover.jpg");
}
[Fact]
public async Task HandleAsync_WhenExistingCoverPathEqualsStoredPath_ShouldNotDeletePreviousArtwork()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command);
SetupExistingLibrary(command);
SetupExistingArtist(command);
SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: STORED_COVER_PATH));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any<string>());
}
[Theory]
[InlineData(null)] // no file name at all
[InlineData("")] // empty file name
[InlineData(" ")] // whitespace file name
public async Task HandleAsync_WhenExistingCoverPathIsEmpty_ShouldNotDeletePreviousArtwork(string? existingCoverPath)
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command);
SetupExistingLibrary(command);
SetupExistingArtist(command);
SetupExistingArtwork(_musicArtworkEntityFixture.Create(
ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: existingCoverPath, includeFileName: existingCoverPath is not null));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any<string>());
}
[Fact]
public async Task HandleAsync_WhenDeletingPreviousArtworkFails_ShouldReturnFailureResultWithoutUpsertingOrSaving()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command);
SetupExistingLibrary(command);
SetupExistingArtist(command);
SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/artist/Ep/album/old-cover.jpg"));
_mockMusicArtworkService.DeleteStoredArtwork(Arg.Any<string>()).Returns(Errors.FileSystemManagement.FileTooLarge);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpsertCoverFails_ShouldReturnFailureResultWithoutSaving()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command);
SetupExistingLibrary(command);
SetupExistingArtist(command);
_mockMusicArtworkRepository.UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResult()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
SetupExistingAlbum(command);
SetupExistingLibrary(command);
SetupExistingArtist(command);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockMusicArtworkRepository.Received(1).UpsertCoverAsync(
MusicArtworkOwnerType.Album, Guid.Parse(command.AlbumId!), STORED_COVER_PATH, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSuccessful_ShouldReturnUpdateAlbumCoverResponseAndStoreArtwork()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
AlbumEntity existingAlbum = SetupExistingAlbum(command, releaseType: MusicReleaseType.Album);
LibraryEntity library = SetupExistingLibrary(command);
ArtistEntity artist = SetupExistingArtist(command);
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
UpdateAlbumCoverResponse response = Assert.IsType<UpdateAlbumCoverResponse>(result.Value);
Assert.Equal(STORED_COVER_PATH, response.CoverPath);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
existingAlbum.LibraryId,
existingAlbum.Id,
library.Title,
artist.Name,
existingAlbum.Title,
Arg.Any<Stream>(),
command.FileName!,
"Album",
Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).UpsertCoverAsync(
MusicArtworkOwnerType.Album,
existingAlbum.Id,
STORED_COVER_PATH,
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
/// <summary>
/// Sets up a stored album that matches the library, artist and album identifiers of the command.
/// </summary>
/// <param name="command">The command whose route identifiers the stored album must match.</param>
/// <param name="releaseType">Optional. The release type of the stored album.</param>
/// <param name="includeReleaseType">Whether the stored album should carry a release type, or an empty collection.</param>
/// <returns>The created <see cref="AlbumEntity"/>.</returns>
private AlbumEntity SetupExistingAlbum(UpdateAlbumCoverCommand command, MusicReleaseType? releaseType = MusicReleaseType.Album, bool includeReleaseType = true)
{
AlbumEntity existingAlbum = _albumEntityFixture.Create(
id: Guid.Parse(command.AlbumId!),
artistId: Guid.Parse(command.ArtistId!),
libraryId: Guid.Parse(command.LibraryId!),
releaseType: releaseType,
includeReleaseType: includeReleaseType);
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(existingAlbum));
return existingAlbum;
}
/// <summary>
/// Sets up a stored media library that matches the library of the command.
/// </summary>
/// <param name="command">The command whose library identifier the stored library must match.</param>
/// <returns>The created <see cref="LibraryEntity"/>.</returns>
private LibraryEntity SetupExistingLibrary(UpdateAlbumCoverCommand command)
{
LibraryEntity library = _libraryEntityFixture.Create(id: Guid.Parse(command.LibraryId!));
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
return library;
}
/// <summary>
/// Sets up a stored artist that matches the artist of the command.
/// </summary>
/// <param name="command">The command whose artist identifier the stored artist must match.</param>
/// <param name="name">Optional. The name of the stored artist.</param>
/// <returns>The created <see cref="ArtistEntity"/>.</returns>
private ArtistEntity SetupExistingArtist(UpdateAlbumCoverCommand command, string? name = null)
{
ArtistEntity artist = _artistEntityFixture.Create(id: Guid.Parse(command.ArtistId!), libraryId: Guid.Parse(command.LibraryId!), name: name);
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
return artist;
}
/// <summary>
/// Sets up the artwork owned by the album.
/// </summary>
/// <param name="artworks">The pieces of artwork owned by the album.</param>
private void SetupExistingArtwork(params MusicArtworkEntity[] artworks)
{
_mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>(artworks));
}
}
@@ -0,0 +1,282 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
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.Albums.Commands.UpdateAlbumCover;
/// <summary>
/// Contains unit tests for the <see cref="UpdateAlbumCoverCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateAlbumCoverCommandValidatorTests
{
private readonly UpdateAlbumCoverCommandFixture _updateAlbumCoverCommandFixture = new();
private readonly UpdateAlbumCoverCommandValidator _validator = new();
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationErrors()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenLibraryIdIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(includeLibraryId: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(libraryId: Guid.Empty.ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsWhitespace_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(libraryId: " ");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsNotAGuid_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(libraryId: "not-a-guid");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(libraryId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtistIdIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(includeArtistId: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtistIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(artistId: Guid.Empty.ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtistIdIsWhitespace_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(artistId: " ");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtistIdIsNotAGuid_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(artistId: "not-a-guid");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(artistId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenAlbumIdIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(includeAlbumId: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenAlbumIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(albumId: Guid.Empty.ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenAlbumIdIsWhitespace_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(albumId: " ");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenAlbumIdIsNotAGuid_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(albumId: "not-a-guid");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(albumId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCoverIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(includeCover: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.CoverCannotBeNull);
}
[Fact]
public void Validate_WhenCoverIsPresentAndFileNameIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(fileName: string.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenCoverIsPresentAndFileNameIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(includeFileName: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenCoverIsMissingAndFileNameIsEmpty_ShouldNotHaveFileNameValidationError()
{
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(fileName: string.Empty, includeCover: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
}
}
@@ -0,0 +1,473 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
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.Artists.Commands.UpdateArtistCover;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
/// <summary>
/// Contains unit tests for the <see cref="UpdateArtistCoverCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistCoverCommandHandlerTests
{
private const string STORED_COVER_PATH = "/media/music/library/artist/cover.jpg";
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
private readonly IMusicArtworkService _mockMusicArtworkService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<UpdateArtistCoverCommand> _mockValidator;
private readonly UpdateArtistCoverCommandHandler _sut;
private readonly Guid _userId;
private readonly UpdateArtistCoverCommandFixture _updateArtistCoverCommandFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCoverCommandHandlerTests"/> class.
/// </summary>
public UpdateArtistCoverCommandHandlerTests()
{
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
_mockMusicArtworkService = Substitute.For<IMusicArtworkService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<UpdateArtistCoverCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated, the library ownership policy allows access, the validator passes, the artist has no artwork yet, and the artwork storage succeeds.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<UpdateArtistCoverCommand>()).Returns([]);
_mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([]));
_mockMusicArtworkRepository.UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockMusicArtworkService.SaveArtistArtworkAsync(
Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Result.From(STORED_COVER_PATH));
_mockMusicArtworkService.DeleteStoredArtwork(Arg.Any<string>()).Returns(Result.From(Result.Deleted));
_sut = new UpdateArtistCoverCommandHandler(_mockUnitOfWork, _mockMusicArtworkService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutStoringArtwork()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
_mockValidator.Validate(Arg.Any<UpdateArtistCoverCommand>()).Returns([Errors.Music.CoverCannotBeNull]);
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.CoverCannotBeNull, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(null));
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
// The stored artist belongs to a different library than the one named by the route.
ArtistEntity existingArtist = _artistEntityFixture.Create(id: Guid.Parse(command.ArtistId!), libraryId: Guid.NewGuid());
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(existingArtist));
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorWithoutStoringArtwork()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
SetupExistingArtist(command);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
SetupExistingArtist(command);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
SetupExistingArtist(command);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkLookupFails_ShouldReturnFailureResultWithoutStoringArtwork()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
SetupExistingArtist(command);
SetupExistingLibrary(command);
_mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkStorageFails_ShouldReturnFailureResultWithoutUpsertingOrSaving()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
SetupExistingArtist(command);
SetupExistingLibrary(command);
_mockMusicArtworkService.SaveArtistArtworkAsync(
Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Errors.FileSystemManagement.FileTooLarge);
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenExistingCoverPathDiffersFromStoredPath_ShouldDeletePreviousArtwork()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
SetupExistingArtist(command);
SetupExistingLibrary(command);
SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, artworkType: ArtworkType.Cover, fileName: "/media/music/library/artist/old-cover.jpg"));
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork("/media/music/library/artist/old-cover.jpg");
}
[Fact]
public async Task HandleAsync_WhenExistingCoverPathEqualsStoredPath_ShouldNotDeletePreviousArtwork()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
SetupExistingArtist(command);
SetupExistingLibrary(command);
SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, artworkType: ArtworkType.Cover, fileName: STORED_COVER_PATH));
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any<string>());
}
[Theory]
[InlineData(null)] // no file name at all
[InlineData("")] // empty file name
[InlineData(" ")] // whitespace file name
public async Task HandleAsync_WhenExistingCoverPathIsEmpty_ShouldNotDeletePreviousArtwork(string? existingCoverPath)
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
SetupExistingArtist(command);
SetupExistingLibrary(command);
SetupExistingArtwork(_musicArtworkEntityFixture.Create(
ownerType: MusicArtworkOwnerType.Artist, artworkType: ArtworkType.Cover, fileName: existingCoverPath, includeFileName: existingCoverPath is not null));
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any<string>());
}
[Fact]
public async Task HandleAsync_WhenDeletingPreviousArtworkFails_ShouldReturnFailureResultWithoutUpsertingOrSaving()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
SetupExistingArtist(command);
SetupExistingLibrary(command);
SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, artworkType: ArtworkType.Cover, fileName: "/media/music/library/artist/old-cover.jpg"));
_mockMusicArtworkService.DeleteStoredArtwork(Arg.Any<string>()).Returns(Errors.FileSystemManagement.FileTooLarge);
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpsertCoverFails_ShouldReturnFailureResultWithoutSaving()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
SetupExistingArtist(command);
SetupExistingLibrary(command);
_mockMusicArtworkRepository.UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResult()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
SetupExistingArtist(command);
SetupExistingLibrary(command);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockMusicArtworkRepository.Received(1).UpsertCoverAsync(
MusicArtworkOwnerType.Artist, Guid.Parse(command.ArtistId!), STORED_COVER_PATH, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSuccessful_ShouldReturnUpdateArtistCoverResponseAndStoreArtwork()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
ArtistEntity existingArtist = SetupExistingArtist(command);
LibraryEntity library = SetupExistingLibrary(command);
// Act
Result<UpdateArtistCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
UpdateArtistCoverResponse response = Assert.IsType<UpdateArtistCoverResponse>(result.Value);
Assert.Equal(STORED_COVER_PATH, response.CoverPath);
await _mockMusicArtworkService.Received(1).SaveArtistArtworkAsync(
existingArtist.LibraryId,
library.Title,
existingArtist.Name,
Arg.Any<Stream>(),
command.FileName!,
Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).UpsertCoverAsync(
MusicArtworkOwnerType.Artist,
existingArtist.Id,
STORED_COVER_PATH,
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
/// <summary>
/// Sets up a stored artist that matches the library and artist identifiers of the command.
/// </summary>
/// <param name="command">The command whose route identifiers the stored artist must match.</param>
/// <returns>The created <see cref="ArtistEntity"/>.</returns>
private ArtistEntity SetupExistingArtist(UpdateArtistCoverCommand command)
{
ArtistEntity existingArtist = _artistEntityFixture.Create(
id: Guid.Parse(command.ArtistId!),
libraryId: Guid.Parse(command.LibraryId!));
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(existingArtist));
return existingArtist;
}
/// <summary>
/// Sets up a stored media library that matches the library of the command.
/// </summary>
/// <param name="command">The command whose library identifier the stored library must match.</param>
/// <returns>The created <see cref="LibraryEntity"/>.</returns>
private LibraryEntity SetupExistingLibrary(UpdateArtistCoverCommand command)
{
LibraryEntity library = _libraryEntityFixture.Create(id: Guid.Parse(command.LibraryId!));
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
return library;
}
/// <summary>
/// Sets up the artwork owned by the artist.
/// </summary>
/// <param name="artworks">The pieces of artwork owned by the artist.</param>
private void SetupExistingArtwork(params MusicArtworkEntity[] artworks)
{
_mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>(artworks));
}
}
@@ -0,0 +1,217 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
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.Artists.Commands.UpdateArtistCover;
/// <summary>
/// Contains unit tests for the <see cref="UpdateArtistCoverCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistCoverCommandValidatorTests
{
private readonly UpdateArtistCoverCommandFixture _updateArtistCoverCommandFixture = new();
private readonly UpdateArtistCoverCommandValidator _validator = new();
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationErrors()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenLibraryIdIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(includeLibraryId: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(libraryId: Guid.Empty.ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsWhitespace_ShouldHaveValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(libraryId: " ");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsNotAGuid_ShouldHaveValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(libraryId: "not-a-guid");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(libraryId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtistIdIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(includeArtistId: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtistIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(artistId: Guid.Empty.ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtistIdIsWhitespace_ShouldHaveValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(artistId: " ");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtistIdIsNotAGuid_ShouldHaveValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(artistId: "not-a-guid");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(artistId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCoverIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(includeCover: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.CoverCannotBeNull);
}
[Fact]
public void Validate_WhenCoverIsPresentAndFileNameIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(fileName: string.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenCoverIsPresentAndFileNameIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(includeFileName: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenCoverIsMissingAndFileNameIsEmpty_ShouldNotHaveFileNameValidationError()
{
// Arrange
UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(fileName: string.Empty, includeCover: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
}
}
@@ -0,0 +1,340 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
/// <summary>
/// Contains unit tests for the <see cref="UpdateAlbumCoverEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateAlbumCoverEndpointTests
{
private readonly ICommandHandler<UpdateAlbumCoverCommand, Result<UpdateAlbumCoverResponse>> _mockHandler;
private readonly UpdateAlbumCoverEndpoint _sut;
private readonly UpdateAlbumCoverResponseFixture _updateAlbumCoverResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpointTests"/> class.
/// </summary>
public UpdateAlbumCoverEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<UpdateAlbumCoverCommand, Result<UpdateAlbumCoverResponse>>>();
_sut = FastEndpoints.Factory.Create<UpdateAlbumCoverEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithCoverPath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
string expectedPath = "/media/music/cover.jpg";
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: expectedPath)));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<UpdateAlbumCoverResponse> okResult = Assert.IsType<Ok<UpdateAlbumCoverResponse>>(result);
Assert.Equal(expectedPath, okResult?.Value?.CoverPath);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidRouteIdsAndFile_ShouldSendUpdateAlbumCoverCommandToSender()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg")));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateAlbumCoverCommand>(command =>
command.LibraryId == libraryId.ToString() &&
command.ArtistId == artistId.ToString() &&
command.AlbumId == albumId.ToString() &&
command.Cover != null &&
command.FileName == "cover.jpg"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg")));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
_sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid";
_sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid";
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateAlbumCoverCommand>(command =>
command.LibraryId == "not-a-library-guid" &&
command.ArtistId == "not-an-artist-guid" &&
command.AlbumId == "not-an-album-guid"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg")));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("artistId");
_sut.HttpContext.Request.RouteValues.Remove("albumId");
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateAlbumCoverCommand>(command =>
command.LibraryId == null &&
command.ArtistId == null &&
command.AlbumId == null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenFormHasNoFiles_ShouldSendCommandWithNullCover()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg")));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
IFormCollection form = new FormCollection([]);
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Assert.IsType<Ok<UpdateAlbumCoverResponse>>(result);
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateAlbumCoverCommand>(command =>
command.AlbumId == albumId.ToString() &&
command.Cover == null &&
command.FileName == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenRequestIsNotMultipart_ShouldSendCommandWithNullCover()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg")));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
_sut.HttpContext.Request.ContentType = "application/json";
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Assert.IsType<Ok<UpdateAlbumCoverResponse>>(result);
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateAlbumCoverCommand>(command => command.Cover == null && command.FileName == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheFormIsMalformed_ShouldSendCommandWithNullCover()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg")));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
ConfigureMalformedForm();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Assert.IsType<Ok<UpdateAlbumCoverResponse>>(result);
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateAlbumCoverCommand>(command => command.Cover == null && command.FileName == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = Errors.Music.CoverCannotBeNull;
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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[] { "CoverCannotBeNull" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Errors.Music.AlbumNotFound;
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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("General.NotFound", problemDetailsBody.Title);
Assert.Equal("AlbumNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<UpdateAlbumCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg"));
}, callInfo.Arg<CancellationToken>()));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
private void ConfigureForm(byte[] content, string fileName)
{
MemoryStream coverStream = new(content);
IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName);
FormFileCollection files = [formFile];
IFormCollection form = new FormCollection([], files);
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
}
/// <summary>
/// Configures a multipart form request whose body cannot be parsed.
/// </summary>
private void ConfigureMalformedForm()
{
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
IFormCollection malformedForm = Substitute.For<IFormCollection>();
malformedForm.Files.Returns(_ => throw new InvalidDataException("Malformed multipart body."));
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(malformedForm));
}
}
@@ -0,0 +1,319 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
/// <summary>
/// Contains unit tests for the <see cref="UpdateArtistCoverEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistCoverEndpointTests
{
private readonly ICommandHandler<UpdateArtistCoverCommand, Result<UpdateArtistCoverResponse>> _mockHandler;
private readonly UpdateArtistCoverEndpoint _sut;
private readonly UpdateArtistCoverResponseFixture _updateArtistCoverResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpointTests"/> class.
/// </summary>
public UpdateArtistCoverEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<UpdateArtistCoverCommand, Result<UpdateArtistCoverResponse>>>();
_sut = FastEndpoints.Factory.Create<UpdateArtistCoverEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithCoverPath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
string expectedPath = "/media/music/artist-cover.jpg";
_mockHandler.HandleAsync(Arg.Any<UpdateArtistCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: expectedPath)));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<UpdateArtistCoverResponse> okResult = Assert.IsType<Ok<UpdateArtistCoverResponse>>(result);
Assert.Equal(expectedPath, okResult?.Value?.CoverPath);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidRouteIdsAndFile_ShouldSendUpdateArtistCoverCommandToSender()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateArtistCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg")));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateArtistCoverCommand>(command =>
command.LibraryId == libraryId.ToString() &&
command.ArtistId == artistId.ToString() &&
command.Cover != null &&
command.FileName == "cover.jpg"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateArtistCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg")));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
_sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid";
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateArtistCoverCommand>(command =>
command.LibraryId == "not-a-library-guid" &&
command.ArtistId == "not-an-artist-guid"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateArtistCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg")));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("artistId");
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateArtistCoverCommand>(command =>
command.LibraryId == null &&
command.ArtistId == null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenFormHasNoFiles_ShouldSendCommandWithNullCover()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateArtistCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg")));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
IFormCollection form = new FormCollection([]);
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Assert.IsType<Ok<UpdateArtistCoverResponse>>(result);
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateArtistCoverCommand>(command =>
command.ArtistId == artistId.ToString() &&
command.Cover == null &&
command.FileName == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenRequestIsNotMultipart_ShouldSendCommandWithNullCover()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateArtistCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg")));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
_sut.HttpContext.Request.ContentType = "application/json";
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Assert.IsType<Ok<UpdateArtistCoverResponse>>(result);
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateArtistCoverCommand>(command => command.Cover == null && command.FileName == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheFormIsMalformed_ShouldSendCommandWithNullCover()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateArtistCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg")));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
ConfigureMalformedForm();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Assert.IsType<Ok<UpdateArtistCoverResponse>>(result);
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateArtistCoverCommand>(command => command.Cover == null && command.FileName == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = Errors.Music.CoverCannotBeNull;
_mockHandler.HandleAsync(Arg.Any<UpdateArtistCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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[] { "CoverCannotBeNull" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Errors.Music.ArtistNotFound;
_mockHandler.HandleAsync(Arg.Any<UpdateArtistCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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("General.NotFound", problemDetailsBody.Title);
Assert.Equal("ArtistNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<UpdateArtistCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg"));
}, callInfo.Arg<CancellationToken>()));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
private void ConfigureForm(byte[] content, string fileName)
{
MemoryStream coverStream = new(content);
IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName);
FormFileCollection files = [formFile];
IFormCollection form = new FormCollection([], files);
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
}
/// <summary>
/// Configures a multipart form request whose body cannot be parsed.
/// </summary>
private void ConfigureMalformedForm()
{
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
IFormCollection malformedForm = Substitute.For<IFormCollection>();
malformedForm.Files.Returns(_ => throw new InvalidDataException("Malformed multipart body."));
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(malformedForm));
}
}