Removes track path editing from the music track update flow

Stops Track.UpdateDetails and Artist.UpdateTrackInAlbum from assigning a path, so a track path can be set only when the track is created. Removes Path from UpdateTrackRequest, UpdateTrackCommand, UpdateTrackCommandValidator and UpdateMusicTrackRequest, and removes the path containment check and IPathService dependency from UpdateTrackCommandHandler. The path stays visible in TrackResponse, MusicTrackDto and the read-only field of the track page. Updates the endpoint summary, request and API docs, and the affected tests.
This commit is contained in:
BinaryAlley committed 2026-10-13 20:14:12 +03:00
1 parent 728a879bb8
commit 1aa427b1e2
29 files changed
+47 -243

No files matched your search

@@ -39,7 +39,6 @@ public class UpdateTrackCommandFixture
/// <param name="artistId">Optional. The Id of the artist the track belongs to.</param>
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
/// <param name="trackId">Optional. The Id of the track to update.</param>
/// <param name="path">Optional. The file system path of the track.</param>
/// <param name="metadata">Optional. The audio metadata of the track.</param>
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
@@ -69,7 +68,6 @@ public class UpdateTrackCommandFixture
/// <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="includeTrackId">Whether the track Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePath">Whether the path should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTrackNumber">Whether the track number should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created command to update a track.</returns>
public UpdateTrackCommand Create(
@@ -77,7 +75,6 @@ public class UpdateTrackCommandFixture
string? artistId = null,
string? albumId = null,
string? trackId = null,
string? path = null,
MusicTrackMetadataDto? metadata = null,
int? trackNumber = null,
int? discNumber = null,
@@ -107,7 +104,6 @@ public class UpdateTrackCommandFixture
bool includeArtistId = true,
bool includeAlbumId = true,
bool includeTrackId = true,
bool includePath = true,
bool includeTrackNumber = true)
{
return new UpdateTrackCommand(
@@ -115,7 +111,6 @@ public class UpdateTrackCommandFixture
includeArtistId ? (artistId ?? _faker.Random.Guid().ToString()) : null,
includeAlbumId ? (albumId ?? _faker.Random.Guid().ToString()) : null,
includeTrackId ? (trackId ?? _faker.Random.Guid().ToString()) : null,
includePath ? (path ?? _faker.System.FilePath()) : null,
includeMetadata ? (metadata ?? _musicTrackMetadataDtoFixture.Create()) : null,
includeTrackNumber ? (trackNumber ?? _faker.Random.Int(1, 20)) : null,
includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null,
@@ -35,7 +35,6 @@ public class UpdateTrackRequestFixture
/// <summary>
/// Creates a random valid request to update a track.
/// </summary>
/// <param name="path">Optional. The file system path of the track.</param>
/// <param name="metadata">Optional. The audio metadata of the track.</param>
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
@@ -60,12 +59,10 @@ public class UpdateTrackRequestFixture
/// <param name="includeIsrcs">Whether the ISRC codes should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContributors">Whether the contributors list should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeRatings">Whether the ratings list should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePath">Whether the path should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMetadata">Whether the metadata should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTrackNumber">Whether the track number should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created request to update a track.</returns>
public UpdateTrackRequest Create(
string? path = null,
MusicTrackMetadataDto? metadata = null,
int? trackNumber = null,
int? discNumber = null,
@@ -90,12 +87,10 @@ public class UpdateTrackRequestFixture
bool includeIsrcs = true,
bool includeContributors = true,
bool includeRatings = true,
bool includePath = true,
bool includeMetadata = true,
bool includeTrackNumber = true)
{
return new UpdateTrackRequest(
includePath ? (path ?? _faker.System.FilePath()) : null,
includeMetadata ? (metadata ?? _musicTrackMetadataDtoFixture.Create()) : null,
includeTrackNumber ? (trackNumber ?? _faker.Random.Int(1, 20)) : null,
includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null,
@@ -35,7 +35,6 @@ public class UpdateMusicTrackRequestFixture
/// <summary>
/// Creates a new <see cref="UpdateMusicTrackRequest"/> instance with randomized test data.
/// </summary>
/// <param name="path">Optional. The file system path of the track.</param>
/// <param name="metadata">Optional. The audio metadata of the track.</param>
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
@@ -49,7 +48,6 @@ public class UpdateMusicTrackRequestFixture
/// <param name="isrcs">Optional. The ISRC codes of the track.</param>
/// <param name="contributors">Optional. The references to the media contributors that performed on the track.</param>
/// <param name="ratings">Optional. The ratings of the track.</param>
/// <param name="includePath">Whether the path should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMetadata">Whether the metadata should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTrackNumber">Whether the track number should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDiscNumber">Whether the disc number should be included, or forced to <see langword="null"/>.</param>
@@ -65,7 +63,6 @@ public class UpdateMusicTrackRequestFixture
/// <param name="includeRatings">Whether the ratings should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="UpdateMusicTrackRequest"/> instance.</returns>
public UpdateMusicTrackRequest Create(
string? path = null,
MusicTrackMetadataDto? metadata = null,
int? trackNumber = null,
int? discNumber = null,
@@ -79,7 +76,6 @@ public class UpdateMusicTrackRequestFixture
List<IsrcDto>? isrcs = null,
List<MediaContributorReferenceDto>? contributors = null,
List<AudioRatingDto>? ratings = null,
bool includePath = true,
bool includeMetadata = true,
bool includeTrackNumber = true,
bool includeDiscNumber = true,
@@ -95,7 +91,6 @@ public class UpdateMusicTrackRequestFixture
bool includeRatings = true)
{
return new UpdateMusicTrackRequest(
Path: includePath ? (path ?? _faker.System.FilePath()) : null,
Metadata: includeMetadata ? (metadata ?? _musicTrackMetadataDtoFixture.Create()) : null,
TrackNumber: includeTrackNumber ? (trackNumber ?? _faker.Random.Number(1, 30)) : null,
DiscNumber: includeDiscNumber ? (discNumber ?? _faker.Random.Number(1, 4)) : null,
@@ -56,7 +56,6 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioL
public class UpdateTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private static readonly string s_contentRootPath = Path.Combine(Path.GetTempPath(), "lumina-update-track-tests");
private static readonly string s_outsideContentRootPath = Path.Combine(Path.GetTempPath(), "lumina-update-track-outside");
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
@@ -115,10 +114,9 @@ public class UpdateTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
(Guid artistId, Guid albumId, Guid trackId) = await SeedArtistGraphAsync(libraryId, Path.Combine(s_contentRootPath, "bohemian-rhapsody.flac"));
string updatedPath = Path.Combine(s_contentRootPath, $"love-of-my-life-{Guid.NewGuid():N}.flac");
string originalPath = Path.Combine(s_contentRootPath, "bohemian-rhapsody.flac");
(Guid artistId, Guid albumId, Guid trackId) = await SeedArtistGraphAsync(libraryId, originalPath);
UpdateTrackRequest request = _updateTrackRequestFixture.Create(
path: updatedPath,
metadata: _musicTrackMetadataDtoFixture.Create(title: "Somebody to Love"),
moods: [],
isrcs: [],
@@ -142,14 +140,15 @@ public class UpdateTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
Assert.NotNull(trackResponse);
Assert.Equal(trackId, trackResponse!.Id);
Assert.Equal(libraryId, trackResponse.LibraryId);
Assert.Equal(updatedPath, trackResponse.Path);
// the file system path is preserved by the update, it is set only when the track is created
Assert.Equal(originalPath, trackResponse.Path);
Assert.Equal("Somebody to Love", trackResponse.Metadata!.Title);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
TrackEntity storedTrack = dbContext.Tracks.Single(track => track.Id == trackId);
Assert.Equal("Somebody to Love", storedTrack.Title);
Assert.Equal(updatedPath, storedTrack.Path);
Assert.Equal(originalPath, storedTrack.Path);
}
[Fact]
@@ -160,7 +159,6 @@ public class UpdateTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
Guid libraryId = await SeedLibraryAsync(otherUserId);
(Guid artistId, Guid albumId, Guid trackId) = await SeedArtistGraphAsync(libraryId, Path.Combine(s_contentRootPath, "bohemian-rhapsody.flac"));
UpdateTrackRequest request = _updateTrackRequestFixture.Create(
path: Path.Combine(s_contentRootPath, "dont-stop-me-now.flac"),
metadata: _musicTrackMetadataDtoFixture.Create(title: "Don't Stop Me Now"),
moods: [],
isrcs: [],
@@ -301,22 +299,6 @@ public class UpdateTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
await AssertNotFoundAsync(response, "LibraryNotFound");
}
[Fact]
public async Task UpdateTrack_WhenPathIsOutsideLibraryContentLocations_ShouldReturnPathError()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
(Guid artistId, Guid albumId, Guid trackId) = await SeedArtistGraphAsync(libraryId, Path.Combine(s_contentRootPath, "bohemian-rhapsody.flac"));
UpdateTrackRequest request = _updateTrackRequestFixture.Create(path: Path.Combine(s_outsideContentRootPath, "under-pressure.flac"));
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", request);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, "TrackPathMustBeWithinLibraryContentLocations");
}
[Fact]
public async Task UpdateTrack_WhenAReferencedContributorDoesNotExist_ShouldReturnMediaContributorNotFoundProblem()
{
@@ -325,7 +307,6 @@ public class UpdateTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
Guid libraryId = await SeedLibraryAsync(userId);
(Guid artistId, Guid albumId, Guid trackId) = await SeedArtistGraphAsync(libraryId, Path.Combine(s_contentRootPath, "bohemian-rhapsody.flac"));
UpdateTrackRequest request = _updateTrackRequestFixture.Create(
path: Path.Combine(s_contentRootPath, "somebody-to-love.flac"),
contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]);
// Act
@@ -350,7 +331,6 @@ public class UpdateTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
];
await SeedContributorsAsync(duplicatedContributors);
UpdateTrackRequest request = _updateTrackRequestFixture.Create(
path: Path.Combine(s_contentRootPath, "another-one-bites-the-dust.flac"),
moods: [],
isrcs: [],
contributors: duplicatedContributors,
@@ -373,32 +353,6 @@ public class UpdateTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
Assert.Contains(links, link => link.Role == MediaContributorRole.Guitar);
}
[Fact]
public async Task UpdateTrack_WhenPathIsNull_ShouldReturnUnprocessableEntity()
{
// Arrange
UpdateTrackRequest request = _updateTrackRequestFixture.Create(includePath: false);
// Act
HttpResponseMessage response = await PutTrackAsync(request);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, "TrackPathCannotBeEmpty");
}
[Fact]
public async Task UpdateTrack_WhenPathExceeds2048Characters_ShouldReturnUnprocessableEntity()
{
// Arrange
UpdateTrackRequest request = _updateTrackRequestFixture.Create(path: new Faker().Random.String2(2049));
// Act
HttpResponseMessage response = await PutTrackAsync(request);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, "TrackPathMustBeMaximum2048CharactersLong");
}
[Fact]
public async Task UpdateTrack_WhenMetadataIsNull_ShouldReturnUnprocessableEntity()
{
@@ -1004,7 +958,7 @@ public class UpdateTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
(Guid artistId, Guid albumId, Guid trackId) = await SeedArtistGraphAsync(libraryId, Path.Combine(s_contentRootPath, "bohemian-rhapsody.flac"));
UpdateTrackRequest request = _updateTrackRequestFixture.Create(path: Path.Combine(s_contentRootPath, "the-show-must-go-on.flac"));
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act & Assert
@@ -63,7 +63,7 @@ public class SaveMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(trackId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" && putRequest.Data is UpdateMusicTrackRequest forwarded && forwarded.Metadata!.Title == request.Metadata!.Title && forwarded.Path == request.Path);
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" && putRequest.Data is UpdateMusicTrackRequest forwarded && forwarded.Metadata!.Title == request.Metadata!.Title);
}
[Fact]
@@ -94,7 +94,6 @@ public class UpdateTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
SeedLibrary(libraryId, userId);
(Guid artistId, Guid albumId, Guid trackId) = SeedArtistGraph(libraryId);
UpdateTrackRequest request = _updateTrackRequestFixture.Create(
path: Path.Combine(s_contentRootPath, $"injected-{Guid.NewGuid():N}.flac"),
metadata: _musicTrackMetadataDtoFixture.Create(title: maliciousTitle),
moods: [],
isrcs: [],
@@ -44,8 +44,9 @@ public class UpdateArtistCommandMappingTests
// Arrange
Guid libraryId = Guid.NewGuid();
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
string updatedPath = "/music/queen/a-night-at-the-opera/03-you-re-my-best-friend.flac";
AddTrackCommand trackCommand = _addTrackCommandFixture.Create(trackId: trackId, path: updatedPath, trackNumber: 7);
string originalPath = artist.Albums.SelectMany(album => album.Tracks).First(track => track.Id.Value == trackId).Path;
string attemptedPath = "/music/queen/a-night-at-the-opera/03-you-re-my-best-friend.flac";
AddTrackCommand trackCommand = _addTrackCommandFixture.Create(trackId: trackId, path: attemptedPath, trackNumber: 7);
AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: [trackCommand]);
UpdateArtistCommand command = _updateArtistCommandFixture.Create(
libraryId: libraryId.ToString(),
@@ -67,7 +68,9 @@ public class UpdateArtistCommandMappingTests
Album updatedAlbum = result.Value.Albums.First(album => album.Id.Value == albumId);
Assert.Equal(albumCommand.Metadata!.Title, updatedAlbum.Metadata.Title);
Track updatedTrack = updatedAlbum.Tracks.First(track => track.Id.Value == trackId);
Assert.Equal(updatedPath, updatedTrack.Path);
// the file system path of an existing track is never changed by the update, it is set only when the track is created
Assert.Equal(originalPath, updatedTrack.Path);
Assert.NotEqual(attemptedPath, updatedTrack.Path);
Assert.Equal(7, updatedTrack.TrackNumber);
Assert.True(updatedTrack.DiscNumber.HasValue);
Assert.Equal(trackCommand.DiscNumber, updatedTrack.DiscNumber.Value);
@@ -45,8 +45,8 @@ public class UpdateTrackCommandMappingTests
// Arrange
Guid libraryId = Guid.NewGuid();
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
string updatedPath = "/music/queen/a-night-at-the-opera/02-love-of-my-life.flac";
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), path: updatedPath);
string originalPath = artist.Albums.SelectMany(album => album.Tracks).First(track => track.Id.Value == trackId).Path;
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
// Act
Result<Artist> result = command.ToDomainEntity(artist);
@@ -55,7 +55,8 @@ public class UpdateTrackCommandMappingTests
Assert.False(result.IsFailure);
Assert.Same(artist, result.Value);
Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId);
Assert.Equal(updatedPath, updatedTrack.Path);
// The file system path is never changed by the update, it is set only when the track is created.
Assert.Equal(originalPath, updatedTrack.Path);
Assert.Equal(command.Metadata!.Title, updatedTrack.Metadata.Title);
Assert.Equal(command.TrackNumber, updatedTrack.TrackNumber);
Assert.True(updatedTrack.DiscNumber.HasValue);
@@ -83,8 +84,8 @@ public class UpdateTrackCommandMappingTests
// Arrange
Guid libraryId = Guid.NewGuid();
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
string updatedPath = "/music/queen/a-night-at-the-opera/03-you-re-my-best-friend.flac";
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), path: updatedPath, includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false, contributors: [], ratings: []);
string originalPath = artist.Albums.SelectMany(album => album.Tracks).First(track => track.Id.Value == trackId).Path;
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false, contributors: [], ratings: []);
// Act
Result<Artist> result = command.ToDomainEntity(artist);
@@ -92,7 +93,8 @@ public class UpdateTrackCommandMappingTests
// Assert
Assert.False(result.IsFailure);
Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId);
Assert.Equal(updatedPath, updatedTrack.Path);
// the file system path is never changed by the update, it is set only when the track is created
Assert.Equal(originalPath, updatedTrack.Path);
Assert.Equal(command.TrackNumber, updatedTrack.TrackNumber);
Assert.False(updatedTrack.DiscNumber.HasValue);
Assert.False(updatedTrack.Script.HasValue);
@@ -38,7 +38,6 @@ public class UpdateTrackRequestMappingTests
Assert.Equal(artistId.ToString(), result.ArtistId);
Assert.Equal(albumId.ToString(), result.AlbumId);
Assert.Equal(trackId.ToString(), result.TrackId);
Assert.Equal(request.Path, result.Path);
Assert.Equal(request.Metadata, result.Metadata);
Assert.Equal(request.TrackNumber, result.TrackNumber);
Assert.Equal(request.DiscNumber, result.DiscNumber);
@@ -26,7 +26,6 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using NSubstitute;
using System;
@@ -54,7 +53,6 @@ public class UpdateTrackCommandHandlerTests
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<UpdateTrackCommand> _mockValidator;
private readonly IPathService _mockPathService;
private readonly UpdateTrackCommandHandler _sut;
private readonly Guid _userId;
private readonly UpdateTrackCommandFixture _updateTrackCommandFixture = new();
@@ -86,16 +84,14 @@ public class UpdateTrackCommandHandlerTests
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<UpdateTrackCommand>>();
_mockPathService = Substitute.For<IPathService>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated, the library ownership policy allows access, the validator passes,
// the track path is within the library content locations, the artist is updated and the library and contributors exist.
// the artist is updated and the library and contributors exist.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<UpdateTrackCommand>()).Returns([]);
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(true);
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
@@ -109,7 +105,7 @@ public class UpdateTrackCommandHandlerTests
return Result.From<IReadOnlyList<MediaContributorEntity>>([.. contributorIds.Select(contributorId => _mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()))]);
});
_sut = new UpdateTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService);
_sut = new UpdateTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
@@ -118,6 +114,7 @@ public class UpdateTrackCommandHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
string originalPath = existingArtist.Albums.SelectMany(album => album.Tracks).First(track => track.Id == trackId).Path;
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
ArtistEntity? updatedArtist = null;
TrackEntity? updatedTrack = null;
@@ -139,7 +136,8 @@ public class UpdateTrackCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
Assert.Equal(trackId, result.Value.Id);
Assert.Equal(command.Path, result.Value.Path);
// The file system path is preserved by the update, it is set only when the track is created.
Assert.Equal(originalPath, result.Value.Path);
Assert.Equal(command.Metadata!.Title, result.Value.Metadata!.Title);
Assert.Equal(command.Contributors!.Count, result.Value.Contributors!.Count);
await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
@@ -338,29 +336,6 @@ public class UpdateTrackCommandHandlerTests
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathIsNotWithinLibraryContentLocations_ShouldReturnPathError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId);
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(existingArtist));
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create(contentLocations: ["/music/queen"])));
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(false);
// Act
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackPathMustBeWithinLibraryContentLocations, result.FirstError);
_mockPathService.Received(1).IsPathWithin(command.Path!, Arg.Any<string>());
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenNoContributorsAreReferenced_ShouldNotQueryTheContributorRepository()
{
@@ -353,71 +353,6 @@ public class UpdateTrackCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Music.TrackIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateTrackCommand command = _updateTrackCommandFixture.Create(includePath: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateTrackCommand command = _updateTrackCommandFixture.Create(path: string.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty);
}
[Fact]
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
UpdateTrackCommand command = _updateTrackCommandFixture.Create(path: " ");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty);
}
[Fact]
public void Validate_WhenPathExceeds2048Characters_ShouldHaveValidationError()
{
// Arrange
UpdateTrackCommand command = _updateTrackCommandFixture.Create(path: new Faker().Random.String2(2049));
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong);
}
[Fact]
public void Validate_WhenPathIs2048Characters_ShouldNotHaveValidationError()
{
// Arrange
UpdateTrackCommand command = _updateTrackCommandFixture.Create(path: new Faker().Random.String2(2048));
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong);
}
[Fact]
public void Validate_WhenMetadataIsNull_ShouldHaveValidationError()
{
@@ -661,7 +661,7 @@ public class ArtistTests
Track track = _trackFixture.Create();
Album album = _albumFixture.Create(tracks: [track]);
Artist artist = _artistFixture.Create(albums: [album]);
string path = "C:\\Music\\queen\\bohemian-rhapsody.flac";
string originalPath = track.Path;
AudioMetadata metadata = _audioMetadataFixture.Create();
Optional<string> disambiguation = Optional<string>.Some("remastered");
Optional<int> discNumber = Optional<int>.Some(1);
@@ -681,7 +681,6 @@ public class ArtistTests
Result<Updated> result = artist.UpdateTrackInAlbum(
album,
track,
path,
metadata,
disambiguation,
11,
@@ -700,7 +699,8 @@ public class ArtistTests
// Assert
Assert.False(result.IsFailure);
Assert.Equal(path, track.Path);
// The file system path is not part of the track update, it is set only when the track is created.
Assert.Equal(originalPath, track.Path);
Assert.Equal(metadata, track.Metadata);
Assert.Equal(disambiguation, track.Disambiguation);
Assert.Equal(11, track.TrackNumber);
@@ -735,7 +735,6 @@ public class ArtistTests
Result<Updated> result = artist.UpdateTrackInAlbum(
foreignAlbum,
track,
"C:\\Music\\queen\\bohemian-rhapsody.flac",
_audioMetadataFixture.Create(),
Optional<string>.None(),
11,
@@ -773,7 +772,6 @@ public class ArtistTests
Result<Updated> result = artist.UpdateTrackInAlbum(
album,
track,
"C:\\Music\\queen\\bohemian-rhapsody.flac",
_audioMetadataFixture.Create(),
Optional<string>.None(),
11,
@@ -190,8 +190,8 @@ public class TrackTests
{
// Arrange
Track track = _trackFixture.Create();
string originalPath = track.Path;
List<Mood> originalMoods = [.. track.Moods];
string path = "C:\\Music\\queen\\bohemian-rhapsody.flac";
AudioMetadata metadata = _audioMetadataFixture.Create();
Optional<string> disambiguation = Optional<string>.Some("remastered");
Optional<int> discNumber = Optional<int>.Some(2);
@@ -206,7 +206,6 @@ public class TrackTests
// Act
Result<Updated> result = track.UpdateDetails(
path,
metadata,
disambiguation,
7,
@@ -221,7 +220,6 @@ public class TrackTests
// Assert
Assert.False(result.IsFailure);
Assert.Equal(path, track.Path);
Assert.Equal(metadata, track.Metadata);
Assert.Equal(disambiguation, track.Disambiguation);
Assert.Equal(7, track.TrackNumber);
@@ -235,7 +233,9 @@ public class TrackTests
Assert.Equal(trackId, track.MusicBrainzTrackId);
Assert.True(track.UpdatedOnUtc.HasValue);
Assert.True(track.UpdatedOnUtc.Value >= beforeUpdate);
// the collections are not part of the details update
// The file system path is not part of the details update, it is set only when the track is created.
Assert.Equal(originalPath, track.Path);
// The collections are not part of the details update.
Assert.Equal(originalMoods, track.Moods);
}
@@ -376,7 +376,6 @@ public class TrackTests
// Act
Result<Updated> result = track.UpdateDetails(
"C:\\Music\\queen\\bohemian-rhapsody.flac",
_audioMetadataFixture.Create(),
Optional<string>.None(),
11,
@@ -158,7 +158,6 @@ public class UpdateTrackEndpointTests
command.ArtistId == artistId.ToString() &&
command.AlbumId == albumId.ToString() &&
command.TrackId == trackId.ToString() &&
command.Path == request.Path &&
command.Metadata == request.Metadata &&
command.TrackNumber == request.TrackNumber &&
command.DiscNumber == request.DiscNumber &&