Moves the cancellation token to the last parameter position.

This commit is contained in:
BinaryAlley committed 2026-10-12 23:02:05 +03:00
1 parent 9a7a1dffb2
commit 006df1da3a
6 files changed
+741 -29

No files matched your search

@@ -8,6 +8,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
using Microsoft.Extensions.Options;
using NSubstitute;
@@ -75,7 +76,7 @@ public class MusicArtworkServiceTests
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -90,7 +91,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -107,7 +108,7 @@ public class MusicArtworkServiceTests
.Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file"));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -196,6 +197,307 @@ public class MusicArtworkServiceTests
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
}
[Fact]
public async Task SaveAlbumArtworkAsync_WhenAnArtworkStreamIsUploaded_ShouldStoreItAsTheCoverAndDeleteTheTemporaryUpload()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
byte[] uploadedBytes = [1, 2, 3, 4, 5, 6, 7, 8];
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg");
string? capturedTemporaryPath = null;
byte[]? capturedBytes = null;
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(callInfo =>
{
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
capturedBytes = File.ReadAllBytes(capturedTemporaryPath);
return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.jpg")));
});
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
.Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath)));
await using MemoryStream artworkStream = new(uploadedBytes);
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value);
Assert.NotNull(capturedTemporaryPath);
Assert.StartsWith(Path.GetTempPath(), capturedTemporaryPath);
Assert.EndsWith(".jpg", capturedTemporaryPath);
Assert.Equal(uploadedBytes, capturedBytes);
Assert.False(File.Exists(capturedTemporaryPath));
_mockFileProviderService.Received(1).RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg");
}
[Fact]
public async Task SaveAlbumArtworkAsync_WhenAnArtworkStreamIsUploadedWithAReleaseType_ShouldStoreTheArtworkUnderTheReleaseTypeDirectory()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string releaseTypeName = "Single";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName);
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg");
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.jpg"))));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
.Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath)));
await using MemoryStream artworkStream = new([1, 2, 3]);
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", releaseTypeName, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.Received(1).CopyFile(
Arg.Any<FileSystemPathId>(),
Arg.Is<FileSystemPathId>(pathId => pathId.Path == artworkDirectoryPath),
true);
}
[Fact]
public async Task SaveAlbumArtworkAsync_WhenTheDownstreamStorageFails_ShouldStillDeleteTheTemporaryUpload()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string? capturedTemporaryPath = null;
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(callInfo =>
{
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
return Error.Failure("FileSystem.Error", "Failed to copy the artwork");
});
await using MemoryStream artworkStream = new([1, 2, 3, 4]);
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
Assert.NotNull(capturedTemporaryPath);
Assert.False(File.Exists(capturedTemporaryPath));
_mockFileProviderService.DidNotReceive().RenameFile(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
}
[Theory]
[InlineData("cover")] // a name without an extension falls back to the .img extension
[InlineData("")] // an empty name falls back to the .img extension
[InlineData(null)] // a null name falls back to the .img extension
public async Task SaveAlbumArtworkAsync_WhenTheUploadedFileNameHasNoExtension_ShouldBufferTheUploadWithTheImgExtension(string? fileName)
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string? capturedTemporaryPath = null;
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(callInfo =>
{
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.img")));
});
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
await using MemoryStream artworkStream = new([1, 2, 3]);
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, fileName!, null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(capturedTemporaryPath);
Assert.EndsWith(".img", capturedTemporaryPath);
}
[Fact]
public async Task SaveArtistArtworkAsync_WhenAnArtworkStreamIsUploaded_ShouldStoreItAsTheCoverAndDeleteTheTemporaryUpload()
{
// Arrange
Guid libraryId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
byte[] uploadedBytes = [9, 8, 7, 6, 5];
string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName);
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.png");
string? capturedTemporaryPath = null;
byte[]? capturedBytes = null;
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.PNG));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(callInfo =>
{
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
capturedBytes = File.ReadAllBytes(capturedTemporaryPath);
return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.png")));
});
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.png")
.Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath)));
await using MemoryStream artworkStream = new(uploadedBytes);
// Act
Result<string> result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistName, artworkStream, "cover.png", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value);
Assert.NotNull(capturedTemporaryPath);
Assert.StartsWith(Path.GetTempPath(), capturedTemporaryPath);
Assert.EndsWith(".png", capturedTemporaryPath);
Assert.Equal(uploadedBytes, capturedBytes);
Assert.False(File.Exists(capturedTemporaryPath));
_mockFileProviderService.Received(1).RenameFile(Arg.Any<FileSystemPathId>(), "cover.png");
}
[Fact]
public async Task SaveArtistArtworkAsync_WhenTheDownstreamStorageFails_ShouldStillDeleteTheTemporaryUpload()
{
// Arrange
Guid libraryId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName);
string? capturedTemporaryPath = null;
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.PNG));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(callInfo =>
{
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
return Error.Failure("FileSystem.Error", "Failed to copy the artwork");
});
await using MemoryStream artworkStream = new([1, 2, 3]);
// Act
Result<string> result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistName, artworkStream, "cover.png", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
Assert.NotNull(capturedTemporaryPath);
Assert.False(File.Exists(capturedTemporaryPath));
}
[Theory]
[InlineData(null)] // a null path is a no-op
[InlineData("")] // an empty path is a no-op
[InlineData(" ")] // a whitespace path is a no-op
public void DeleteStoredArtwork_WhenThePathIsMissing_ShouldReturnDeletedWithoutTouchingTheFileSystem(string? artworkRelativePath)
{
// Act
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath!);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.DidNotReceive().FileExists(Arg.Any<FileSystemPathId>());
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
}
[Fact]
public void DeleteStoredArtwork_WhenTheFileDoesNotExist_ShouldReturnDeleted()
{
// Arrange
string artworkRelativePath = $"\\media\\music\\cover-{Guid.NewGuid():N}.jpg";
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
// Act
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
}
[Fact]
public void DeleteStoredArtwork_WhenTheFileExists_ShouldDeleteItAndReturnDeleted()
{
// Arrange
string artworkRelativePath = $"\\media\\music\\cover-{Guid.NewGuid():N}.jpg";
string expectedAbsolutePath = Path.Combine(AppContext.BaseDirectory, artworkRelativePath.TrimStart('\\'));
_mockFileProviderService.FileExists(Arg.Is<FileSystemPathId>(pathId => pathId.Path == expectedAbsolutePath))
.Returns(Result.From(true));
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
// Act
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.Received(1).DeleteFile(Arg.Is<FileSystemPathId>(pathId => pathId.Path == expectedAbsolutePath));
}
[Fact]
public void DeleteStoredArtwork_WhenTheExistenceCheckFails_ShouldReturnTheError()
{
// Arrange
string artworkRelativePath = "\\media\\music\\cover.jpg";
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
.Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file"));
// Act
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
}
[Fact]
public void DeleteStoredArtwork_WhenDeletingTheFileFails_ShouldReturnDeleted()
{
// Arrange
string artworkRelativePath = "\\media\\music\\cover.jpg";
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>())
.Returns(Error.Failure("FileSystem.Error", "Failed to delete the artwork file"));
// Act
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.Received(1).DeleteFile(Arg.Any<FileSystemPathId>());
}
/// <summary>
/// Stubs the path service so that building the artwork directory paths succeeds.
/// </summary>
@@ -238,15 +540,45 @@ public class MusicArtworkServiceTests
/// <param name="libraryName">The name of the media library the album belongs to.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <param name="albumTitle">The title of the album.</param>
/// <param name="releaseTypeName">Optional. The name of the release type directory the album is stored under.</param>
/// <returns>The expected file system path of the album artwork directory.</returns>
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle)
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null)
{
if (string.IsNullOrWhiteSpace(releaseTypeName))
{
return Path.Combine(
AppContext.BaseDirectory,
"media",
"music",
$"{libraryName}-{libraryId}",
artistName,
$"{albumTitle}-{albumId}");
}
return Path.Combine(
AppContext.BaseDirectory,
"media",
"music",
$"{libraryName}-{libraryId}",
artistName,
releaseTypeName,
$"{albumTitle}-{albumId}");
}
/// <summary>
/// Builds the file system path of the directory that the artwork of the artist is stored into.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
/// <param name="artistName">The name of the artist.</param>
/// <returns>The expected file system path of the artist artwork directory.</returns>
private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName)
{
return Path.Combine(
AppContext.BaseDirectory,
"media",
"music",
$"{libraryName}-{libraryId}",
artistName);
}
}
@@ -272,8 +272,8 @@ public class MusicMediaLibraryScanArtworkEnricherTests
Arg.Any<string>(),
album.Title,
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
Arg.Any<CancellationToken>(),
Arg.Any<string?>());
Arg.Any<string?>(),
Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, album.Id, Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
@@ -553,7 +553,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests
{
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("/media/music/cover.jpg"));
_mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>(), Arg.Any<string?>())
_mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From("/media/music/cover.jpg"));
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>()).Returns(Result.Deleted);
_mockMusicArtworkService.DeleteAlbumArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>()).Returns(Result.Deleted);