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

@@ -104,7 +104,7 @@ public class MusicArtworkServiceTests
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -150,7 +150,7 @@ public class MusicArtworkServiceTests
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, expectedFileName))));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, type: artworkType, ordinal: ordinal), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, type: artworkType, ordinal: ordinal), null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -187,7 +187,7 @@ public class MusicArtworkServiceTests
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName: " ", albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName: " ", albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -218,7 +218,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: linkPath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -246,7 +246,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// 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);
@@ -272,7 +272,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// 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);
@@ -309,7 +309,7 @@ public class MusicArtworkServiceTests
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -327,7 +327,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -342,7 +342,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -375,7 +375,7 @@ public class MusicArtworkServiceTests
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -402,7 +402,7 @@ public class MusicArtworkServiceTests
// Act
async Task Act()
{
await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), cancellationTokenSource.Token);
await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, cancellationTokenSource.Token);
}
// Assert
@@ -422,7 +422,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// 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);
@@ -458,7 +458,7 @@ public class MusicArtworkServiceTests
.Returns(Error.Failure("Directory.Error", "Failed to create the artwork directory"));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -494,7 +494,7 @@ public class MusicArtworkServiceTests
.Returns(Error.Failure("Directory.Error", "Failed to check the artwork directory"));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -530,7 +530,7 @@ public class MusicArtworkServiceTests
.Returns(Error.Failure("FileSystem.Error", "Failed to copy the artwork"));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -568,7 +568,7 @@ public class MusicArtworkServiceTests
.Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork"));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -613,7 +613,7 @@ public class MusicArtworkServiceTests
});
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -654,6 +654,193 @@ public class MusicArtworkServiceTests
_mockFileProviderService.Received(1).DeleteFile(bookletFileId);
}
[Fact]
public async Task SaveAlbumArtworkAsync_WhenAnArtworkStreamIsUploaded_ShouldStoreTheFileOnDiskAndDeleteTheTemporaryUpload()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
byte[] uploadedBytes = [10, 20, 30, 40, 50];
string libraryDirectoryPath = BuildLibraryDirectoryPath(libraryName, libraryId);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string expectedStoredPath = Path.Combine(artworkDirectoryPath, "cover.jpg");
string? temporaryUploadPath = null;
MockRealFileSystemStubs(pathId => temporaryUploadPath = pathId.Path);
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
await using MemoryStream artworkStream = new(uploadedBytes);
try
{
// 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(expectedStoredPath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value);
Assert.True(File.Exists(expectedStoredPath));
Assert.Equal(uploadedBytes, File.ReadAllBytes(expectedStoredPath));
Assert.NotNull(temporaryUploadPath);
Assert.StartsWith(Path.GetTempPath(), temporaryUploadPath);
Assert.EndsWith(".jpg", temporaryUploadPath);
Assert.False(File.Exists(temporaryUploadPath));
}
finally
{
if (Directory.Exists(libraryDirectoryPath))
Directory.Delete(libraryDirectoryPath, recursive: true);
}
}
[Fact]
public async Task SaveArtistArtworkAsync_WhenAnArtworkStreamIsUploaded_ShouldStoreTheFileOnDiskAndDeleteTheTemporaryUpload()
{
// Arrange
Guid libraryId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
byte[] uploadedBytes = [60, 70, 80, 90];
string libraryDirectoryPath = BuildLibraryDirectoryPath(libraryName, libraryId);
string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName);
string expectedStoredPath = Path.Combine(artworkDirectoryPath, "cover.png");
string? temporaryUploadPath = null;
MockRealFileSystemStubs(pathId => temporaryUploadPath = pathId.Path);
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.PNG));
await using MemoryStream artworkStream = new(uploadedBytes);
try
{
// Act
Result<string> result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistName, artworkStream, "cover.png", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedStoredPath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value);
Assert.True(File.Exists(expectedStoredPath));
Assert.Equal(uploadedBytes, File.ReadAllBytes(expectedStoredPath));
Assert.NotNull(temporaryUploadPath);
Assert.StartsWith(Path.GetTempPath(), temporaryUploadPath);
Assert.EndsWith(".png", temporaryUploadPath);
Assert.False(File.Exists(temporaryUploadPath));
}
finally
{
if (Directory.Exists(libraryDirectoryPath))
Directory.Delete(libraryDirectoryPath, recursive: true);
}
}
[Fact]
public void DeleteStoredArtwork_WhenTheFileExists_ShouldDeleteTheRealFile()
{
// Arrange
string libraryDirectoryPath = Path.Combine(AppContext.BaseDirectory, "media", "music", $"delete-{Guid.NewGuid():N}");
Directory.CreateDirectory(libraryDirectoryPath);
string artworkPath = Path.Combine(libraryDirectoryPath, "cover.jpg");
File.WriteAllBytes(artworkPath, [1, 2, 3]);
string artworkRelativePath = artworkPath[AppContext.BaseDirectory.Length..].Insert(0, "\\");
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
.Returns(callInfo => Result.From(File.Exists(callInfo.Arg<FileSystemPathId>().Path)));
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>())
.Returns(callInfo =>
{
File.Delete(callInfo.Arg<FileSystemPathId>().Path);
return Result.Deleted;
});
try
{
// Act
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
// Assert
Assert.False(result.IsFailure);
Assert.False(File.Exists(artworkPath));
}
finally
{
if (Directory.Exists(libraryDirectoryPath))
Directory.Delete(libraryDirectoryPath, recursive: true);
}
}
[Fact]
public void DeleteStoredArtwork_WhenTheFileIsMissing_ShouldReturnDeleted()
{
// Arrange
string artworkRelativePath = $"\\media\\music\\missing-{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>());
}
[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>());
}
/// <summary>
/// Stubs the path and file system services so that the artwork storage pipeline performs real file system operations.
/// </summary>
/// <param name="onCopySource">Optional callback invoked with the source file of every file copy, used to observe the temporary upload.</param>
private void MockRealFileSystemStubs(Action<FileSystemPathId>? onCopySource = null)
{
MockPathBuilding();
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
.Returns(callInfo => Result.From(File.Exists(callInfo.Arg<FileSystemPathId>().Path)));
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
.Returns(callInfo => Result.From(Directory.Exists(callInfo.Arg<FileSystemPathId>().Path)));
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
.Returns(callInfo =>
{
string createdDirectoryPath = Path.Combine(callInfo.ArgAt<FileSystemPathId>(0).Path, callInfo.ArgAt<string>(1));
Directory.CreateDirectory(createdDirectoryPath);
return Result.From(_fileSystemPathIdFixture.Create(createdDirectoryPath));
});
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(callInfo =>
{
FileSystemPathId sourcePathId = callInfo.ArgAt<FileSystemPathId>(0);
FileSystemPathId destinationDirectoryPathId = callInfo.ArgAt<FileSystemPathId>(1);
onCopySource?.Invoke(sourcePathId);
string destinationFilePath = Path.Combine(destinationDirectoryPathId.Path, Path.GetFileName(sourcePathId.Path));
File.Copy(sourcePathId.Path, destinationFilePath, overwrite: true);
return Result.From(_fileSystemPathIdFixture.Create(destinationFilePath));
});
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
.Returns(callInfo =>
{
FileSystemPathId sourcePathId = callInfo.ArgAt<FileSystemPathId>(0);
string newFileName = callInfo.ArgAt<string>(1);
string renamedFilePath = Path.Combine(Path.GetDirectoryName(sourcePathId.Path)!, newFileName);
File.Move(sourcePathId.Path, renamedFilePath);
return Result.From(_fileSystemPathIdFixture.Create(renamedFilePath));
});
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>())
.Returns(callInfo =>
{
File.Delete(callInfo.Arg<FileSystemPathId>().Path);
return Result.Deleted;
});
}
/// <summary>
/// Stubs the path service so that building the artwork directory paths succeeds.
/// </summary>
@@ -708,6 +895,38 @@ public class MusicArtworkServiceTests
$"{albumTitle}-{albumId}");
}
/// <summary>
/// Builds the file system path of the directory of a music media library.
/// </summary>
/// <param name="libraryName">The name of the media library.</param>
/// <param name="libraryId">The Id of the media library.</param>
/// <returns>The expected file system path of the music media library directory.</returns>
private static string BuildLibraryDirectoryPath(string libraryName, Guid libraryId)
{
return Path.Combine(
AppContext.BaseDirectory,
"media",
"music",
$"{libraryName}-{libraryId}");
}
/// <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);
}
/// <summary>
/// Creates a temporary image file and returns its path.
/// </summary>
@@ -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);