Adds the local music artwork plugin, its fixtures, and its unit and integration test suites

This commit is contained in:
BinaryAlley committed 2026-10-04 21:16:42 +03:00
1 parent fb05561619
commit 62b0e9297a
25 files changed
+2720

No files matched your search

@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.Fixtures.Common.Models.DTO.Settings;
/// <summary>
/// Fixture class for the <see cref="LocalMusicArtworkSettingsDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class LocalMusicArtworkSettingsDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="LocalMusicArtworkSettingsDto"/> instance with randomized test data.
/// </summary>
/// <param name="shouldExtractEmbeddedCover">Optional. Whether the cover embedded in the audio files is extracted when the album has no cover image on disk.</param>
/// <returns>A configured <see cref="LocalMusicArtworkSettingsDto"/> instance.</returns>
public LocalMusicArtworkSettingsDto Create(
bool? shouldExtractEmbeddedCover = null)
{
return new LocalMusicArtworkSettingsDto
{
ShouldExtractEmbeddedCover = shouldExtractEmbeddedCover ?? _faker.Random.Bool()
};
}
/// <summary>
/// Creates multiple <see cref="LocalMusicArtworkSettingsDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="LocalMusicArtworkSettingsDto"/> instances.</returns>
public List<LocalMusicArtworkSettingsDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,124 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.Fixtures.Core;
/// <summary>
/// Builds minimal, structurally valid WAV files used as test input for the artwork scanning and embedded cover extraction tests.
/// The files are produced into a temporary directory at test runtime, because a WAV is a binary container whose embedded pictures can only be written by the tagging library itself.
/// </summary>
[ExcludeFromCodeCoverage]
public static class TestAudioFileFactory
{
/// <summary>
/// Creates a minimal, untagged PCM WAV file.
/// </summary>
/// <param name="path">The path where the WAV is written.</param>
/// <param name="durationMs">The duration of the audio of the file, in milliseconds.</param>
public static void CreateWav(string path, int durationMs = 200)
{
WriteFile(path, BuildWav(durationMs));
}
/// <summary>
/// Creates a PCM WAV file that carries the provided image as its embedded front cover.
/// </summary>
/// <param name="path">The path where the WAV is written.</param>
/// <param name="imageBytes">The bytes of the embedded cover image.</param>
/// <param name="mimeType">The MIME type of the embedded cover image, defaulting to JPEG.</param>
/// <param name="durationMs">The duration of the audio of the file, in milliseconds.</param>
public static void CreateWavWithEmbeddedCover(string path, byte[] imageBytes, string? mimeType = "image/jpeg", int durationMs = 200)
{
CreateTaggedWav(path, tagFile =>
{
tagFile.Tag.Pictures =
[
new TagLib.Picture
{
MimeType = mimeType!,
Type = TagLib.PictureType.FrontCover,
Data = [.. imageBytes]
}
];
}, durationMs);
}
/// <summary>
/// Creates a PCM WAV file whose embedded tags are configured by the provided callback.
/// </summary>
/// <param name="path">The path where the WAV is written.</param>
/// <param name="configureTags">The callback that configures the tags of the file.</param>
/// <param name="durationMs">The duration of the audio of the file, in milliseconds.</param>
public static void CreateTaggedWav(string path, Action<TagLib.File> configureTags, int durationMs = 200)
{
WriteFile(path, BuildWav(durationMs));
using (TagLib.File tagFile = TagLib.File.Create(path))
{
configureTags(tagFile);
tagFile.Save();
}
}
/// <summary>
/// Creates a file whose content is not a recognizable audio container, so that the resilience of the embedded cover extraction can be exercised.
/// </summary>
/// <param name="path">The path where the file is written.</param>
public static void CreateUnsupportedFile(string path)
{
WriteFile(path, Encoding.UTF8.GetBytes("This is not an audio file."));
}
/// <summary>
/// Writes the provided bytes at <paramref name="path"/>, creating the containing directory when it does not exist yet.
/// </summary>
/// <param name="path">The path where the bytes are written.</param>
/// <param name="contents">The bytes of the file.</param>
private static void WriteFile(string path, byte[] contents)
{
string? directory = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(directory))
Directory.CreateDirectory(directory);
File.WriteAllBytes(path, contents);
}
/// <summary>
/// Builds the bytes of a minimal, valid PCM WAV file with a single silent audio channel.
/// </summary>
/// <param name="durationMs">The duration of the audio of the file, in milliseconds.</param>
/// <returns>The bytes of the WAV file.</returns>
private static byte[] BuildWav(int durationMs)
{
const int SAMPLE_RATE = 44100;
const short CHANNELS = 1;
const short BITS_PER_SAMPLE = 16;
int bytesPerSample = BITS_PER_SAMPLE / 8;
int dataSize = SAMPLE_RATE * CHANNELS * bytesPerSample * durationMs / 1000;
using (MemoryStream memoryStream = new())
{
using (BinaryWriter writer = new(memoryStream))
{
writer.Write(Encoding.ASCII.GetBytes("RIFF"));
writer.Write(36 + dataSize);
writer.Write(Encoding.ASCII.GetBytes("WAVE"));
writer.Write(Encoding.ASCII.GetBytes("fmt "));
writer.Write(16);
writer.Write((short)1);
writer.Write(CHANNELS);
writer.Write(SAMPLE_RATE);
writer.Write(SAMPLE_RATE * CHANNELS * bytesPerSample);
writer.Write((short)(CHANNELS * bytesPerSample));
writer.Write(BITS_PER_SAMPLE);
writer.Write(Encoding.ASCII.GetBytes("data"));
writer.Write(dataSize);
writer.Write(new byte[dataSize]);
}
return memoryStream.ToArray();
}
}
}
@@ -0,0 +1,91 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.Fixtures.Core;
/// <summary>
/// Creates image files of the formats a local music library stores next to its tracks, so that artwork scanning can be exercised against real files.
/// Each file carries the magic bytes of its format, mirroring the images a music library keeps in the folders of its artists and albums.
/// </summary>
[ExcludeFromCodeCoverage]
public static class TestImageFileFactory
{
/// <summary>
/// Creates a JPEG image file at the provided path.
/// </summary>
/// <param name="path">The path where the image is written.</param>
public static void CreateJpeg(string path)
{
WriteFile(path, [0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0xFF, 0xD9]);
}
/// <summary>
/// Creates a PNG image file at the provided path.
/// </summary>
/// <param name="path">The path where the image is written.</param>
public static void CreatePng(string path)
{
WriteFile(path, [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52]);
}
/// <summary>
/// Creates a WebP image file at the provided path.
/// </summary>
/// <param name="path">The path where the image is written.</param>
public static void CreateWebp(string path)
{
WriteFile(path, [.. Encoding.ASCII.GetBytes("RIFF"), 0x00, 0x00, 0x00, 0x00, .. Encoding.ASCII.GetBytes("WEBP")]);
}
/// <summary>
/// Creates a BMP image file at the provided path.
/// </summary>
/// <param name="path">The path where the image is written.</param>
public static void CreateBmp(string path)
{
WriteFile(path, [0x42, 0x4D, 0x00, 0x00, 0x00, 0x00]);
}
/// <summary>
/// Creates a GIF image file at the provided path.
/// </summary>
/// <param name="path">The path where the image is written.</param>
public static void CreateGif(string path)
{
WriteFile(path, [.. Encoding.ASCII.GetBytes("GIF89a")]);
}
/// <summary>
/// Creates a TIFF image file at the provided path.
/// </summary>
/// <param name="path">The path where the image is written.</param>
public static void CreateTiff(string path)
{
WriteFile(path, [0x49, 0x49, 0x2A, 0x00]);
}
/// <summary>
/// Creates a file whose content is not an image, so that the exclusion of non image files can be exercised.
/// </summary>
/// <param name="path">The path where the file is written.</param>
public static void CreateTextFile(string path)
{
WriteFile(path, Encoding.UTF8.GetBytes("This is not an image."));
}
/// <summary>
/// Writes the provided bytes at <paramref name="path"/>, creating the containing directory when it does not exist yet.
/// </summary>
/// <param name="path">The path where the bytes are written.</param>
/// <param name="contents">The bytes of the file.</param>
private static void WriteFile(string path, byte[] contents)
{
string? directory = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(directory))
Directory.CreateDirectory(directory);
File.WriteAllBytes(path, contents);
}
}
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
<IsPackable>false</IsPackable>
<IsTestProject>false</IsTestProject>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoFixture" />
<PackageReference Include="AutoFixture.AutoNSubstitute" />
<PackageReference Include="AutoFixture.Xunit2" />
<PackageReference Include="Bogus" />
<PackageReference Include="TagLibSharp" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.LocalMusicArtwork\Lumina.Plugins.LocalMusicArtwork.csproj" />
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,21 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lumina.Plugins.LocalMusicArtwork.Fixtures")]
[assembly: AssemblyProduct("Lumina.Plugins.LocalMusicArtwork.Fixtures")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3401EC09-8D4F-4E45-9F40-62FEA3C81373")]
[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.UnitTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.IntegrationTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
@@ -0,0 +1,300 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.LocalMusicArtwork.Core;
using Lumina.Plugins.LocalMusicArtwork.Core.Settings;
using Lumina.Plugins.LocalMusicArtwork.Fixtures.Common.Models.DTO.Settings;
using Lumina.Plugins.LocalMusicArtwork.Fixtures.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.IntegrationTests.Core;
/// <summary>
/// Contains integration tests for the <see cref="LocalMusicAlbumArtworkProvider"/> class, reading real image and audio files from the file system.
/// </summary>
[ExcludeFromCodeCoverage]
public class LocalMusicAlbumArtworkProviderTests : IDisposable
{
private static readonly byte[] s_embeddedCoverBytes = [0xFF, 0xD8, 0xFF, 0xE0, 0x01, 0x02, 0x03, 0xFF, 0xD9];
private readonly AlbumMetadataLookupDtoFixture _albumMetadataLookupDtoFixture = new();
private readonly LocalMusicArtworkSettingsDtoFixture _localMusicArtworkSettingsDtoFixture = new();
private readonly string _temporaryDirectory;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMusicAlbumArtworkProviderTests"/> class.
/// </summary>
public LocalMusicAlbumArtworkProviderTests()
{
_temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-local-music-album-artwork-{Guid.NewGuid():N}");
Directory.CreateDirectory(_temporaryDirectory);
}
[Fact]
public void Name_WhenCalled_ShouldReturnTheProviderDisplayName()
{
// Arrange
LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true);
// Act
string result = sut.Name;
// Assert
Assert.Equal("Local Music Artwork", result);
}
[Fact]
public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic()
{
// Arrange
LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true);
// Act
IReadOnlyList<LibraryType> result = sut.SupportedLibraryTypes;
// Assert
Assert.Equal([LibraryType.Music], result);
}
[Fact]
public void RequiresWebAccess_WhenCalled_ShouldReturnFalse()
{
// Arrange
LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true);
// Act
bool result = sut.RequiresWebAccess;
// Assert
Assert.False(result);
}
[Fact]
public async Task GetArtworkAsync_WhenTheAlbumHasDiskImages_ShouldReturnTheDiskArtwork()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg"));
TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png"));
TestAudioFileFactory.CreateWav(Path.Combine(albumDirectory, "track.wav"));
string trackPath = Path.Combine(albumDirectory, "track.wav");
LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true);
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath);
// Act
IReadOnlyList<ArtworkDto> result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
List<ArtworkDto> expected =
[
new(ArtworkType.Cover, 0, Path.Combine(albumDirectory, "cover.jpg"), null),
new(ArtworkType.Back, 0, Path.Combine(albumDirectory, "back.png"), null)
];
Assert.Equal(expected, result);
}
[Fact]
public async Task GetArtworkAsync_WhenTheAlbumHasACoverOnDisk_ShouldNotExtractTheEmbeddedCover()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg"));
TestAudioFileFactory.CreateWavWithEmbeddedCover(Path.Combine(albumDirectory, "track.wav"), s_embeddedCoverBytes);
string trackPath = Path.Combine(albumDirectory, "track.wav");
LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true);
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath);
// Act
IReadOnlyList<ArtworkDto> result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
ArtworkDto artwork = Assert.Single(result);
Assert.Equal(ArtworkType.Cover, artwork.Type);
Assert.Equal(0, artwork.Ordinal);
Assert.Equal(Path.Combine(albumDirectory, "cover.jpg"), artwork.LocalPath);
Assert.Null(artwork.RemoteUrl);
Assert.False(artwork.IsTemporary);
}
[Fact]
public async Task GetArtworkAsync_WhenTheAlbumHasNoCoverOnDiskAndExtractionIsEnabled_ShouldReturnTheEmbeddedCover()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png"));
TestAudioFileFactory.CreateWavWithEmbeddedCover(Path.Combine(albumDirectory, "track.wav"), s_embeddedCoverBytes);
string trackPath = Path.Combine(albumDirectory, "track.wav");
LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true);
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath);
// Act
IReadOnlyList<ArtworkDto> result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Equal(2, result.Count);
Assert.Equal(ArtworkType.Back, result[0].Type);
Assert.Equal(0, result[0].Ordinal);
Assert.Equal(Path.Combine(albumDirectory, "back.png"), result[0].LocalPath);
Assert.Null(result[0].RemoteUrl);
Assert.False(result[0].IsTemporary);
Assert.Equal(ArtworkType.Cover, result[1].Type);
Assert.Equal(0, result[1].Ordinal);
Assert.NotNull(result[1].LocalPath);
Assert.EndsWith(".jpg", result[1].LocalPath);
Assert.True(File.Exists(result[1].LocalPath));
Assert.Equal(s_embeddedCoverBytes, File.ReadAllBytes(result[1].LocalPath!));
Assert.Null(result[1].RemoteUrl);
Assert.True(result[1].IsTemporary);
File.Delete(result[1].LocalPath!);
}
[Fact]
public async Task GetArtworkAsync_WhenTheAlbumHasNoCoverOnDiskAndExtractionIsDisabled_ShouldReturnOnlyTheDiskArtwork()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png"));
TestAudioFileFactory.CreateWavWithEmbeddedCover(Path.Combine(albumDirectory, "track.wav"), s_embeddedCoverBytes);
string trackPath = Path.Combine(albumDirectory, "track.wav");
LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: false);
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath);
// Act
IReadOnlyList<ArtworkDto> result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
ArtworkDto artwork = Assert.Single(result);
Assert.Equal(ArtworkType.Back, artwork.Type);
Assert.Equal(0, artwork.Ordinal);
Assert.Equal(Path.Combine(albumDirectory, "back.png"), artwork.LocalPath);
Assert.Null(artwork.RemoteUrl);
Assert.False(artwork.IsTemporary);
}
[Fact]
public async Task GetArtworkAsync_WhenTheAlbumHasNoCoverOnDiskAndTheTrackHasNoEmbeddedCover_ShouldReturnOnlyTheDiskArtwork()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png"));
TestAudioFileFactory.CreateWav(Path.Combine(albumDirectory, "track.wav"));
string trackPath = Path.Combine(albumDirectory, "track.wav");
LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true);
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath);
// Act
IReadOnlyList<ArtworkDto> result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
ArtworkDto artwork = Assert.Single(result);
Assert.Equal(ArtworkType.Back, artwork.Type);
Assert.Equal(Path.Combine(albumDirectory, "back.png"), artwork.LocalPath);
}
[Fact]
public async Task GetArtworkAsync_WhenTheTrackHasNoImagesAtAll_ShouldReturnEmpty()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestAudioFileFactory.CreateWav(Path.Combine(albumDirectory, "track.wav"));
string trackPath = Path.Combine(albumDirectory, "track.wav");
LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true);
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath);
// Act
IReadOnlyList<ArtworkDto> result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Empty(result);
}
[Theory]
[InlineData(null)] // a null path contributes no artwork
[InlineData("")] // an empty path contributes no artwork
[InlineData(" ")] // a white space path contributes no artwork
[InlineData("track.flac")] // a path without a directory part contributes no artwork
public async Task GetArtworkAsync_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath)
{
// Arrange
LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true);
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath);
// Act
IReadOnlyList<ArtworkDto> result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Empty(result);
}
[Fact]
public async Task GetArtworkAsync_WhenTheTrackDirectoryDoesNotExist_ShouldReturnEmpty()
{
// Arrange
string trackPath = Path.Combine(_temporaryDirectory, "Missing", "Album", "track.wav");
LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true);
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath);
// Act
IReadOnlyList<ArtworkDto> result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Empty(result);
}
[Fact]
public async Task GetArtworkAsync_WhenTheAlbumHasNoCoverOnDiskAndTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation()
{
// Arrange
using (CancellationTokenSource cancellationTokenSource = new())
{
cancellationTokenSource.Cancel();
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png"));
TestAudioFileFactory.CreateWav(Path.Combine(albumDirectory, "track.wav"));
string trackPath = Path.Combine(albumDirectory, "track.wav");
LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true);
AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath);
// Act
Task Act()
{
return sut.GetArtworkAsync(lookup, cancellationTokenSource.Token);
}
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
}
}
/// <summary>
/// Creates a <see cref="LocalMusicAlbumArtworkProvider"/> whose settings provider carries the provided embedded cover extraction setting.
/// </summary>
/// <param name="shouldExtractEmbeddedCover">Whether the cover embedded in the audio files is extracted when the album has no cover image on disk.</param>
/// <returns>The created provider.</returns>
private LocalMusicAlbumArtworkProvider CreateProvider(bool shouldExtractEmbeddedCover)
{
LocalMusicArtworkSettingsProvider settingsProvider = new(
null,
Guid.NewGuid(),
_localMusicArtworkSettingsDtoFixture.Create(shouldExtractEmbeddedCover: shouldExtractEmbeddedCover));
return new LocalMusicAlbumArtworkProvider(settingsProvider);
}
/// <summary>
/// Removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,170 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.LocalMusicArtwork.Core;
using Lumina.Plugins.LocalMusicArtwork.Fixtures.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.IntegrationTests.Core;
/// <summary>
/// Contains integration tests for the <see cref="LocalMusicArtistArtworkProvider"/> class, reading real image files from the file system.
/// </summary>
[ExcludeFromCodeCoverage]
public class LocalMusicArtistArtworkProviderTests : IDisposable
{
private readonly ArtistMetadataLookupDtoFixture _artistMetadataLookupDtoFixture = new();
private readonly LocalMusicArtistArtworkProvider _sut = new();
private readonly string _temporaryDirectory;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMusicArtistArtworkProviderTests"/> class.
/// </summary>
public LocalMusicArtistArtworkProviderTests()
{
_temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-local-music-artist-artwork-{Guid.NewGuid():N}");
Directory.CreateDirectory(_temporaryDirectory);
}
[Fact]
public void Name_WhenCalled_ShouldReturnTheProviderDisplayName()
{
// Act
string result = _sut.Name;
// Assert
Assert.Equal("Local Music Artwork", result);
}
[Fact]
public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic()
{
// Act
IReadOnlyList<LibraryType> result = _sut.SupportedLibraryTypes;
// Assert
Assert.Equal([LibraryType.Music], result);
}
[Fact]
public void RequiresWebAccess_WhenCalled_ShouldReturnFalse()
{
// Act
bool result = _sut.RequiresWebAccess;
// Assert
Assert.False(result);
}
[Fact]
public async Task GetArtworkAsync_WhenTheArtistDirectoryCarriesImages_ShouldReturnTheArtistArtwork()
{
// Arrange
string artistDirectory = Path.Combine(_temporaryDirectory, "Artist");
TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "folder.jpg"));
TestImageFileFactory.CreatePng(Path.Combine(artistDirectory, "banner.png"));
TestImageFileFactory.CreateWebp(Path.Combine(artistDirectory, "logo.webp"));
string trackPath = Path.Combine(artistDirectory, "Album", "track.flac");
ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath);
// Act
IReadOnlyList<ArtworkDto> result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
List<ArtworkDto> expected =
[
new(ArtworkType.Cover, 0, Path.Combine(artistDirectory, "folder.jpg"), null),
new(ArtworkType.Banner, 0, Path.Combine(artistDirectory, "banner.png"), null),
new(ArtworkType.Logo, 0, Path.Combine(artistDirectory, "logo.webp"), null)
];
Assert.Equal(expected, result);
}
[Fact]
public async Task GetArtworkAsync_WhenNoArtistImagesExist_ShouldReturnEmpty()
{
// Arrange
string artistDirectory = Path.Combine(_temporaryDirectory, "Artist");
TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "cover.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "back.jpg"));
string trackPath = Path.Combine(artistDirectory, "Album", "track.flac");
ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath);
// Act
IReadOnlyList<ArtworkDto> result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Empty(result);
}
[Theory]
[InlineData(null)] // a null path contributes no artwork
[InlineData("")] // an empty path contributes no artwork
[InlineData(" ")] // a white space path contributes no artwork
[InlineData("track.flac")] // a path without a directory part contributes no artwork
public async Task GetArtworkAsync_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath)
{
// Arrange
ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath);
// Act
IReadOnlyList<ArtworkDto> result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Empty(result);
}
[Fact]
public async Task GetArtworkAsync_WhenTheTrackDirectoryDoesNotExist_ShouldReturnEmpty()
{
// Arrange
string trackPath = Path.Combine(_temporaryDirectory, "Missing", "Artist", "track.flac");
ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath);
// Act
IReadOnlyList<ArtworkDto> result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Empty(result);
}
[Fact]
public async Task GetArtworkAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldStillReturnTheDiskArtwork()
{
// Arrange
using (CancellationTokenSource cancellationTokenSource = new())
{
cancellationTokenSource.Cancel();
string artistDirectory = Path.Combine(_temporaryDirectory, "Artist");
TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "folder.jpg"));
string trackPath = Path.Combine(artistDirectory, "Album", "track.flac");
ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath);
// Act
IReadOnlyList<ArtworkDto> result = await _sut.GetArtworkAsync(lookup, cancellationTokenSource.Token);
// Assert
ArtworkDto artwork = Assert.Single(result);
Assert.Equal(ArtworkType.Cover, artwork.Type);
Assert.Equal(Path.Combine(artistDirectory, "folder.jpg"), artwork.LocalPath);
}
}
/// <summary>
/// Removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,198 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.LocalMusicArtwork.Core;
using Lumina.Plugins.LocalMusicArtwork.Fixtures.Core;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.IntegrationTests.Core;
/// <summary>
/// Contains integration tests for the <see cref="LocalMusicArtworkEmbeddedCoverExtractor"/> class, reading real audio containers that carry embedded pictures.
/// </summary>
[ExcludeFromCodeCoverage]
public class LocalMusicArtworkEmbeddedCoverExtractorTests : IDisposable
{
private static readonly byte[] s_coverBytes = [0xFF, 0xD8, 0xFF, 0xE0, 0x11, 0x22, 0x33, 0xFF, 0xD9];
private readonly string _temporaryDirectory;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMusicArtworkEmbeddedCoverExtractorTests"/> class.
/// </summary>
public LocalMusicArtworkEmbeddedCoverExtractorTests()
{
_temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-local-music-embedded-cover-{Guid.NewGuid():N}");
Directory.CreateDirectory(_temporaryDirectory);
}
[Fact]
public void Extract_WhenTheTrackCarriesAnEmbeddedCover_ShouldReturnATemporaryCoverArtwork()
{
// Arrange
string trackPath = Path.Combine(_temporaryDirectory, "track.wav");
TestAudioFileFactory.CreateWavWithEmbeddedCover(trackPath, s_coverBytes, "image/jpeg");
// Act
ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath);
// Assert
Assert.NotNull(result);
Assert.Equal(ArtworkType.Cover, result.Type);
Assert.Equal(0, result.Ordinal);
Assert.NotNull(result.LocalPath);
Assert.StartsWith(Path.GetTempPath(), result.LocalPath);
Assert.EndsWith(".jpg", result.LocalPath);
Assert.True(File.Exists(result.LocalPath));
Assert.Equal(s_coverBytes, File.ReadAllBytes(result.LocalPath!));
Assert.Null(result.RemoteUrl);
Assert.True(result.IsTemporary);
File.Delete(result.LocalPath!);
}
[Fact]
public void Extract_WhenTheTrackHasNoEmbeddedCover_ShouldReturnNull()
{
// Arrange
string trackPath = Path.Combine(_temporaryDirectory, "track.wav");
TestAudioFileFactory.CreateWav(trackPath);
// Act
ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath);
// Assert
Assert.Null(result);
}
[Theory]
[InlineData(null)] // a null path contributes no cover
[InlineData("")] // an empty path contributes no cover
[InlineData(" ")] // a white space path contributes no cover
public void Extract_WhenTheTrackPathIsNullOrEmpty_ShouldReturnNull(string? trackPath)
{
// Act
ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath);
// Assert
Assert.Null(result);
}
[Fact]
public void Extract_WhenTheTrackFileDoesNotExist_ShouldReturnNull()
{
// Arrange
string trackPath = Path.Combine(_temporaryDirectory, "missing.wav");
// Act
ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath);
// Assert
Assert.Null(result);
}
[Theory]
[InlineData("image/jpeg", ".jpg")]
[InlineData("image/png", ".png")]
[InlineData("image/webp", ".webp")]
[InlineData("image/bmp", ".bmp")]
[InlineData("image/x-ms-bmp", ".bmp")]
[InlineData("image/gif", ".gif")]
[InlineData("image/tiff", ".tiff")]
[InlineData("IMAGE/PNG", ".png")] // the MIME type is matched without regard to casing
[InlineData(" image/png ", ".png")] // the MIME type is trimmed before it is matched
[InlineData("application/octet-stream", ".jpg")] // an unknown MIME type falls back to the JPEG extension
[InlineData("", ".jpg")] // an empty MIME type falls back to the JPEG extension
[InlineData(null, ".jpg")] // a missing MIME type falls back to the JPEG extension
public void Extract_WhenTheMimeTypeIsProvided_ShouldUseTheMatchingFileExtension(string? mimeType, string expectedExtension)
{
// Arrange
string trackPath = Path.Combine(_temporaryDirectory, "track.wav");
TestAudioFileFactory.CreateWavWithEmbeddedCover(trackPath, s_coverBytes, mimeType);
// Act
ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath);
// Assert
Assert.NotNull(result);
Assert.NotNull(result.LocalPath);
Assert.EndsWith(expectedExtension, result.LocalPath);
Assert.Equal(s_coverBytes, File.ReadAllBytes(result.LocalPath!));
Assert.True(result.IsTemporary);
File.Delete(result.LocalPath!);
}
[Fact]
public void Extract_WhenTheEmbeddedCoverIsExactlyTheMaximumSize_ShouldReturnTheCover()
{
// Arrange
byte[] maximumCover = new byte[10 * 1024 * 1024];
string trackPath = Path.Combine(_temporaryDirectory, "track.wav");
TestAudioFileFactory.CreateWavWithEmbeddedCover(trackPath, maximumCover, "image/jpeg");
// Act
ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath);
// Assert
Assert.NotNull(result);
Assert.NotNull(result.LocalPath);
Assert.Equal(maximumCover, File.ReadAllBytes(result.LocalPath!));
Assert.True(result.IsTemporary);
File.Delete(result.LocalPath!);
}
[Fact]
public void Extract_WhenTheEmbeddedCoverIsLargerThanTheMaximumSize_ShouldReturnNull()
{
// Arrange
byte[] oversizedCover = new byte[10 * 1024 * 1024 + 1];
string trackPath = Path.Combine(_temporaryDirectory, "track.wav");
TestAudioFileFactory.CreateWavWithEmbeddedCover(trackPath, oversizedCover, "image/jpeg");
// Act
ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath);
// Assert
Assert.Null(result);
}
[Fact]
public void Extract_WhenTheTrackIsNotAnAudioFile_ShouldReturnNull()
{
// Arrange
string trackPath = Path.Combine(_temporaryDirectory, "track.txt");
TestAudioFileFactory.CreateUnsupportedFile(trackPath);
// Act
ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath);
// Assert
Assert.Null(result);
}
[Fact]
public void Extract_WhenTheAudioFileIsCorrupt_ShouldReturnNull()
{
// Arrange
string trackPath = Path.Combine(_temporaryDirectory, "track.mp3");
TestAudioFileFactory.CreateUnsupportedFile(trackPath);
// Act
ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath);
// Assert
Assert.Null(result);
}
/// <summary>
/// Removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,487 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.LocalMusicArtwork.Core;
using Lumina.Plugins.LocalMusicArtwork.Fixtures.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.IntegrationTests.Core;
/// <summary>
/// Contains integration tests for the <see cref="LocalMusicArtworkScanner"/> class, scanning real image files on the file system.
/// </summary>
[ExcludeFromCodeCoverage]
public class LocalMusicArtworkScannerTests : IDisposable
{
private readonly string _temporaryDirectory;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMusicArtworkScannerTests"/> class.
/// </summary>
public LocalMusicArtworkScannerTests()
{
_temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-local-music-artwork-scanner-{Guid.NewGuid():N}");
Directory.CreateDirectory(_temporaryDirectory);
}
[Fact]
public void ScanAlbumArtwork_WhenTheAlbumDirectoryCarriesTheStandardImages_ShouldReturnEachArtworkType()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Artist", "Album");
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "front.jpg"));
TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet1.jpg"));
TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "booklet2.png"));
TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "disk.png"));
TestImageFileFactory.CreateGif(Path.Combine(albumDirectory, "tray.gif"));
TestImageFileFactory.CreateTiff(Path.Combine(albumDirectory, "spine.tiff"));
TestImageFileFactory.CreateBmp(Path.Combine(albumDirectory, "obi.bmp"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "sticker.jpg"));
TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "poster.png"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "liner.jpg"));
string trackPath = Path.Combine(albumDirectory, "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
List<ArtworkDto> expected =
[
new(ArtworkType.Cover, 0, Path.Combine(albumDirectory, "cover.jpg"), null),
new(ArtworkType.Front, 0, Path.Combine(albumDirectory, "front.jpg"), null),
new(ArtworkType.Back, 0, Path.Combine(albumDirectory, "back.png"), null),
new(ArtworkType.Booklet, 1, Path.Combine(albumDirectory, "booklet1.jpg"), null),
new(ArtworkType.Booklet, 2, Path.Combine(albumDirectory, "booklet2.png"), null),
new(ArtworkType.Medium, 0, Path.Combine(albumDirectory, "disk.png"), null),
new(ArtworkType.Tray, 0, Path.Combine(albumDirectory, "tray.gif"), null),
new(ArtworkType.Spine, 0, Path.Combine(albumDirectory, "spine.tiff"), null),
new(ArtworkType.Obi, 0, Path.Combine(albumDirectory, "obi.bmp"), null),
new(ArtworkType.Sticker, 0, Path.Combine(albumDirectory, "sticker.jpg"), null),
new(ArtworkType.Poster, 0, Path.Combine(albumDirectory, "poster.png"), null),
new(ArtworkType.Liner, 0, Path.Combine(albumDirectory, "liner.jpg"), null)
];
Assert.Equal(12, result.Count);
Assert.Equal(expected, result);
}
[Fact]
public void ScanAlbumArtwork_WhenTheStemCarriesANumber_ShouldUseItAsTheOrdinal()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet1.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet2.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "disk1.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "disk2.jpg"));
string trackPath = Path.Combine(albumDirectory, "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
List<ArtworkDto> expected =
[
new(ArtworkType.Booklet, 0, Path.Combine(albumDirectory, "booklet.jpg"), null),
new(ArtworkType.Booklet, 1, Path.Combine(albumDirectory, "booklet1.jpg"), null),
new(ArtworkType.Booklet, 2, Path.Combine(albumDirectory, "booklet2.jpg"), null),
new(ArtworkType.Medium, 1, Path.Combine(albumDirectory, "disk1.jpg"), null),
new(ArtworkType.Medium, 2, Path.Combine(albumDirectory, "disk2.jpg"), null)
];
Assert.Equal(expected, result);
}
[Fact]
public void ScanAlbumArtwork_WhenTheStemHasAHyphenOrUnderscoreBeforeTheNumber_ShouldTrimTheSeparator()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet - 1.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet_2.jpg"));
string trackPath = Path.Combine(albumDirectory, "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
List<ArtworkDto> expected =
[
new(ArtworkType.Booklet, 1, Path.Combine(albumDirectory, "booklet - 1.jpg"), null),
new(ArtworkType.Booklet, 2, Path.Combine(albumDirectory, "booklet_2.jpg"), null)
];
Assert.Equal(expected, result);
}
[Fact]
public void ScanAlbumArtwork_WhenBothCoverAndFrontExist_ShouldReturnThemAsDistinctArtworks()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "front.jpg"));
string trackPath = Path.Combine(albumDirectory, "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
List<ArtworkDto> expected =
[
new(ArtworkType.Cover, 0, Path.Combine(albumDirectory, "cover.jpg"), null),
new(ArtworkType.Front, 0, Path.Combine(albumDirectory, "front.jpg"), null)
];
Assert.Equal(expected, result);
}
[Fact]
public void ScanAlbumArtwork_WhenSeveralNamesMapToTheSameTypeAndOrdinal_ShouldKeepOnlyThePreferredFile()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "disk.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "disc.jpg"));
string trackPath = Path.Combine(albumDirectory, "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
// Both file names describe the medium of the album, and the one that sorts first by name wins, so that a single image is stored per type and ordinal.
ArtworkDto artwork = Assert.Single(result);
Assert.Equal(ArtworkType.Medium, artwork.Type);
Assert.Equal(0, artwork.Ordinal);
Assert.Equal(Path.Combine(albumDirectory, "disc.jpg"), artwork.LocalPath);
Assert.Null(artwork.RemoteUrl);
Assert.False(artwork.IsTemporary);
}
[Fact]
public void ScanAlbumArtwork_WhenAFileIsNotAnImage_ShouldIgnoreIt()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg"));
TestImageFileFactory.CreateTextFile(Path.Combine(albumDirectory, "notes.txt"));
string trackPath = Path.Combine(albumDirectory, "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
ArtworkDto artwork = Assert.Single(result);
Assert.Equal(ArtworkType.Cover, artwork.Type);
Assert.Equal(Path.Combine(albumDirectory, "cover.jpg"), artwork.LocalPath);
}
[Fact]
public void ScanAlbumArtwork_WhenTheImageExtensionIsUppercase_ShouldIgnoreIt()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.JPG"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "back.JPEG"));
string trackPath = Path.Combine(albumDirectory, "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
Assert.Empty(result);
}
[Fact]
public void ScanAlbumArtwork_WhenTheImageNameHasDifferentCasing_ShouldIgnoreIt()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "Cover.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "BACK.jpg"));
string trackPath = Path.Combine(albumDirectory, "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
Assert.Empty(result);
}
[Fact]
public void ScanAlbumArtwork_WhenTheImageNameIsNotRecognized_ShouldIgnoreIt()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "random.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "folder.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "backdrop.jpg"));
string trackPath = Path.Combine(albumDirectory, "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
Assert.Empty(result);
}
[Fact]
public void ScanAlbumArtwork_WhenTheAlbumIsMultiDiscAndTheParentDirectoryCarriesTheArtwork_ShouldFindIt()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
string discDirectory = Path.Combine(albumDirectory, "CD1");
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "back.jpg"));
Directory.CreateDirectory(discDirectory);
string trackPath = Path.Combine(discDirectory, "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
List<ArtworkDto> expected =
[
new(ArtworkType.Cover, 0, Path.Combine(albumDirectory, "cover.jpg"), null),
new(ArtworkType.Back, 0, Path.Combine(albumDirectory, "back.jpg"), null)
];
Assert.Equal(expected, result);
}
[Fact]
public void ScanAlbumArtwork_WhenBothTheDiscAndTheParentDirectoryCarryTheSameArtwork_ShouldPreferTheNearest()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
string discDirectory = Path.Combine(albumDirectory, "CD1");
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(discDirectory, "cover.jpg"));
string trackPath = Path.Combine(discDirectory, "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
ArtworkDto artwork = Assert.Single(result);
Assert.Equal(ArtworkType.Cover, artwork.Type);
Assert.Equal(0, artwork.Ordinal);
Assert.Equal(Path.Combine(discDirectory, "cover.jpg"), artwork.LocalPath);
}
[Fact]
public void ScanAlbumArtwork_WhenTheDiscAndTheParentDirectoryCarryDifferentArtworks_ShouldReturnBoth()
{
// Arrange
string albumDirectory = Path.Combine(_temporaryDirectory, "Album");
string discDirectory = Path.Combine(albumDirectory, "CD1");
TestImageFileFactory.CreateJpeg(Path.Combine(discDirectory, "cover.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "back.jpg"));
string trackPath = Path.Combine(discDirectory, "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
List<ArtworkDto> expected =
[
new(ArtworkType.Cover, 0, Path.Combine(discDirectory, "cover.jpg"), null),
new(ArtworkType.Back, 0, Path.Combine(albumDirectory, "back.jpg"), null)
];
Assert.Equal(expected, result);
}
[Fact]
public void ScanAlbumArtwork_WhenTheArtworkIsMoreThanTwoLevelsAboveTheTrack_ShouldNotFindIt()
{
// Arrange
TestImageFileFactory.CreateJpeg(Path.Combine(_temporaryDirectory, "cover.jpg"));
string trackPath = Path.Combine(_temporaryDirectory, "Album", "CD1", "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
Assert.Empty(result);
}
[Theory]
[InlineData(null)] // a null path contributes no artwork
[InlineData("")] // an empty path contributes no artwork
[InlineData(" ")] // a white space path contributes no artwork
[InlineData("track.flac")] // a path without a directory part contributes no artwork
public void ScanAlbumArtwork_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath)
{
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
Assert.Empty(result);
}
[Fact]
public void ScanAlbumArtwork_WhenTheAlbumDirectoryDoesNotExist_ShouldReturnEmpty()
{
// Arrange
string trackPath = Path.Combine(_temporaryDirectory, "Missing", "Album", "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
Assert.Empty(result);
}
[Fact]
public void ScanArtistArtwork_WhenTheArtistDirectoryCarriesTheStandardImages_ShouldReturnEachArtworkType()
{
// Arrange
string artistDirectory = Path.Combine(_temporaryDirectory, "Artist");
TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "folder.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "backdrop.jpg"));
TestImageFileFactory.CreatePng(Path.Combine(artistDirectory, "banner.png"));
TestImageFileFactory.CreateWebp(Path.Combine(artistDirectory, "logo.webp"));
TestImageFileFactory.CreateGif(Path.Combine(artistDirectory, "thumb.gif"));
string trackPath = Path.Combine(artistDirectory, "Album", "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath);
// Assert
List<ArtworkDto> expected =
[
new(ArtworkType.Cover, 0, Path.Combine(artistDirectory, "folder.jpg"), null),
new(ArtworkType.Backdrop, 0, Path.Combine(artistDirectory, "backdrop.jpg"), null),
new(ArtworkType.Banner, 0, Path.Combine(artistDirectory, "banner.png"), null),
new(ArtworkType.Logo, 0, Path.Combine(artistDirectory, "logo.webp"), null),
new(ArtworkType.Thumb, 0, Path.Combine(artistDirectory, "thumb.gif"), null)
];
Assert.Equal(expected, result);
}
[Fact]
public void ScanArtistArtwork_WhenTheDirectoryCarriesOnlyAlbumImages_ShouldReturnEmpty()
{
// Arrange
string artistDirectory = Path.Combine(_temporaryDirectory, "Artist");
TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "cover.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "back.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "disk.jpg"));
string trackPath = Path.Combine(artistDirectory, "Album", "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath);
// Assert
Assert.Empty(result);
}
[Fact]
public void ScanArtistArtwork_WhenTheArtistImagesAreInAnAncestorDirectory_ShouldFindThem()
{
// Arrange
string artistDirectory = Path.Combine(_temporaryDirectory, "Artist");
TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "folder.jpg"));
string trackPath = Path.Combine(artistDirectory, "Album", "CD1", "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath);
// Assert
ArtworkDto artwork = Assert.Single(result);
Assert.Equal(ArtworkType.Cover, artwork.Type);
Assert.Equal(0, artwork.Ordinal);
Assert.Equal(Path.Combine(artistDirectory, "folder.jpg"), artwork.LocalPath);
}
[Fact]
public void ScanArtistArtwork_WhenSeveralAncestorDirectoriesCarryArtistImages_ShouldPreferTheNearest()
{
// Arrange
string artistDirectory = Path.Combine(_temporaryDirectory, "Artist");
string albumDirectory = Path.Combine(artistDirectory, "Album");
TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "backdrop.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "folder.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg"));
string trackPath = Path.Combine(albumDirectory, "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath);
// Assert
// The nearest ancestor that carries an artist image wins, and the album images of that directory are not part of the artist artwork.
ArtworkDto artwork = Assert.Single(result);
Assert.Equal(ArtworkType.Cover, artwork.Type);
Assert.Equal(0, artwork.Ordinal);
Assert.Equal(Path.Combine(albumDirectory, "folder.jpg"), artwork.LocalPath);
}
[Fact]
public void ScanArtistArtwork_WhenTheArtistImagesAreBeyondTheSearchDepth_ShouldReturnEmpty()
{
// Arrange
TestImageFileFactory.CreateJpeg(Path.Combine(_temporaryDirectory, "folder.jpg"));
string trackPath = Path.Combine(_temporaryDirectory, "A", "B", "C", "D", "E", "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath);
// Assert
Assert.Empty(result);
}
[Fact]
public void ScanArtistArtwork_WhenTheImageNameHasDifferentCasing_ShouldIgnoreIt()
{
// Arrange
string artistDirectory = Path.Combine(_temporaryDirectory, "Artist");
TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "Folder.jpg"));
TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "Backdrop.jpg"));
string trackPath = Path.Combine(artistDirectory, "Album", "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath);
// Assert
Assert.Empty(result);
}
[Theory]
[InlineData(null)] // a null path contributes no artwork
[InlineData("")] // an empty path contributes no artwork
[InlineData(" ")] // a white space path contributes no artwork
[InlineData("track.flac")] // a path without a directory part contributes no artwork
public void ScanArtistArtwork_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath)
{
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath);
// Assert
Assert.Empty(result);
}
[Fact]
public void ScanArtistArtwork_WhenTheAncestorDirectoryDoesNotExist_ShouldReturnEmpty()
{
// Arrange
string trackPath = Path.Combine(_temporaryDirectory, "Missing", "Artist", "track.flac");
// Act
IReadOnlyList<ArtworkDto> result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath);
// Assert
Assert.Empty(result);
}
/// <summary>
/// Removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,49 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" />
<PackageReference Include="AutoFixture.Xunit2" />
<PackageReference Include="Bogus" />
<PackageReference Include="coverlet.collector">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="TagLibSharp" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.LocalMusicArtwork\Lumina.Plugins.LocalMusicArtwork.csproj" />
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Plugins.LocalMusicArtwork.Fixtures\Lumina.Plugins.LocalMusicArtwork.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,97 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.LocalMusicArtwork.Common.DependencyInjection;
using Lumina.Plugins.LocalMusicArtwork.Core;
using Lumina.Plugins.LocalMusicArtwork.Core.Settings;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.UnitTests.Common.DependencyInjection;
/// <summary>
/// Contains unit tests for the <see cref="LocalMusicArtworkServices"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LocalMusicArtworkServicesTests
{
[Fact]
public void AddLocalMusicArtworkProviders_WhenServicesIsNull_ShouldThrowArgumentNullException()
{
// Arrange
IServiceCollection services = null!;
// Act
Action act = () => services.AddLocalMusicArtworkProviders(pluginId: Guid.NewGuid());
// Assert
Assert.Throws<ArgumentNullException>(act);
}
[Fact]
public void AddLocalMusicArtworkProviders_WhenCalled_ShouldReturnTheSameServiceCollection()
{
// Arrange
ServiceCollection services = new();
// Act
IServiceCollection result = services.AddLocalMusicArtworkProviders(pluginId: Guid.NewGuid());
// Assert
Assert.Same(services, result);
}
[Fact]
public void AddLocalMusicArtworkProviders_WhenCalled_ShouldRegisterTheAlbumAndArtistProvidersForKeyedResolution()
{
// Arrange
Guid pluginId = Guid.NewGuid();
ServiceCollection services = new();
// Act
services.AddLocalMusicArtworkProviders(pluginId: pluginId);
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert
IReadOnlyList<IArtworkProvider> providers = [.. serviceProvider.GetKeyedServices<IArtworkProvider>(pluginId)];
Assert.Equal(2, providers.Count);
Assert.Contains(providers, provider => provider is LocalMusicAlbumArtworkProvider);
Assert.Contains(providers, provider => provider is LocalMusicArtistArtworkProvider);
Assert.Equal(2, providers.Select(provider => provider.GetType()).Distinct().Count());
Assert.Empty(serviceProvider.GetKeyedServices<IArtworkProvider>(Guid.NewGuid()));
}
[Fact]
public void AddLocalMusicArtworkProviders_WhenCalled_ShouldRegisterTheSettingsProviderAsScoped()
{
// Arrange
ServiceCollection services = new();
// Act
services.AddLocalMusicArtworkProviders(pluginId: Guid.NewGuid());
// Assert
ServiceDescriptor settingsProviderDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(LocalMusicArtworkSettingsProvider));
Assert.Equal(ServiceLifetime.Scoped, settingsProviderDescriptor.Lifetime);
}
[Fact]
public void AddLocalMusicArtworkProviders_WhenCalledTwice_ShouldNotDuplicateTheTryAddSettingsProvider()
{
// Arrange
Guid pluginId = Guid.NewGuid();
ServiceCollection services = new();
// Act
services.AddLocalMusicArtworkProviders(pluginId: pluginId);
services.AddLocalMusicArtworkProviders(pluginId: pluginId);
// Assert
// The settings provider is registered with TryAdd, so a second call must not add it again, while the artwork providers stay transient and are added once per call.
Assert.Single(services, descriptor => descriptor.ServiceType == typeof(LocalMusicArtworkSettingsProvider));
Assert.Equal(4, services.Count(descriptor => descriptor.ServiceType == typeof(IArtworkProvider)));
}
}
@@ -0,0 +1,118 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.LocalMusicArtwork.Core;
using Lumina.Plugins.LocalMusicArtwork.Core.Settings;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.UnitTests.Core;
/// <summary>
/// Contains unit tests for the <see cref="LocalMusicArtworkPlugin"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LocalMusicArtworkPluginTests
{
private readonly LocalMusicArtworkPlugin _sut = new();
[Fact]
public void Id_WhenCalled_ShouldReturnStablePluginIdentifier()
{
// Act
Guid result = _sut.Id;
// Assert
Assert.Equal(LocalMusicArtworkPlugin.s_pluginId, result);
Assert.Equal(new Guid("c9f1a7d3-2b64-4e18-8f05-7a3d9c1b6e42"), result);
}
[Fact]
public void Name_WhenCalled_ShouldReturnPluginDisplayName()
{
// Act
string result = _sut.Name;
// Assert
Assert.Equal("Local Music Artwork", result);
}
[Fact]
public void Author_WhenCalled_ShouldReturnPluginAuthor()
{
// Act
string result = _sut.Author;
// Assert
Assert.Equal("Lumina", result);
}
[Fact]
public void Version_WhenCalled_ShouldReturnPluginVersion()
{
// Act
Version result = _sut.Version;
// Assert
Assert.Equal(new Version(1, 0, 0), result);
}
[Fact]
public void Description_WhenCalled_ShouldReturnPluginDescription()
{
// Act
string result = _sut.Description;
// Assert
Assert.Equal("Reads the artwork of the artists and the albums from the images stored in the folders of a local music library.", result);
}
[Fact]
public void GetSettingsSchema_WhenCalled_ShouldReturnTheSingleSettingDescriptor()
{
// Act
IReadOnlyList<PluginSettingDescriptorDto> result = _sut.GetSettingsSchema();
// Assert
PluginSettingDescriptorDto descriptor = Assert.Single(result);
Assert.Equal(LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER, descriptor.Key);
}
[Fact]
public void GetSettingsSchema_WhenCalled_ShouldDescribeTheEmbeddedCoverSettingCorrectly()
{
// Act
IReadOnlyList<PluginSettingDescriptorDto> result = _sut.GetSettingsSchema();
// Assert
PluginSettingDescriptorDto descriptor = Assert.Single(result);
Assert.Equal("Extract embedded album cover image from audio files when it is not already present on disk", descriptor.Label);
Assert.Equal(PluginSettingType.Boolean, descriptor.Type);
Assert.Equal("true", descriptor.DefaultValue);
Assert.Null(descriptor.AllowedValues);
}
[Fact]
public void RegisterServices_WhenCalled_ShouldRegisterTheAlbumAndArtistArtworkProviders()
{
// Arrange
ServiceCollection services = new();
// Act
_sut.RegisterServices(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert
IReadOnlyList<IArtworkProvider> providers = [.. serviceProvider.GetKeyedServices<IArtworkProvider>(LocalMusicArtworkPlugin.s_pluginId)];
Assert.Equal(2, providers.Count);
Assert.Contains(providers, provider => provider is LocalMusicAlbumArtworkProvider);
Assert.Contains(providers, provider => provider is LocalMusicArtistArtworkProvider);
Assert.Equal(2, providers.Select(provider => provider.GetType()).Distinct().Count());
Assert.Empty(serviceProvider.GetKeyedServices<IArtworkProvider>(Guid.NewGuid()));
}
}
@@ -0,0 +1,223 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings;
using Lumina.Plugins.LocalMusicArtwork.Core.Settings;
using Lumina.Plugins.LocalMusicArtwork.Fixtures.Common.Models.DTO.Settings;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.UnitTests.Core.Settings;
/// <summary>
/// Contains unit tests for the <see cref="LocalMusicArtworkSettingsProvider"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LocalMusicArtworkSettingsProviderTests
{
private readonly LocalMusicArtworkSettingsDtoFixture _localMusicArtworkSettingsDtoFixture = new();
[Fact]
public async Task GetAsync_WhenNoStoreIsAvailable_ShouldReturnTheDefaults()
{
// Arrange
LocalMusicArtworkSettingsDto defaults = CreateDefaults(shouldExtractEmbeddedCover: true);
LocalMusicArtworkSettingsProvider sut = new(null, Guid.NewGuid(), defaults);
// Act
LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None);
// Assert
Assert.NotSame(defaults, result);
Assert.True(result.ShouldExtractEmbeddedCover);
}
[Fact]
public async Task GetAsync_WhenNoStoreIsAvailableAndTheDefaultsDisableExtraction_ShouldReturnTheDisabledDefault()
{
// Arrange
LocalMusicArtworkSettingsDto defaults = CreateDefaults(shouldExtractEmbeddedCover: false);
LocalMusicArtworkSettingsProvider sut = new(null, Guid.NewGuid(), defaults);
// Act
LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None);
// Assert
Assert.False(result.ShouldExtractEmbeddedCover);
}
[Fact]
public async Task GetAsync_WhenTheStoreReturnsNoSettings_ShouldReturnTheDefaults()
{
// Arrange
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns((IReadOnlyDictionary<string, string>?)null);
LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true));
// Act
LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None);
// Assert
Assert.True(result.ShouldExtractEmbeddedCover);
}
[Theory]
[InlineData("false", true, false)] // a stored value disables extraction over a default that enables it
[InlineData("true", false, true)] // a stored value enables extraction over a default that disables it
[InlineData("True", false, true)] // the stored value is parsed without regard to casing
[InlineData("FALSE", true, false)] // the stored value is parsed without regard to casing
public async Task GetAsync_WhenTheSettingIsPersisted_ShouldOverlayItOverTheDefaults(string storedValue, bool defaultValue, bool expectedValue)
{
// Arrange
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER] = storedValue });
LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: defaultValue));
// Act
LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None);
// Assert
Assert.Equal(expectedValue, result.ShouldExtractEmbeddedCover);
}
[Theory]
[InlineData("not-a-boolean")]
[InlineData("")]
[InlineData(" ")]
[InlineData("1")]
[InlineData("0")]
[InlineData("yes")]
public async Task GetAsync_WhenThePersistedSettingIsNotABoolean_ShouldKeepTheDefault(string storedValue)
{
// Arrange
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER] = storedValue });
LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true));
// Act
LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None);
// Assert
Assert.True(result.ShouldExtractEmbeddedCover);
}
[Fact]
public async Task GetAsync_WhenThePersistedSettingsDoNotContainTheKey_ShouldKeepTheDefault()
{
// Arrange
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { ["SomeOtherKey"] = "false" });
LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true));
// Act
LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None);
// Assert
Assert.True(result.ShouldExtractEmbeddedCover);
}
[Fact]
public async Task GetAsync_WhenThePersistedKeyHasDifferentCasing_ShouldKeepTheDefault()
{
// Arrange
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { ["shouldextractembeddedcover"] = "false" });
LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true));
// Act
LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None);
// Assert
Assert.True(result.ShouldExtractEmbeddedCover);
}
[Fact]
public async Task GetAsync_WhenThePersistedSettingOverridesTheDefaults_ShouldNotMutateTheDefaults()
{
// Arrange
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER] = "false" });
LocalMusicArtworkSettingsDto defaults = CreateDefaults(shouldExtractEmbeddedCover: true);
LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), defaults);
// Act
LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None);
// Assert
Assert.False(result.ShouldExtractEmbeddedCover);
Assert.True(defaults.ShouldExtractEmbeddedCover);
}
[Fact]
public async Task GetAsync_WhenCalledTwice_ShouldReadTheStoreOnlyOnce()
{
// Arrange
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(new Dictionary<string, string>());
LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true));
// Act
LocalMusicArtworkSettingsDto first = await sut.GetAsync(CancellationToken.None);
LocalMusicArtworkSettingsDto second = await sut.GetAsync(CancellationToken.None);
// Assert
Assert.Same(first, second);
await mockStore.Received(1).GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetAsync_WhenCalledConcurrently_ShouldReadTheStoreOnlyOnce()
{
// Arrange
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(new Dictionary<string, string>());
LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true));
// Act
LocalMusicArtworkSettingsDto[] results = await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => sut.GetAsync(CancellationToken.None)));
// Assert
Assert.All(results, result => Assert.Same(results[0], result));
await mockStore.Received(1).GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldThrowOperationCanceledException()
{
// Arrange
using (CancellationTokenSource cancellationTokenSource = new())
{
cancellationTokenSource.Cancel();
LocalMusicArtworkSettingsProvider sut = new(null, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true));
// Act
Task Act()
{
return sut.GetAsync(cancellationTokenSource.Token);
}
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
}
}
/// <summary>
/// Creates the default settings used by the tests of the provider.
/// </summary>
/// <param name="shouldExtractEmbeddedCover">Whether the cover embedded in the audio files is extracted when the album has no cover image on disk.</param>
/// <returns>The default settings.</returns>
private LocalMusicArtworkSettingsDto CreateDefaults(bool shouldExtractEmbeddedCover)
{
return _localMusicArtworkSettingsDtoFixture.Create(shouldExtractEmbeddedCover: shouldExtractEmbeddedCover);
}
}
@@ -0,0 +1,47 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" />
<PackageReference Include="AutoFixture.Xunit2" />
<PackageReference Include="Bogus" />
<PackageReference Include="coverlet.collector">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.LocalMusicArtwork\Lumina.Plugins.LocalMusicArtwork.csproj" />
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Plugins.LocalMusicArtwork.Fixtures\Lumina.Plugins.LocalMusicArtwork.Fixtures.csproj" />
</ItemGroup>
</Project>