Adds the music library persistence model, its repositories, and the scanning migration

This commit is contained in:
BinaryAlley committed 2026-10-08 20:48:00 +03:00
1 parent 4f0526faa4
commit 00376c8313
63 files changed
+8679 -203

No files matched your search

@@ -70,11 +70,11 @@ public class AlbumConfigurationTests : IDisposable
IProperty originalTitleProperty = entityType.GetProperty(nameof(AlbumEntity.OriginalTitle));
IProperty descriptionProperty = entityType.GetProperty(nameof(AlbumEntity.Description));
IProperty releaseCountryProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseCountry));
IProperty releaseTypeProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseType));
IProperty releaseTypeProperty = entityType.FindNavigation(nameof(AlbumEntity.ReleaseTypes))!.TargetEntityType.GetProperty(nameof(AlbumReleaseTypeEntity.ReleaseType));
IProperty releaseStatusProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseStatus));
IProperty mediaFormatProperty = entityType.GetProperty(nameof(AlbumEntity.MediaFormat));
IProperty barcodeProperty = entityType.GetProperty(nameof(AlbumEntity.Barcode));
IProperty catalogNumberProperty = entityType.GetProperty(nameof(AlbumEntity.CatalogNumber));
IProperty catalogNumberProperty = entityType.FindNavigation(nameof(AlbumEntity.CatalogNumbers))!.TargetEntityType.GetProperty(nameof(AlbumCatalogNumberEntity.CatalogNumber));
IProperty languageCodeProperty = entityType.GetProperty(nameof(AlbumEntity.LanguageCode));
// Assert
@@ -87,7 +87,7 @@ public class AlbumConfigurationTests : IDisposable
Assert.Equal(typeof(ReleaseCountry?), releaseCountryProperty.ClrType);
Assert.Equal("TEXT", releaseCountryProperty.GetColumnType());
Assert.Equal(2, releaseCountryProperty.GetMaxLength());
Assert.Equal(typeof(MusicReleaseType?), releaseTypeProperty.ClrType);
Assert.Equal(typeof(MusicReleaseType), releaseTypeProperty.ClrType);
Assert.Equal("TEXT", releaseTypeProperty.GetColumnType());
Assert.Equal(50, releaseTypeProperty.GetMaxLength());
Assert.Equal(typeof(MusicReleaseStatus?), releaseStatusProperty.ClrType);
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
@@ -0,0 +1,163 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
/// <summary>
/// Contains unit tests for the <see cref="MusicLibraryScanItemMetadataConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicLibraryScanItemMetadataConfigurationTests : IDisposable
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="MusicLibraryScanItemMetadataConfigurationTests"/> class.
/// </summary>
public MusicLibraryScanItemMetadataConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("MusicLibraryScanItemMetadata", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
IProperty idProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.Id));
// Assert
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRequiredScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
IProperty libraryScanIdProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.LibraryScanId));
IProperty libraryIdProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.LibraryId));
IProperty pathProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.Path));
// Assert
Assert.False(libraryScanIdProperty.IsNullable);
Assert.False(libraryIdProperty.IsNullable);
Assert.False(pathProperty.IsNullable);
Assert.Equal(2048, pathProperty.GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOptionalScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
IProperty artistNameProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ArtistName));
IProperty releaseTypeProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReleaseType));
IProperty releaseYearProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReleaseYear));
IProperty releaseNameProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReleaseName));
IProperty trackTitleProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.TrackTitle));
IProperty audioCodecProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.AudioCodec));
IProperty workTitleProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.WorkTitle));
IProperty acoustIdProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.AcoustId));
// Assert
Assert.True(artistNameProperty.IsNullable);
Assert.Equal(255, artistNameProperty.GetMaxLength());
Assert.True(releaseTypeProperty.IsNullable);
Assert.Equal(typeof(MusicReleaseType?), releaseTypeProperty.ClrType);
Assert.Equal("TEXT", releaseTypeProperty.GetColumnType());
Assert.Equal(50, releaseTypeProperty.GetMaxLength());
Assert.True(releaseYearProperty.IsNullable);
Assert.Equal(255, releaseNameProperty.GetMaxLength());
Assert.Equal(255, trackTitleProperty.GetMaxLength());
Assert.Equal(50, audioCodecProperty.GetMaxLength());
Assert.Equal(255, workTitleProperty.GetMaxLength());
Assert.Equal(64, acoustIdProperty.GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureReplayGainDecimalPrecision()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
IProperty trackGainProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainTrackGain));
IProperty trackPeakProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainTrackPeak));
IProperty albumGainProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainAlbumGain));
IProperty albumPeakProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainAlbumPeak));
// Assert
Assert.Equal("decimal(8,2)", trackGainProperty.GetColumnType());
Assert.Equal("decimal(8,6)", trackPeakProperty.GetColumnType());
Assert.Equal("decimal(8,2)", albumGainProperty.GetColumnType());
Assert.Equal("decimal(8,6)", albumPeakProperty.GetColumnType());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureMoodsAsPrimitiveCollection()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
IProperty moodsProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.Moods));
// Assert
Assert.True(moodsProperty.IsPrimitiveCollection);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureUniqueScanIdPathIndex()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
List<IIndex> indexes = [.. entityType.GetIndexes()];
// Assert
IIndex uniqueIndex = Assert.Single(indexes, index => index.IsUnique);
Assert.Equal(
[nameof(MusicLibraryScanItemMetadataEntity.LibraryScanId), nameof(MusicLibraryScanItemMetadataEntity.Path)],
uniqueIndex.Properties.Select(property => property.Name));
}
/// <summary>
/// Disposes the database context.
/// </summary>
public void Dispose()
{
_context.Dispose();
}
}
@@ -72,7 +72,7 @@ public class TrackConfigurationTests : IDisposable
IProperty scriptProperty = entityType.GetProperty(nameof(TrackEntity.Script));
IProperty keyProperty = entityType.GetProperty(nameof(TrackEntity.Key));
IProperty audioCodecProperty = entityType.GetProperty(nameof(TrackEntity.AudioCodec));
IProperty workProperty = entityType.GetProperty(nameof(TrackEntity.Work));
IProperty workProperty = entityType.GetProperty(nameof(TrackEntity.WorkTitle));
// Assert
Assert.False(pathProperty.IsNullable);
@@ -118,9 +118,11 @@ public class TrackConfigurationTests : IDisposable
List<IEntityType> ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)];
// Assert
Assert.Equal(3, ownedTypes.Count);
Assert.Equal(5, ownedTypes.Count);
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackMoodEntity) && ownedType.GetTableName() == "TrackMoods");
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackIsrcEntity) && ownedType.GetTableName() == "TrackIsrcs");
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackWorkLanguageEntity) && ownedType.GetTableName() == "TrackWorkLanguages");
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackWorkIswcEntity) && ownedType.GetTableName() == "TrackWorkIswcs");
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(AudioRatingEntity) && ownedType.GetTableName() == "TrackRatings");
}
@@ -314,6 +314,74 @@ public class BookRepositoryTests
Assert.Null(result.Value);
}
[Fact]
public async Task GetExistingPathsAsync_WhenPathsIsEmpty_ShouldReturnAnEmptyCollection()
{
// Arrange
IReadOnlyCollection<string> paths = [];
// Act
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(Guid.NewGuid(), paths, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetExistingPathsAsync_WhenCalled_ShouldReturnOnlyThePathsUsedByBooksOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity bookOfLibrary = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/tolkien/the-hobbit.epub");
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(libraryId: Guid.NewGuid(), path: "/books/tolkien/the-lord-of-the-rings.epub");
_mockContext.Books.AddRange(bookOfLibrary, bookOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(libraryId, ["/books/tolkien/the-hobbit.epub", "/books/tolkien/the-lord-of-the-rings.epub"], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
string existingPath = Assert.Single(result.Value);
Assert.Equal("/books/tolkien/the-hobbit.epub", existingPath);
}
[Fact]
public async Task GetExistingPathsAsync_WhenInputContainsDuplicatePaths_ShouldDeDuplicateTheResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/tolkien/the-hobbit.epub");
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(libraryId, ["/books/tolkien/the-hobbit.epub", "/books/tolkien/the-hobbit.epub", "/books/tolkien/the-hobbit.epub"], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Single(result.Value);
Assert.Equal("/books/tolkien/the-hobbit.epub", result.Value.First());
}
[Fact]
public async Task GetExistingPathsAsync_WhenPathDiffersOnlyByCase_ShouldNotReportItAsExisting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: "/Books/Tolkien/The-Hobbit.epub");
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(libraryId, ["/books/tolkien/the-hobbit.epub"], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetBooksNeedingMetadataAsync_WhenCalled_ShouldReturnOnlyBooksWhoseMetadataIsNotEnriched()
{
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.DataAccess.Core.Repositories.MediaContributors;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
@@ -91,6 +92,42 @@ public class MediaContributorRepositoryTests
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>());
}
[Fact]
public async Task FindOrCreateByDisplayNameAsync_WhenExistingNameStartsWithNonAsciiUppercase_ShouldReturnTheExistingContributor()
{
// Arrange
// The storage medium folds only ASCII case, so a name starting with a non-ASCII uppercase letter would previously not be found by the lookup
// and would be inserted again, violating the unique index on the display name.
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Лев Ошанин");
_mockContext.MediaContributors.Add(existingContributor);
await _mockContext.SaveChangesAsync();
// Act
Result<MediaContributorEntity> result = await _sut.FindOrCreateByDisplayNameAsync("Лев Ошанин", null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(existingContributor.Id, result.Value.Id);
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>());
}
[Fact]
public async Task FindOrCreateByDisplayNameAsync_WhenContributorWasAddedButNotSaved_ShouldReturnTheTrackedContributor()
{
// Arrange
Result<MediaContributorEntity> firstResult = await _sut.FindOrCreateByDisplayNameAsync("Bob Ludwig", null, CancellationToken.None);
Assert.False(firstResult.IsFailure);
// Act
Result<MediaContributorEntity> secondResult = await _sut.FindOrCreateByDisplayNameAsync("BOB LUDWIG", null, CancellationToken.None);
// Assert
Assert.False(secondResult.IsFailure);
// The contributor added earlier in the same unit of work is tracked, so it is returned instead of a duplicate being added.
Assert.Equal(firstResult.Value.Id, secondResult.Value.Id);
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>(), entityEntry => entityEntry.State == EntityState.Added);
}
[Fact]
public async Task GetByIdsAsync_WhenCalled_ShouldReturnOnlyTheContributorsWithTheProvidedIds()
{
@@ -128,4 +165,21 @@ public class MediaContributorRepositoryTests
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == contributor.Id);
Assert.NotNull(addedContributor);
}
[Fact]
public async Task InsertAsync_WhenContributorWithSameIdAlreadyExists_ShouldReturnError()
{
// Arrange
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create();
_mockContext.MediaContributors.Add(existingContributor);
await _mockContext.SaveChangesAsync();
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(id: existingContributor.Id);
// Act
Result<Created> result = await _sut.InsertAsync(contributor, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.MediaContributor.MediaContributorAlreadyExists, result.FirstError);
}
}
@@ -14,6 +14,7 @@ using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using NSubstitute;
@@ -499,6 +500,32 @@ public class AlbumRepositoryTests
Assert.Single(_mockContext.Set<GenreEntity>().Where(genre => genre.Name == "ExistingGenre"));
}
[Fact]
public async Task UpdateAsync_WhenCatalogNumbersChange_ShouldAddTheNewAndRemoveTheMissingOnes()
{
// Arrange
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false, catalogNumbers: ["EMC 3006", "OC 062 o 94519"]);
_mockContext.Albums.Add(storedAlbum);
await _mockContext.SaveChangesAsync();
AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false, catalogNumbers: ["EMC 3006", "EMTC 104"]);
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
AlbumEntity? retrievedAlbum = await _mockContext.Albums
.Include(album => album.CatalogNumbers)
.FirstOrDefaultAsync(album => album.Id == storedAlbum.Id);
Assert.NotNull(retrievedAlbum);
Assert.Equal(2, retrievedAlbum!.CatalogNumbers.Count);
Assert.Contains(retrievedAlbum.CatalogNumbers, catalogNumber => catalogNumber.CatalogNumber == "EMC 3006");
Assert.Contains(retrievedAlbum.CatalogNumbers, catalogNumber => catalogNumber.CatalogNumber == "EMTC 104");
Assert.DoesNotContain(retrievedAlbum.CatalogNumbers, catalogNumber => catalogNumber.CatalogNumber == "OC 062 o 94519");
}
[Fact]
public async Task GetByIdAsync_WhenAlbumExists_ShouldReturnTheAlbum()
{
@@ -714,6 +741,26 @@ public class AlbumRepositoryTests
Assert.Equal(12, row.TotalTracks);
}
[Fact]
public async Task GetAlbumsNeedingMetadataCountAsync_WhenAlbumsHaveMixedMetadataStatuses_ShouldCountOnlyTheNotEnrichedOnesOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AlbumEntity pendingAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
AlbumEntity failedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Failed);
AlbumEntity enrichedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Enriched);
AlbumEntity albumOfAnotherLibrary = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
_mockContext.Albums.AddRange(pendingAlbum, failedAlbum, enrichedAlbum, albumOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetAlbumsNeedingMetadataCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value);
}
/// <summary>
/// Creates an album that belongs to the artist identified by <paramref name="artistId"/>, with every related collection populated deterministically.
/// </summary>
@@ -16,6 +16,7 @@ using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
@@ -1118,6 +1119,104 @@ public class ArtistRepositoryTests
Assert.Equal(expectedRowCount, page.Data.Count);
}
[Fact]
public async Task GetArtistsNeedingMetadataAsync_WhenAnArtistAndAllItsDescendantsAreEnriched_ShouldNotReturnIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity enriched = CreateArtistWithFullAggregate();
enriched.LibraryId = libraryId;
MarkEnriched(enriched);
ArtistEntity pending = _artistEntityFixture.Create(libraryId: libraryId, name: "Pending Artist", includeAlbums: false, includeContributors: false);
_mockContext.Artists.AddRange(enriched, pending);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<ArtistEntity>> result = await _sut.GetArtistsNeedingMetadataAsync(libraryId, null, 10, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistEntity onlyArtist = Assert.Single(result.Value);
Assert.Equal(pending.Id, onlyArtist.Id);
}
[Fact]
public async Task GetArtistsNeedingMetadataAsync_WhenATrackIsNotEnriched_ShouldReturnTheArtist()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = CreateArtistWithFullAggregate();
artist.LibraryId = libraryId;
MarkEnriched(artist);
artist.Albums[0].Tracks[0].MetadataStatus = MetadataStatus.Pending;
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<ArtistEntity>> result = await _sut.GetArtistsNeedingMetadataAsync(libraryId, null, 10, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistEntity onlyArtist = Assert.Single(result.Value);
Assert.Equal(artist.Id, onlyArtist.Id);
}
[Fact]
public async Task GetArtistsNeedingMetadataAsync_WhenLastNameIsProvided_ShouldReturnOnlyArtistsAfterIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity alpha = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false);
ArtistEntity beta = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false);
ArtistEntity gamma = _artistEntityFixture.Create(libraryId: libraryId, name: "Gamma", includeAlbums: false, includeContributors: false);
_mockContext.Artists.AddRange(alpha, beta, gamma);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<ArtistEntity>> result = await _sut.GetArtistsNeedingMetadataAsync(libraryId, "Beta", 10, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistEntity onlyArtist = Assert.Single(result.Value);
Assert.Equal(gamma.Id, onlyArtist.Id);
}
[Fact]
public async Task GetArtistsNeedingMetadataCountAsync_ShouldCountArtistsWithPendingMetadataIncludingDescendants()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity enriched = CreateArtistWithFullAggregate();
enriched.LibraryId = libraryId;
MarkEnriched(enriched);
ArtistEntity pending = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
ArtistEntity otherLibrary = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
_mockContext.Artists.AddRange(enriched, pending, otherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetArtistsNeedingMetadataCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, result.Value);
}
/// <summary>
/// Marks the provided artist, its albums and its tracks as enriched.
/// </summary>
/// <param name="artist">The artist whose metadata enrichment status is set.</param>
private static void MarkEnriched(ArtistEntity artist)
{
artist.MetadataStatus = MetadataStatus.Enriched;
foreach (AlbumEntity album in artist.Albums)
{
album.MetadataStatus = MetadataStatus.Enriched;
foreach (TrackEntity track in album.Tracks)
track.MetadataStatus = MetadataStatus.Enriched;
}
}
/// <summary>
/// Creates an artist that owns an album which in turn owns a track, with every related collection of the aggregate populated deterministically.
/// </summary>
@@ -0,0 +1,130 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary;
/// <summary>
/// Contains unit tests for the <see cref="MusicLibraryScanItemMetadataRepository"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicLibraryScanItemMetadataRepositoryTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly LuminaDbContext _context;
private readonly MusicLibraryScanItemMetadataRepository _sut;
private readonly MusicLibraryScanItemMetadataEntityFixture _musicLibraryScanItemMetadataEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MusicLibraryScanItemMetadataRepositoryTests"/> class.
/// </summary>
public MusicLibraryScanItemMetadataRepositoryTests()
{
// the repository deletes in bulk, which translates to SQL, so it can only be exercised against a real SQLite database
_connection = new SqliteConnection("Data Source=:memory:");
_connection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connection).Options);
_context.Database.EnsureCreated();
_sut = new MusicLibraryScanItemMetadataRepository(_context);
}
[Fact]
public async Task InsertRangeAsync_WhenCalledWithItems_ShouldAddThemToContextAndReturnCreated()
{
// Arrange
List<MusicLibraryScanItemMetadataEntity> items = _musicLibraryScanItemMetadataEntityFixture.CreateMany(3);
// Act
Result<Created> result = await _sut.InsertRangeAsync(items, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
await _context.SaveChangesAsync();
Assert.Equal(3, await _context.MusicLibraryScanItemMetadata.CountAsync());
}
[Fact]
public async Task InsertRangeAsync_WhenCollectionIsEmpty_ShouldReturnCreatedWithoutAddingAnyItems()
{
// Act
Result<Created> result = await _sut.InsertRangeAsync([], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
await _context.SaveChangesAsync();
Assert.Empty(await _context.MusicLibraryScanItemMetadata.ToListAsync());
}
[Fact]
public async Task GetByScanIdAsync_WhenCalled_ShouldReturnOnlyTheItemsOfTheScanOrderedByPath()
{
// Arrange
Guid scanId = Guid.NewGuid();
MusicLibraryScanItemMetadataEntity bicycleItem = _musicLibraryScanItemMetadataEntityFixture.Create(libraryScanId: scanId, path: "/music/queen/bicycle-race.flac");
MusicLibraryScanItemMetadataEntity bohemianItem = _musicLibraryScanItemMetadataEntityFixture.Create(libraryScanId: scanId, path: "/music/queen/bohemian-rhapsody.flac");
MusicLibraryScanItemMetadataEntity itemOfAnotherScan = _musicLibraryScanItemMetadataEntityFixture.Create(path: "/music/queen/dont-stop-me-now.flac");
_context.MusicLibraryScanItemMetadata.AddRange(bicycleItem, bohemianItem, itemOfAnotherScan);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>> result = await _sut.GetByScanIdAsync(scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([bicycleItem.Id, bohemianItem.Id], result.Value.Select(item => item.Id));
}
[Fact]
public async Task GetByScanIdAsync_WhenNoItemsExistForTheScan_ShouldReturnAnEmptyCollection()
{
// Act
Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>> result = await _sut.GetByScanIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task DeleteByScanIdAsync_WhenCalled_ShouldDeleteOnlyTheItemsOfTheScan()
{
// Arrange
Guid scanId = Guid.NewGuid();
MusicLibraryScanItemMetadataEntity itemOfScan = _musicLibraryScanItemMetadataEntityFixture.Create(libraryScanId: scanId, path: "/music/queen/bohemian-rhapsody.flac");
MusicLibraryScanItemMetadataEntity itemOfAnotherScan = _musicLibraryScanItemMetadataEntityFixture.Create(path: "/music/queen/love-of-my-life.flac");
_context.MusicLibraryScanItemMetadata.AddRange(itemOfScan, itemOfAnotherScan);
await _context.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByScanIdAsync(scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
MusicLibraryScanItemMetadataEntity remainingItem = Assert.Single(await _context.MusicLibraryScanItemMetadata.ToListAsync());
Assert.Equal(itemOfAnotherScan.Id, remainingItem.Id);
}
/// <summary>
/// Disposes the database context and its underlying connection.
/// </summary>
public void Dispose()
{
_context.Dispose();
_connection.Dispose();
}
}
@@ -13,6 +13,7 @@ using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
@@ -792,4 +793,24 @@ public class TrackRepositoryTests
Assert.Equal(9, row.TrackNumber);
Assert.Equal(3, row.DiscNumber);
}
[Fact]
public async Task GetTracksNeedingMetadataCountAsync_WhenTracksHaveMixedMetadataStatuses_ShouldCountOnlyTheNotEnrichedOnesOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
TrackEntity pendingTrack = _trackEntityFixture.Create(libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
TrackEntity failedTrack = _trackEntityFixture.Create(libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Failed);
TrackEntity enrichedTrack = _trackEntityFixture.Create(libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Enriched);
TrackEntity trackOfAnotherLibrary = _trackEntityFixture.Create(includeMetadata: false, metadataStatus: MetadataStatus.Pending);
_mockContext.Tracks.AddRange(pendingTrack, failedTrack, enrichedTrack, trackOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetTracksNeedingMetadataCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value);
}
}