mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 06:11:10 +00:00
Adds cover update endpoints for music artists and albums.
This commit is contained in:
1 parent
4f43bf352b
commit
4ceb8f7360
32 files changed
+4892
No files matched your search
+72
@@ -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);
|
||||
}
|
||||
}
|
||||
+67
@@ -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);
|
||||
}
|
||||
}
|
||||
+40
@@ -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())];
|
||||
}
|
||||
}
|
||||
+40
@@ -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())];
|
||||
}
|
||||
}
|
||||
+382
@@ -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();
|
||||
}
|
||||
}
|
||||
+391
@@ -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();
|
||||
}
|
||||
}
|
||||
+320
@@ -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);
|
||||
}
|
||||
}
|
||||
+298
@@ -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);
|
||||
}
|
||||
}
|
||||
+722
@@ -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));
|
||||
}
|
||||
}
|
||||
+282
@@ -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);
|
||||
}
|
||||
}
|
||||
+473
@@ -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));
|
||||
}
|
||||
}
|
||||
+217
@@ -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);
|
||||
}
|
||||
}
|
||||
+340
@@ -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));
|
||||
}
|
||||
}
|
||||
+319
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user