Renames project paths from Lumina to Nemera

This commit is contained in:
BinaryAlley committed 2026-11-27 15:34:43 +02:00
1 parent ce6fddb4c9
commit 0f659a4877
6450 files changed

No files matched your search

@@ -0,0 +1,208 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
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="AlbumConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AlbumConfigurationTests : IDisposable
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="AlbumConfigurationTests"/> class.
/// </summary>
public AlbumConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("Albums", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
// Act
IProperty idProperty = entityType.GetProperty(nameof(AlbumEntity.Id));
// Assert
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
// Act
IProperty artistIdProperty = entityType.GetProperty(nameof(AlbumEntity.ArtistId));
IProperty libraryIdProperty = entityType.GetProperty(nameof(AlbumEntity.LibraryId));
IProperty titleProperty = entityType.GetProperty(nameof(AlbumEntity.Title));
IProperty originalTitleProperty = entityType.GetProperty(nameof(AlbumEntity.OriginalTitle));
IProperty descriptionProperty = entityType.GetProperty(nameof(AlbumEntity.Description));
IProperty releaseCountryProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseCountry));
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.FindNavigation(nameof(AlbumEntity.CatalogNumbers))!.TargetEntityType.GetProperty(nameof(AlbumCatalogNumberEntity.CatalogNumber));
IProperty languageCodeProperty = entityType.GetProperty(nameof(AlbumEntity.LanguageCode));
// Assert
Assert.False(artistIdProperty.IsNullable);
Assert.False(libraryIdProperty.IsNullable);
Assert.False(titleProperty.IsNullable);
Assert.Equal(255, titleProperty.GetMaxLength());
Assert.Equal(255, originalTitleProperty.GetMaxLength());
Assert.Equal(2000, descriptionProperty.GetMaxLength());
Assert.Equal(typeof(ReleaseCountry?), releaseCountryProperty.ClrType);
Assert.Equal("TEXT", releaseCountryProperty.GetColumnType());
Assert.Equal(2, releaseCountryProperty.GetMaxLength());
Assert.Equal(typeof(MusicReleaseType), releaseTypeProperty.ClrType);
Assert.Equal("TEXT", releaseTypeProperty.GetColumnType());
Assert.Equal(50, releaseTypeProperty.GetMaxLength());
Assert.Equal(typeof(MusicReleaseStatus?), releaseStatusProperty.ClrType);
Assert.Equal("TEXT", releaseStatusProperty.GetColumnType());
Assert.Equal(50, releaseStatusProperty.GetMaxLength());
Assert.Equal(typeof(MusicMediaFormat?), mediaFormatProperty.ClrType);
Assert.Equal("TEXT", mediaFormatProperty.GetColumnType());
Assert.Equal(50, mediaFormatProperty.GetMaxLength());
Assert.Equal(13, barcodeProperty.GetMaxLength());
Assert.Equal(50, catalogNumberProperty.GetMaxLength());
Assert.True(languageCodeProperty.IsNullable);
Assert.Equal(typeof(string), languageCodeProperty.ClrType);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureArtistRelationshipWithCascadeDelete()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
// Act
List<IForeignKey> foreignKeys = [.. entityType.GetForeignKeys()];
// Assert
IForeignKey artistForeignKey = Assert.Single(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(ArtistEntity));
Assert.Equal(nameof(AlbumEntity.ArtistId), artistForeignKey.Properties.Single().Name);
Assert.Equal(DeleteBehavior.Cascade, artistForeignKey.DeleteBehavior);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOwnedAlbumRatings()
{
// Arrange
IEntityType ratingEntityType = _context.Model.GetEntityTypes()
.Single(entityType => entityType.IsOwned() && entityType.ClrType == typeof(AudioRatingEntity) && entityType.GetTableName() == "AlbumRatings");
// Act
string? tableName = ratingEntityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = ratingEntityType.FindPrimaryKey()!.Properties;
IProperty valueProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.Value));
IProperty maxValueProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.MaxValue));
IProperty voteCountProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.VoteCount));
IProperty sourceProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.Source));
// Assert
Assert.Equal("AlbumRatings", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
Assert.Equal("decimal(3,2)", valueProperty.GetColumnType());
Assert.False(valueProperty.IsNullable);
Assert.Equal("decimal(3,2)", maxValueProperty.GetColumnType());
Assert.False(maxValueProperty.IsNullable);
Assert.True(voteCountProperty.IsNullable);
Assert.Equal(typeof(AudioRatingSource?), sourceProperty.ClrType);
Assert.Equal("TEXT", sourceProperty.GetColumnType());
Assert.Equal(50, sourceProperty.GetMaxLength());
Assert.True(sourceProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureManyToManyJoinTablesForTagsAndGenres()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
// Act
List<ISkipNavigation> skipNavigations = [.. entityType.GetSkipNavigations()];
// Assert
Assert.Equal(2, skipNavigations.Count);
ISkipNavigation tagsNavigation = Assert.Single(skipNavigations, navigation => navigation.Name == nameof(AlbumEntity.Tags));
Assert.Equal("AlbumTags", tagsNavigation.JoinEntityType.GetTableName());
Assert.Equal(["AlbumId", "TagId"], tagsNavigation.JoinEntityType.FindPrimaryKey()!.Properties.Select(property => property.Name));
ISkipNavigation genresNavigation = Assert.Single(skipNavigations, navigation => navigation.Name == nameof(AlbumEntity.Genres));
Assert.Equal("AlbumGenres", genresNavigation.JoinEntityType.GetTableName());
Assert.Equal(["AlbumId", "GenreId"], genresNavigation.JoinEntityType.FindPrimaryKey()!.Properties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureIndexesOnArtistIdTitleAndLibraryIdTitle()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
// Act
List<IIndex> indexes = [.. entityType.GetIndexes()];
// Assert
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(AlbumEntity.ArtistId), nameof(AlbumEntity.Title)]));
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(AlbumEntity.LibraryId), nameof(AlbumEntity.Title)]));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(AlbumEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(AlbumEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(AlbumEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(AlbumEntity.UpdatedBy));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.False(createdByProperty.IsNullable);
Assert.True(updatedOnUtcProperty.IsNullable);
Assert.True(updatedByProperty.IsNullable);
}
/// <summary>
/// Disposes the database context.
/// </summary>
public void Dispose()
{
_context.Dispose();
}
}
@@ -0,0 +1,135 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Core.UoW;
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="ArtistConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtistConfigurationTests : IDisposable
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="ArtistConfigurationTests"/> class.
/// </summary>
public ArtistConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("Artists", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!;
// Act
IProperty idProperty = entityType.GetProperty(nameof(ArtistEntity.Id));
// Assert
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!;
// Act
IProperty libraryIdProperty = entityType.GetProperty(nameof(ArtistEntity.LibraryId));
IProperty nameProperty = entityType.GetProperty(nameof(ArtistEntity.Name));
IProperty websiteProperty = entityType.GetProperty(nameof(ArtistEntity.Website));
IProperty musicBrainzArtistIdProperty = entityType.GetProperty(nameof(ArtistEntity.MusicBrainzArtistId));
// Assert
Assert.False(libraryIdProperty.IsNullable);
Assert.False(nameProperty.IsNullable);
Assert.Equal(255, nameProperty.GetMaxLength());
Assert.True(websiteProperty.IsNullable);
Assert.Equal(2048, websiteProperty.GetMaxLength());
Assert.True(musicBrainzArtistIdProperty.IsNullable);
Assert.Equal(typeof(Guid?), musicBrainzArtistIdProperty.ClrType);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureContributorsRelationshipWithCascadeDelete()
{
// Arrange
IEntityType contributorEntityType = _context.Model.FindEntityType(typeof(ArtistContributorEntity))!;
// Act
List<IForeignKey> foreignKeys = [.. contributorEntityType.GetForeignKeys()];
// Assert
IForeignKey artistForeignKey = Assert.Single(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(ArtistEntity));
Assert.Equal(nameof(ArtistContributorEntity.ArtistId), artistForeignKey.Properties.Single().Name);
Assert.Equal(DeleteBehavior.Cascade, artistForeignKey.DeleteBehavior);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnLibraryIdAndName()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!;
// Act
List<IIndex> indexes = [.. entityType.GetIndexes()];
// Assert
IIndex uniquenessIndex = Assert.Single(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(ArtistEntity.LibraryId), nameof(ArtistEntity.Name)]));
Assert.True(uniquenessIndex.IsUnique);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(ArtistEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(ArtistEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(ArtistEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(ArtistEntity.UpdatedBy));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.False(createdByProperty.IsNullable);
Assert.True(updatedOnUtcProperty.IsNullable);
Assert.True(updatedByProperty.IsNullable);
}
/// <summary>
/// Disposes the database context.
/// </summary>
public void Dispose()
{
_context.Dispose();
}
}
@@ -0,0 +1,129 @@
#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;
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="BookConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="BookConfigurationTests"/> class.
/// </summary>
public BookConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("Books", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!;
// Act
IProperty titleProperty = entityType.GetProperty(nameof(BookEntity.Title));
IProperty pathProperty = entityType.GetProperty(nameof(BookEntity.Path));
IProperty formatProperty = entityType.GetProperty(nameof(BookEntity.Format));
IProperty metadataStatusProperty = entityType.GetProperty(nameof(BookEntity.MetadataStatus));
// Assert
Assert.False(titleProperty.IsNullable);
Assert.Equal(255, titleProperty.GetMaxLength());
Assert.False(pathProperty.IsNullable);
Assert.Equal(2048, pathProperty.GetMaxLength());
Assert.Equal(typeof(BookFormat?), formatProperty.ClrType);
Assert.Equal("TEXT", formatProperty.GetColumnType());
Assert.Equal(typeof(MetadataStatus), metadataStatusProperty.ClrType);
Assert.Equal("TEXT", metadataStatusProperty.GetColumnType());
Assert.Equal(20, metadataStatusProperty.GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOwnedTypesForRatingsAndIsbns()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!;
// Act
List<IEntityType> ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)];
// Assert
Assert.Equal(2, ownedTypes.Count);
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(BookRatingEntity) && ownedType.GetTableName() == "BookRatings");
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(IsbnEntity) && ownedType.GetTableName() == "BookISBNs");
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureManyToManyJoinTablesForTagsAndGenres()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!;
// Act
List<ISkipNavigation> skipNavigations = [.. entityType.GetSkipNavigations()];
// Assert
Assert.Equal(2, skipNavigations.Count);
Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(BookEntity.Tags) && navigation.JoinEntityType.GetTableName() == "BookTags");
Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(BookEntity.Genres) && navigation.JoinEntityType.GetTableName() == "BookGenres");
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureIndexesOnLibraryIdAndPath()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!;
// Act
List<IIndex> indexes = [.. entityType.GetIndexes()];
// Assert
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(BookEntity.LibraryId), nameof(BookEntity.Path)]));
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(BookEntity.LibraryId), nameof(BookEntity.MetadataStatus)]));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(BookEntity.CreatedOnUtc));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(BookEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
}
@@ -0,0 +1,88 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
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="DirectoryScanFingerprintConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DirectoryScanFingerprintConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryScanFingerprintConfigurationTests"/> class.
/// </summary>
public DirectoryScanFingerprintConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndCompositeKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(DirectoryScanFingerprintEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("DirectoryScanFingerprints", tableName);
Assert.Equal([nameof(DirectoryScanFingerprintEntity.LibraryId), nameof(DirectoryScanFingerprintEntity.Path)], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(DirectoryScanFingerprintEntity))!;
// Act
IProperty pathProperty = entityType.GetProperty(nameof(DirectoryScanFingerprintEntity.Path));
IProperty lastWriteTimeUtcProperty = entityType.GetProperty(nameof(DirectoryScanFingerprintEntity.LastWriteTimeUtc));
// Assert
Assert.False(pathProperty.IsNullable);
Assert.Equal(1024, pathProperty.GetMaxLength());
Assert.False(lastWriteTimeUtcProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRelationshipWithCascadeDelete()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(DirectoryScanFingerprintEntity))!;
// Act
IForeignKey foreignKey = Assert.Single(entityType.GetForeignKeys());
// Assert
Assert.Equal(typeof(LibraryEntity), foreignKey.PrincipalEntityType.ClrType);
Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior);
Assert.Equal(nameof(DirectoryScanFingerprintEntity.LibraryId), foreignKey.Properties[0].Name);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureIndexOnLibraryId()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(DirectoryScanFingerprintEntity))!;
// Act
IIndex index = Assert.Single(entityType.GetIndexes());
// Assert
Assert.Equal(nameof(DirectoryScanFingerprintEntity.LibraryId), index.Properties[0].Name);
}
}
@@ -0,0 +1,211 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Favorites;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
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="FavoriteConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FavoriteConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="FavoriteConfigurationTests"/> class.
/// </summary>
public FavoriteConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
/// <summary>
/// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits.
/// </summary>
private IModel DesignTimeModel => _context.GetService<IDesignTimeModel>().Model;
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("Favorites", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldNotGenerateTheIdValueAndOrderItFirst()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(FavoriteEntity))!;
// Act
IProperty idProperty = entityType.GetProperty(nameof(FavoriteEntity.Id));
// Assert
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
Assert.Equal(0, idProperty.GetColumnOrder());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureCascadingRelationshipWithUser()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
// Act
IForeignKey userForeignKey = Assert.Single(entityType.GetForeignKeys());
// Assert
Assert.Equal(typeof(UserEntity), userForeignKey.PrincipalEntityType.ClrType);
Assert.Equal(nameof(FavoriteEntity.UserId), userForeignKey.Properties[0].Name);
Assert.Equal(DeleteBehavior.Cascade, userForeignKey.DeleteBehavior);
Assert.True(userForeignKey.IsRequired);
}
[Fact]
public void Configure_WhenApplied_ShouldStoreTheMediaKindAsABoundedRequiredString()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
// Act
IProperty mediaKindProperty = entityType.GetProperty(nameof(FavoriteEntity.MediaKind));
// Assert
Assert.Equal(typeof(FavoriteMediaKind), mediaKindProperty.ClrType);
Assert.Equal(typeof(string), mediaKindProperty.GetTypeMapping().Converter!.ProviderClrType);
Assert.Equal("TEXT", mediaKindProperty.GetColumnType());
Assert.Equal(20, mediaKindProperty.GetMaxLength());
Assert.False(mediaKindProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheRequiredColumns()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
// Act
IProperty userIdProperty = entityType.GetProperty(nameof(FavoriteEntity.UserId));
IProperty mediaItemIdProperty = entityType.GetProperty(nameof(FavoriteEntity.MediaItemId));
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(FavoriteEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(FavoriteEntity.CreatedBy));
// Assert
Assert.False(userIdProperty.IsNullable);
Assert.False(mediaItemIdProperty.IsNullable);
Assert.False(createdOnUtcProperty.IsNullable);
Assert.False(createdByProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheNullableAuditColumns()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
// Act
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(FavoriteEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(FavoriteEntity.UpdatedBy));
// Assert
Assert.True(updatedOnUtcProperty.IsNullable);
Assert.True(updatedByProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
Assert.Null(updatedByProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheUniqueBusinessKeyIndex()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
// Act
IIndex businessKeyIndex = Assert.Single(
entityType.GetIndexes(),
index => index.Properties.Select(property => property.Name).SequenceEqual(
[
nameof(FavoriteEntity.UserId),
nameof(FavoriteEntity.MediaKind),
nameof(FavoriteEntity.MediaItemId)
]));
// Assert
Assert.True(businessKeyIndex.IsUnique);
Assert.Equal(3, businessKeyIndex.Properties.Count);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheListingIndexes()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
// Act
IIndex everyKindListingIndex = Assert.Single(
entityType.GetIndexes(),
index => index.Properties.Select(property => property.Name).SequenceEqual(
[
nameof(FavoriteEntity.UserId),
nameof(FavoriteEntity.CreatedOnUtc)
]));
IIndex oneKindListingIndex = Assert.Single(
entityType.GetIndexes(),
index => index.Properties.Select(property => property.Name).SequenceEqual(
[
nameof(FavoriteEntity.UserId),
nameof(FavoriteEntity.MediaKind),
nameof(FavoriteEntity.CreatedOnUtc)
]));
// Assert
Assert.False(everyKindListingIndex.IsUnique);
Assert.False(oneKindListingIndex.IsUnique);
}
[Fact]
public void Configure_WhenApplied_ShouldOrderEveryColumnAsConfigured()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(FavoriteEntity))!;
// Act
IProperty idProperty = entityType.GetProperty(nameof(FavoriteEntity.Id));
IProperty userIdProperty = entityType.GetProperty(nameof(FavoriteEntity.UserId));
IProperty mediaKindProperty = entityType.GetProperty(nameof(FavoriteEntity.MediaKind));
IProperty mediaItemIdProperty = entityType.GetProperty(nameof(FavoriteEntity.MediaItemId));
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(FavoriteEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(FavoriteEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(FavoriteEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(FavoriteEntity.UpdatedBy));
// Assert
Assert.Equal(0, idProperty.GetColumnOrder());
Assert.Equal(1, userIdProperty.GetColumnOrder());
Assert.Equal(2, mediaKindProperty.GetColumnOrder());
Assert.Equal(3, mediaItemIdProperty.GetColumnOrder());
Assert.Equal(4, createdOnUtcProperty.GetColumnOrder());
Assert.Equal(5, createdByProperty.GetColumnOrder());
Assert.Equal(6, updatedOnUtcProperty.GetColumnOrder());
Assert.Equal(7, updatedByProperty.GetColumnOrder());
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.DataAccess.Core.UoW;
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="GenreConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GenreConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="GenreConfigurationTests"/> class.
/// </summary>
public GenreConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(GenreEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("Genres", tableName);
Assert.Equal([nameof(GenreEntity.Name)], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureNameAsRequired()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(GenreEntity))!;
// Act
IProperty nameProperty = entityType.GetProperty(nameof(GenreEntity.Name));
// Assert
Assert.False(nameProperty.IsNullable);
Assert.Equal(50, nameProperty.GetMaxLength());
}
}
@@ -0,0 +1,89 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.DataAccess.Core.UoW;
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="LibraryBookReaderConfigurationConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryBookReaderConfigurationConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryBookReaderConfigurationConfigurationTests"/> class.
/// </summary>
public LibraryBookReaderConfigurationConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryBookReaderConfigurationEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("LibraryBookReaderConfigurations", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarPropertiesAsRequired()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryBookReaderConfigurationEntity))!;
// Act
IProperty libraryIdProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.LibraryId));
IProperty pluginIdProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.PluginId));
IProperty isEnabledProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.IsEnabled));
// Assert
Assert.False(libraryIdProperty.IsNullable);
Assert.False(pluginIdProperty.IsNullable);
Assert.False(isEnabledProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureIndexOnLibraryIdAndPluginId()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryBookReaderConfigurationEntity))!;
// Act
IIndex index = Assert.Single(entityType.GetIndexes());
// Assert
Assert.Equal([nameof(LibraryBookReaderConfigurationEntity.LibraryId), nameof(LibraryBookReaderConfigurationEntity.PluginId)], index.Properties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryBookReaderConfigurationEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.CreatedOnUtc));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
}
@@ -0,0 +1,295 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
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="LibraryConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryConfigurationTests"/> class.
/// </summary>
public LibraryConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
/// <summary>
/// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits.
/// </summary>
private IModel DesignTimeModel => _context.GetService<IDesignTimeModel>().Model;
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("Libraries", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
// Act
IProperty titleProperty = entityType.GetProperty(nameof(LibraryEntity.Title));
IProperty libraryTypeProperty = entityType.GetProperty(nameof(LibraryEntity.LibraryType));
IProperty isEnabledProperty = entityType.GetProperty(nameof(LibraryEntity.IsEnabled));
IProperty downloadMetadataProperty = entityType.GetProperty(nameof(LibraryEntity.CanDownloadMetadataFromWeb));
IProperty shouldTrackConsumptionProgressProperty = entityType.GetProperty(nameof(LibraryEntity.ShouldTrackConsumptionProgress));
IProperty completionThresholdPercentageProperty = entityType.GetProperty(nameof(LibraryEntity.CompletionThresholdPercentage));
IProperty isContentOnSsdProperty = entityType.GetProperty(nameof(LibraryEntity.IsContentOnSsd));
// Assert
Assert.False(titleProperty.IsNullable);
Assert.Equal(255, titleProperty.GetMaxLength());
Assert.Equal(typeof(LibraryType), libraryTypeProperty.ClrType);
Assert.Equal("TEXT", libraryTypeProperty.GetColumnType());
Assert.Equal(true, isEnabledProperty.GetDefaultValue());
Assert.Equal(true, downloadMetadataProperty.GetDefaultValue());
Assert.Equal(typeof(bool), shouldTrackConsumptionProgressProperty.ClrType);
Assert.False(shouldTrackConsumptionProgressProperty.IsNullable);
Assert.Equal(false, shouldTrackConsumptionProgressProperty.GetDefaultValue());
Assert.Equal(typeof(int?), completionThresholdPercentageProperty.ClrType);
Assert.True(completionThresholdPercentageProperty.IsNullable);
Assert.Null(completionThresholdPercentageProperty.GetDefaultValue());
Assert.Equal(typeof(bool), isContentOnSsdProperty.ClrType);
Assert.False(isContentOnSsdProperty.IsNullable);
Assert.Equal(false, isContentOnSsdProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureSsdContentColumnOrder()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
// Act
IProperty isContentOnSsdProperty = entityType.GetProperty(nameof(LibraryEntity.IsContentOnSsd));
// Assert
Assert.Equal(18, isContentOnSsdProperty.GetColumnOrder());
Assert.Equal(nameof(LibraryEntity.IsContentOnSsd), isContentOnSsdProperty.GetColumnName());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigurePathTemplateFingerprint()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
// Act
IProperty fingerprintProperty = entityType.GetProperty(nameof(LibraryEntity.PathTemplateFingerprint));
// Assert
Assert.True(fingerprintProperty.IsNullable);
Assert.Equal(typeof(string), fingerprintProperty.ClrType);
Assert.Equal(64, fingerprintProperty.GetMaxLength());
Assert.Equal(11, fingerprintProperty.GetColumnOrder());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureConsumptionSettingsColumnOrders()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
// Act
IProperty shouldTrackProperty = entityType.GetProperty(nameof(LibraryEntity.ShouldTrackConsumptionProgress));
IProperty completionThresholdProperty = entityType.GetProperty(nameof(LibraryEntity.CompletionThresholdPercentage));
// Assert
Assert.Equal(16, shouldTrackProperty.GetColumnOrder());
Assert.Equal(17, completionThresholdProperty.GetColumnOrder());
Assert.Equal(nameof(LibraryEntity.ShouldTrackConsumptionProgress), shouldTrackProperty.GetColumnName());
Assert.Equal(nameof(LibraryEntity.CompletionThresholdPercentage), completionThresholdProperty.GetColumnName());
}
[Fact]
public void Configure_WhenApplied_ShouldMapConsumptionSettingsAsScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
// Act
IProperty shouldTrackConsumptionProgressProperty = entityType.GetProperty(nameof(LibraryEntity.ShouldTrackConsumptionProgress));
IProperty completionThresholdPercentageProperty = entityType.GetProperty(nameof(LibraryEntity.CompletionThresholdPercentage));
List<INavigation> navigations = [.. entityType.GetNavigations()];
// Assert
Assert.Equal(typeof(LibraryEntity), shouldTrackConsumptionProgressProperty.DeclaringType.ClrType);
Assert.Equal(typeof(LibraryEntity), completionThresholdPercentageProperty.DeclaringType.ClrType);
Assert.DoesNotContain(navigations, navigation => navigation.Name == nameof(LibraryEntity.ShouldTrackConsumptionProgress));
Assert.DoesNotContain(navigations, navigation => navigation.Name == nameof(LibraryEntity.CompletionThresholdPercentage));
}
[Fact]
public void Configure_WhenApplied_ShouldMapConsumptionSettingsToTheirOwnColumns()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
// Act
string shouldTrackConsumptionProgressColumnName = entityType.GetProperty(nameof(LibraryEntity.ShouldTrackConsumptionProgress)).GetColumnName();
string completionThresholdPercentageColumnName = entityType.GetProperty(nameof(LibraryEntity.CompletionThresholdPercentage)).GetColumnName();
// Assert
Assert.Equal(nameof(LibraryEntity.ShouldTrackConsumptionProgress), shouldTrackConsumptionProgressColumnName);
Assert.Equal(nameof(LibraryEntity.CompletionThresholdPercentage), completionThresholdPercentageColumnName);
Assert.NotEqual(shouldTrackConsumptionProgressColumnName, completionThresholdPercentageColumnName);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOwnedContentLocations()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
// Act
IEntityType contentLocationType = Assert.Single(
_context.Model.GetEntityTypes(),
ownedType => ownedType.IsOwned()
&& ownedType.ClrType == typeof(LibraryContentLocationEntity)
&& ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name);
// Assert
Assert.Equal(typeof(LibraryContentLocationEntity), contentLocationType.ClrType);
Assert.Equal("LibraryContentLocations", contentLocationType.GetTableName());
Assert.Equal(260, contentLocationType.GetProperty(nameof(LibraryContentLocationEntity.Path)).GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOwnedPathTemplateParts()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
// Act
IEntityType partEntityType = Assert.Single(
_context.Model.GetEntityTypes(),
ownedType => ownedType.IsOwned()
&& ownedType.ClrType == typeof(LibraryPathTemplatePartEntity)
&& ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name);
IForeignKey ownershipForeignKey = partEntityType.FindOwnership()!;
// Assert
Assert.Equal("LibraryPathTemplateParts", partEntityType.GetTableName());
Assert.Equal(["Id"], partEntityType.FindPrimaryKey()!.Properties.Select(property => property.Name));
Assert.Equal(typeof(LibraryEntity), ownershipForeignKey.PrincipalEntityType.ClrType);
Assert.Equal(["LibraryId"], ownershipForeignKey.Properties.Select(property => property.Name));
Assert.True(ownershipForeignKey.IsRequired);
IIndex uniqueIndex = Assert.Single(
partEntityType.GetIndexes(),
index => index.Properties.Select(property => property.Name).SequenceEqual(["LibraryId", nameof(LibraryPathTemplatePartEntity.Position)]));
Assert.True(uniqueIndex.IsUnique);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOwnedPathTemplatePartColumns()
{
// Arrange
IEntityType partEntityType = DesignTimeModel.GetEntityTypes()
.Single(entityType => entityType.IsOwned()
&& entityType.ClrType == typeof(LibraryPathTemplatePartEntity)
&& entityType.GetTableName() == "LibraryPathTemplateParts");
// Act
IProperty positionProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Position));
IProperty kindProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Kind));
IProperty representationProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Representation));
IProperty isOptionalProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.IsOptional));
// Assert
Assert.Equal("Position", positionProperty.GetColumnName());
Assert.False(positionProperty.IsNullable);
Assert.Equal(typeof(LibraryPathPartKind), kindProperty.ClrType);
Assert.Equal(typeof(string), kindProperty.GetTypeMapping().Converter!.ProviderClrType);
Assert.Equal("TEXT", kindProperty.GetColumnType());
Assert.Equal(32, kindProperty.GetMaxLength());
Assert.False(kindProperty.IsNullable);
Assert.Equal(512, representationProperty.GetMaxLength());
Assert.False(representationProperty.IsNullable);
Assert.Equal(typeof(bool), isOptionalProperty.ClrType);
Assert.False(isOptionalProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRelationships()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
// Act
IForeignKey userForeignKey = Assert.Single(entityType.GetForeignKeys());
List<INavigation> navigations = [.. entityType.GetNavigations()];
// Assert
Assert.Equal(DeleteBehavior.Cascade, userForeignKey.DeleteBehavior);
Assert.Equal(nameof(LibraryEntity.UserId), userForeignKey.Properties[0].Name);
Assert.Contains(navigations, navigation => navigation.Name == nameof(LibraryEntity.User));
Assert.Contains(navigations, navigation => navigation.Name == nameof(LibraryEntity.LibraryScans) && navigation.IsCollection);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.CreatedOnUtc));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditColumnOrders()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(LibraryEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(LibraryEntity.UpdatedBy));
// Assert
Assert.Equal(12, createdOnUtcProperty.GetColumnOrder());
Assert.Equal(13, createdByProperty.GetColumnOrder());
Assert.Equal(14, updatedOnUtcProperty.GetColumnOrder());
Assert.Equal(15, updatedByProperty.GetColumnOrder());
}
}
@@ -0,0 +1,91 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.DataAccess.Core.UoW;
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="LibraryMetadataProviderConfigurationConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryMetadataProviderConfigurationConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryMetadataProviderConfigurationConfigurationTests"/> class.
/// </summary>
public LibraryMetadataProviderConfigurationConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryMetadataProviderConfigurationEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("LibraryMetadataProviderConfigurations", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarPropertiesAsRequired()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryMetadataProviderConfigurationEntity))!;
// Act
IProperty libraryIdProperty = entityType.GetProperty(nameof(LibraryMetadataProviderConfigurationEntity.LibraryId));
IProperty pluginIdProperty = entityType.GetProperty(nameof(LibraryMetadataProviderConfigurationEntity.PluginId));
IProperty isEnabledProperty = entityType.GetProperty(nameof(LibraryMetadataProviderConfigurationEntity.IsEnabled));
IProperty rankProperty = entityType.GetProperty(nameof(LibraryMetadataProviderConfigurationEntity.Rank));
// Assert
Assert.False(libraryIdProperty.IsNullable);
Assert.False(pluginIdProperty.IsNullable);
Assert.False(isEnabledProperty.IsNullable);
Assert.False(rankProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureIndexOnLibraryIdAndPluginId()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryMetadataProviderConfigurationEntity))!;
// Act
IIndex index = Assert.Single(entityType.GetIndexes());
// Assert
Assert.Equal([nameof(LibraryMetadataProviderConfigurationEntity.LibraryId), nameof(LibraryMetadataProviderConfigurationEntity.PluginId)], index.Properties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryMetadataProviderConfigurationEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryMetadataProviderConfigurationEntity.CreatedOnUtc));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryMetadataProviderConfigurationEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
}
@@ -0,0 +1,107 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
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="LibraryScanConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanConfigurationTests"/> class.
/// </summary>
public LibraryScanConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("LibraryScans", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureStatusAsRequiredString()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanEntity))!;
// Act
IProperty statusProperty = entityType.GetProperty(nameof(LibraryScanEntity.Status));
// Assert
Assert.False(statusProperty.IsNullable);
Assert.Equal(typeof(LibraryScanJobStatus), statusProperty.ClrType);
Assert.Equal("TEXT", statusProperty.GetColumnType());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRelationshipsWithUserAndLibrary()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanEntity))!;
// Act
List<IForeignKey> foreignKeys = [.. entityType.GetForeignKeys()];
// Assert
Assert.Equal(2, foreignKeys.Count);
Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(LibraryEntity) && foreignKey.Properties[0].Name == nameof(LibraryScanEntity.LibraryId));
Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(UserEntity) && foreignKey.Properties[0].Name == nameof(LibraryScanEntity.UserId));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureDescendingIndexOnLibraryIdStatusAndCreatedOnUtc()
{
// Arrange
// The read-optimized runtime model does not store the index sort order, so the design-time model is inspected instead.
IDesignTimeModel designTimeModel = _context.GetService<IDesignTimeModel>();
IEntityType entityType = designTimeModel.Model.FindEntityType(typeof(LibraryScanEntity))!;
// Act
IIndex index = Assert.Single(entityType.GetIndexes(), candidate => candidate.Properties.Select(property => property.Name).SequenceEqual([nameof(LibraryScanEntity.LibraryId), nameof(LibraryScanEntity.Status), nameof(LibraryScanEntity.CreatedOnUtc)]));
// Assert
Assert.Equal([true, false, true], index.IsDescending);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryScanEntity.CreatedOnUtc));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryScanEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
}
@@ -0,0 +1,94 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
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="LibraryScanResultConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanResultConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanResultConfigurationTests"/> class.
/// </summary>
public LibraryScanResultConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndCompositeKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanResultEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("LibraryScanResults", tableName);
Assert.Equal([nameof(LibraryScanResultEntity.LibraryScanId), nameof(LibraryScanResultEntity.Path)], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanResultEntity))!;
// Act
IProperty pathProperty = entityType.GetProperty(nameof(LibraryScanResultEntity.Path));
IProperty statusProperty = entityType.GetProperty(nameof(LibraryScanResultEntity.Status));
IProperty fileSizeProperty = entityType.GetProperty(nameof(LibraryScanResultEntity.FileSize));
// Assert
Assert.False(pathProperty.IsNullable);
Assert.Equal(1024, pathProperty.GetMaxLength());
Assert.Equal(typeof(LibraryScanFileStatus), statusProperty.ClrType);
Assert.Equal("TEXT", statusProperty.GetColumnType());
Assert.Equal(10, statusProperty.GetMaxLength());
Assert.False(fileSizeProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRelationshipWithCascadeDelete()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanResultEntity))!;
// Act
IForeignKey foreignKey = Assert.Single(entityType.GetForeignKeys());
// Assert
Assert.Equal(typeof(LibraryScanEntity), foreignKey.PrincipalEntityType.ClrType);
Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior);
Assert.Equal(nameof(LibraryScanResultEntity.LibraryScanId), foreignKey.Properties[0].Name);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureIndexes()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanResultEntity))!;
// Act
List<IIndex> indexes = [.. entityType.GetIndexes()];
// Assert
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(LibraryScanResultEntity.ContentHash), nameof(LibraryScanResultEntity.FileSize), nameof(LibraryScanResultEntity.Path)]));
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(LibraryScanResultEntity.Path)]));
}
}
@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
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="LibraryScanSnapshotConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanSnapshotConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanSnapshotConfigurationTests"/> class.
/// </summary>
public LibraryScanSnapshotConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndCompositeKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanSnapshotEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("LibraryScanSnapshots", tableName);
Assert.Equal([nameof(LibraryScanSnapshotEntity.LibraryId), nameof(LibraryScanSnapshotEntity.Path)], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanSnapshotEntity))!;
// Act
IProperty pathProperty = entityType.GetProperty(nameof(LibraryScanSnapshotEntity.Path));
IProperty contentHashProperty = entityType.GetProperty(nameof(LibraryScanSnapshotEntity.ContentHash));
// Assert
Assert.False(pathProperty.IsNullable);
Assert.Equal(1024, pathProperty.GetMaxLength());
Assert.False(contentHashProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRelationshipWithCascadeDelete()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanSnapshotEntity))!;
// Act
IForeignKey foreignKey = Assert.Single(entityType.GetForeignKeys());
// Assert
Assert.Equal(typeof(LibraryEntity), foreignKey.PrincipalEntityType.ClrType);
Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior);
Assert.Equal(nameof(LibraryScanSnapshotEntity.LibraryId), foreignKey.Properties[0].Name);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureIndexOnLibraryId()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanSnapshotEntity))!;
// Act
IIndex index = Assert.Single(entityType.GetIndexes());
// Assert
Assert.Equal(nameof(LibraryScanSnapshotEntity.LibraryId), index.Properties[0].Name);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanSnapshotEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryScanSnapshotEntity.CreatedOnUtc));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryScanSnapshotEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
}
@@ -0,0 +1,90 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
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="LibraryScanStagingResultsConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanStagingResultsConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanStagingResultsConfigurationTests"/> class.
/// </summary>
public LibraryScanStagingResultsConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndCompositeKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanStagingResultsEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("LibraryScanStagingResults", tableName);
Assert.Equal([nameof(LibraryScanStagingResultsEntity.LibraryScanId), nameof(LibraryScanStagingResultsEntity.Path)], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanStagingResultsEntity))!;
// Act
IProperty pathProperty = entityType.GetProperty(nameof(LibraryScanStagingResultsEntity.Path));
IProperty needsRehashProperty = entityType.GetProperty(nameof(LibraryScanStagingResultsEntity.NeedsRehash));
IProperty isNewProperty = entityType.GetProperty(nameof(LibraryScanStagingResultsEntity.IsNew));
// Assert
Assert.False(pathProperty.IsNullable);
Assert.Equal(1024, pathProperty.GetMaxLength());
Assert.False(needsRehashProperty.IsNullable);
Assert.False(isNewProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRelationshipWithCascadeDelete()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanStagingResultsEntity))!;
// Act
IForeignKey foreignKey = Assert.Single(entityType.GetForeignKeys());
// Assert
Assert.Equal(typeof(LibraryScanEntity), foreignKey.PrincipalEntityType.ClrType);
Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior);
Assert.Equal(nameof(LibraryScanStagingResultsEntity.LibraryScanId), foreignKey.Properties[0].Name);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureIndexOnLibraryScanIdAndNeedsRehash()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanStagingResultsEntity))!;
// Act
IIndex index = Assert.Single(entityType.GetIndexes());
// Assert
Assert.Equal([nameof(LibraryScanStagingResultsEntity.LibraryScanId), nameof(LibraryScanStagingResultsEntity.NeedsRehash)], index.Properties.Select(property => property.Name));
}
}
@@ -0,0 +1,237 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
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="MediaConsumptionRecordConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaConsumptionRecordConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="MediaConsumptionRecordConfigurationTests"/> class.
/// </summary>
public MediaConsumptionRecordConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("MediaConsumptionRecords", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureCascadingRelationshipWithUser()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
// Act
IForeignKey userForeignKey = Assert.Single(entityType.GetForeignKeys());
// Assert
Assert.Equal(typeof(UserEntity), userForeignKey.PrincipalEntityType.ClrType);
Assert.Equal(nameof(MediaConsumptionRecordEntity.UserId), userForeignKey.Properties[0].Name);
Assert.Equal(DeleteBehavior.Cascade, userForeignKey.DeleteBehavior);
Assert.True(userForeignKey.IsRequired);
}
[Fact]
public void Configure_WhenApplied_ShouldStoreTheKindAndStatusAsBoundedStrings()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
// Act
IProperty mediaKindProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.MediaKind));
IProperty statusProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.Status));
// Assert
Assert.Equal(typeof(MediaKind), mediaKindProperty.ClrType);
Assert.Equal(typeof(string), mediaKindProperty.GetTypeMapping().Converter!.ProviderClrType);
Assert.Equal("TEXT", mediaKindProperty.GetColumnType());
Assert.Equal(20, mediaKindProperty.GetMaxLength());
Assert.False(mediaKindProperty.IsNullable);
Assert.Equal(typeof(ConsumptionStatus), statusProperty.ClrType);
Assert.Equal(typeof(string), statusProperty.GetTypeMapping().Converter!.ProviderClrType);
Assert.Equal("TEXT", statusProperty.GetColumnType());
Assert.Equal(20, statusProperty.GetMaxLength());
Assert.False(statusProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldStoreTheOptionalPositionKindAsABoundedString()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
// Act
IProperty lastPositionKindProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.LastPositionKind));
// Assert
Assert.Equal(typeof(MediaPositionKind?), lastPositionKindProperty.ClrType);
Assert.Equal(typeof(string), lastPositionKindProperty.GetTypeMapping().Converter!.ProviderClrType);
Assert.Equal("TEXT", lastPositionKindProperty.GetColumnType());
Assert.Equal(20, lastPositionKindProperty.GetMaxLength());
Assert.True(lastPositionKindProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheRequiredColumns()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
// Act
IProperty mediaKindProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.MediaKind));
IProperty statusProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.Status));
IProperty startedOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.StartedOnUtc));
IProperty lastActivityOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.LastActivityOnUtc));
IProperty consumedDurationMillisecondsProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.ConsumedDurationMilliseconds));
IProperty lastProgressFractionProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.LastProgressFraction));
IProperty consecutivePagesReadProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.ConsecutivePagesRead));
IProperty versionProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.Version));
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.CreatedBy));
// Assert
Assert.False(mediaKindProperty.IsNullable);
Assert.False(statusProperty.IsNullable);
Assert.False(startedOnUtcProperty.IsNullable);
Assert.False(lastActivityOnUtcProperty.IsNullable);
Assert.False(consumedDurationMillisecondsProperty.IsNullable);
Assert.False(lastProgressFractionProperty.IsNullable);
Assert.False(consecutivePagesReadProperty.IsNullable);
Assert.False(versionProperty.IsNullable);
Assert.False(createdOnUtcProperty.IsNullable);
Assert.False(createdByProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheOptionalColumns()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
// Act
IProperty endedOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.EndedOnUtc));
IProperty lastPositionKindProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.LastPositionKind));
IProperty lastPositionTimeOffsetMillisecondsProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.LastPositionTimeOffsetMilliseconds));
IProperty lastPositionLocationProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.LastPositionLocation));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.UpdatedBy));
// Assert
Assert.True(endedOnUtcProperty.IsNullable);
Assert.True(lastPositionKindProperty.IsNullable);
Assert.True(lastPositionTimeOffsetMillisecondsProperty.IsNullable);
Assert.True(lastPositionLocationProperty.IsNullable);
Assert.True(updatedOnUtcProperty.IsNullable);
Assert.True(updatedByProperty.IsNullable);
Assert.Equal(4096, lastPositionLocationProperty.GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheConsecutivePagesReadDefault()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
// Act
IProperty consecutivePagesReadProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.ConsecutivePagesRead));
// Assert
Assert.Equal(0, consecutivePagesReadProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheVersionAsAConcurrencyToken()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
// Act
IProperty versionProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.Version));
// Assert
Assert.True(versionProperty.IsConcurrencyToken);
Assert.False(versionProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheHistoryAndStatisticsIndexes()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
// Act
IIndex historyIndex = Assert.Single(
entityType.GetIndexes(),
index => index.Properties.Select(property => property.Name).SequenceEqual(
[
nameof(MediaConsumptionRecordEntity.UserId),
nameof(MediaConsumptionRecordEntity.MediaKind),
nameof(MediaConsumptionRecordEntity.MediaItemId),
nameof(MediaConsumptionRecordEntity.LastActivityOnUtc)
]));
IIndex statisticsIndex = Assert.Single(
entityType.GetIndexes(),
index => index.Properties.Select(property => property.Name).SequenceEqual(
[
nameof(MediaConsumptionRecordEntity.UserId),
nameof(MediaConsumptionRecordEntity.MediaKind),
nameof(MediaConsumptionRecordEntity.StartedOnUtc)
]));
// Assert
Assert.False(historyIndex.IsUnique);
Assert.False(statisticsIndex.IsUnique);
// The two configured indexes are distinct, and neither of them is the foreign key index on the owner.
Assert.NotSame(historyIndex, statisticsIndex);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.UpdatedBy));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.False(createdByProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
Assert.Null(updatedByProperty.GetDefaultValue());
}
}
@@ -0,0 +1,191 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
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="MediaResumePointConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaResumePointConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="MediaResumePointConfigurationTests"/> class.
/// </summary>
public MediaResumePointConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("MediaResumePoints", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureCascadingRelationshipWithUser()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
// Act
IForeignKey userForeignKey = Assert.Single(entityType.GetForeignKeys());
// Assert
Assert.Equal(typeof(UserEntity), userForeignKey.PrincipalEntityType.ClrType);
Assert.Equal(nameof(MediaResumePointEntity.UserId), userForeignKey.Properties[0].Name);
Assert.Equal(DeleteBehavior.Cascade, userForeignKey.DeleteBehavior);
Assert.True(userForeignKey.IsRequired);
}
[Fact]
public void Configure_WhenApplied_ShouldStoreTheMediaKindAsABoundedString()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
// Act
IProperty mediaKindProperty = entityType.GetProperty(nameof(MediaResumePointEntity.MediaKind));
// Assert
Assert.Equal(typeof(MediaKind), mediaKindProperty.ClrType);
Assert.Equal(typeof(string), mediaKindProperty.GetTypeMapping().Converter!.ProviderClrType);
Assert.Equal("TEXT", mediaKindProperty.GetColumnType());
Assert.Equal(20, mediaKindProperty.GetMaxLength());
Assert.False(mediaKindProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldStoreThePositionKindAsABoundedRequiredString()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
// Act
IProperty lastPositionKindProperty = entityType.GetProperty(nameof(MediaResumePointEntity.LastPositionKind));
// Assert
Assert.Equal(typeof(MediaPositionKind), lastPositionKindProperty.ClrType);
Assert.Equal(typeof(string), lastPositionKindProperty.GetTypeMapping().Converter!.ProviderClrType);
Assert.Equal("TEXT", lastPositionKindProperty.GetColumnType());
Assert.Equal(20, lastPositionKindProperty.GetMaxLength());
Assert.False(lastPositionKindProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldBoundThePositionLocationLength()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
// Act
IProperty lastPositionLocationProperty = entityType.GetProperty(nameof(MediaResumePointEntity.LastPositionLocation));
// Assert
Assert.Equal(typeof(string), lastPositionLocationProperty.ClrType);
Assert.Equal(4096, lastPositionLocationProperty.GetMaxLength());
Assert.True(lastPositionLocationProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheRequiredColumns()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
// Act
IProperty mediaKindProperty = entityType.GetProperty(nameof(MediaResumePointEntity.MediaKind));
IProperty lastPositionKindProperty = entityType.GetProperty(nameof(MediaResumePointEntity.LastPositionKind));
IProperty lastProgressFractionProperty = entityType.GetProperty(nameof(MediaResumePointEntity.LastProgressFraction));
IProperty lastConsumedOnUtcProperty = entityType.GetProperty(nameof(MediaResumePointEntity.LastConsumedOnUtc));
IProperty versionProperty = entityType.GetProperty(nameof(MediaResumePointEntity.Version));
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(MediaResumePointEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(MediaResumePointEntity.CreatedBy));
// Assert
Assert.False(mediaKindProperty.IsNullable);
Assert.False(lastPositionKindProperty.IsNullable);
Assert.False(lastProgressFractionProperty.IsNullable);
Assert.False(lastConsumedOnUtcProperty.IsNullable);
Assert.False(versionProperty.IsNullable);
Assert.False(createdOnUtcProperty.IsNullable);
Assert.False(createdByProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheVersionAsAConcurrencyToken()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
// Act
IProperty versionProperty = entityType.GetProperty(nameof(MediaResumePointEntity.Version));
// Assert
Assert.True(versionProperty.IsConcurrencyToken);
Assert.False(versionProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheUniqueBusinessKeyIndex()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
// Act
IIndex businessKeyIndex = Assert.Single(
entityType.GetIndexes(),
index => index.Properties.Select(property => property.Name).SequenceEqual(
[
nameof(MediaResumePointEntity.UserId),
nameof(MediaResumePointEntity.MediaKind),
nameof(MediaResumePointEntity.MediaItemId)
]));
// Assert
Assert.True(businessKeyIndex.IsUnique);
Assert.Equal(3, businessKeyIndex.Properties.Count);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(MediaResumePointEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(MediaResumePointEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(MediaResumePointEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(MediaResumePointEntity.UpdatedBy));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.False(createdByProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
Assert.Null(updatedByProperty.GetDefaultValue());
}
}
@@ -0,0 +1,155 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
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="MusicArtworkConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicArtworkConfigurationTests : IDisposable
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="MusicArtworkConfigurationTests"/> class.
/// </summary>
public MusicArtworkConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("MusicArtwork", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!;
// Act
IProperty idProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Id));
// Assert
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!;
// Act
IProperty ownerTypeProperty = entityType.GetProperty(nameof(MusicArtworkEntity.OwnerType));
IProperty ownerIdProperty = entityType.GetProperty(nameof(MusicArtworkEntity.OwnerId));
IProperty artworkTypeProperty = entityType.GetProperty(nameof(MusicArtworkEntity.ArtworkType));
IProperty ordinalProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Ordinal));
IProperty fileNameProperty = entityType.GetProperty(nameof(MusicArtworkEntity.FileName));
IProperty contentHashProperty = entityType.GetProperty(nameof(MusicArtworkEntity.ContentHash));
IProperty statusProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Status));
IProperty providerProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Provider));
IProperty lastUpdateUtcProperty = entityType.GetProperty(nameof(MusicArtworkEntity.LastUpdateUtc));
// Assert
Assert.False(ownerTypeProperty.IsNullable);
Assert.Equal(typeof(MusicArtworkOwnerType), ownerTypeProperty.ClrType);
Assert.Equal("TEXT", ownerTypeProperty.GetColumnType());
Assert.Equal(50, ownerTypeProperty.GetMaxLength());
Assert.False(ownerIdProperty.IsNullable);
Assert.False(artworkTypeProperty.IsNullable);
Assert.Equal(typeof(ArtworkType), artworkTypeProperty.ClrType);
Assert.Equal("TEXT", artworkTypeProperty.GetColumnType());
Assert.Equal(50, artworkTypeProperty.GetMaxLength());
Assert.False(ordinalProperty.IsNullable);
Assert.True(fileNameProperty.IsNullable);
Assert.Equal(2048, fileNameProperty.GetMaxLength());
Assert.False(contentHashProperty.IsNullable);
Assert.False(statusProperty.IsNullable);
Assert.Equal(typeof(ArtworkStatus), statusProperty.ClrType);
Assert.Equal("TEXT", statusProperty.GetColumnType());
Assert.Equal(20, statusProperty.GetMaxLength());
Assert.True(providerProperty.IsNullable);
Assert.Equal(100, providerProperty.GetMaxLength());
Assert.True(lastUpdateUtcProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureUniqueOwnerArtworkIndex()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!;
// Act
List<IIndex> indexes = [.. entityType.GetIndexes()];
// Assert
IIndex uniqueIndex = Assert.Single(indexes, index => index.IsUnique);
Assert.Equal(
[nameof(MusicArtworkEntity.OwnerType), nameof(MusicArtworkEntity.OwnerId), nameof(MusicArtworkEntity.ArtworkType), nameof(MusicArtworkEntity.Ordinal)],
uniqueIndex.Properties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureIndexOnStatus()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!;
// Act
List<IIndex> indexes = [.. entityType.GetIndexes()];
// Assert
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(MusicArtworkEntity.Status)]));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(MusicArtworkEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(MusicArtworkEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(MusicArtworkEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(MusicArtworkEntity.UpdatedBy));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.False(createdByProperty.IsNullable);
Assert.True(updatedOnUtcProperty.IsNullable);
Assert.True(updatedByProperty.IsNullable);
}
/// <summary>
/// Disposes the database context.
/// </summary>
public void Dispose()
{
_context.Dispose();
}
}
@@ -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();
}
}
@@ -0,0 +1,76 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
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="PermissionConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PermissionConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="PermissionConfigurationTests"/> class.
/// </summary>
public PermissionConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PermissionEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("Permissions", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigurePermissionNameAsRequiredString()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PermissionEntity))!;
// Act
IProperty permissionNameProperty = entityType.GetProperty(nameof(PermissionEntity.PermissionName));
// Assert
Assert.False(permissionNameProperty.IsNullable);
Assert.Equal(100, permissionNameProperty.GetMaxLength());
Assert.Equal(typeof(AuthorizationPermission), permissionNameProperty.ClrType);
Assert.Equal("TEXT", permissionNameProperty.GetColumnType());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PermissionEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PermissionEntity.CreatedOnUtc));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PermissionEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
}
@@ -0,0 +1,239 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Playlists;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
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="PlaylistConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="PlaylistConfigurationTests"/> class.
/// </summary>
public PlaylistConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
/// <summary>
/// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits.
/// </summary>
private IModel DesignTimeModel => _context.GetService<IDesignTimeModel>().Model;
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("Playlists", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldNotGenerateTheIdValueAndOrderItFirst()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(PlaylistEntity))!;
// Act
IProperty idProperty = entityType.GetProperty(nameof(PlaylistEntity.Id));
// Assert
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
Assert.Equal(0, idProperty.GetColumnOrder());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureCascadingRelationshipWithUser()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
// Act
IForeignKey userForeignKey = Assert.Single(entityType.GetForeignKeys());
// Assert
Assert.Equal(typeof(UserEntity), userForeignKey.PrincipalEntityType.ClrType);
Assert.Equal(nameof(PlaylistEntity.UserId), userForeignKey.Properties[0].Name);
Assert.Equal(DeleteBehavior.Cascade, userForeignKey.DeleteBehavior);
Assert.True(userForeignKey.IsRequired);
}
[Fact]
public void Configure_WhenApplied_ShouldStoreThePlaylistTypeAsABoundedRequiredString()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
// Act
IProperty typeProperty = entityType.GetProperty(nameof(PlaylistEntity.Type));
// Assert
Assert.Equal(typeof(PlaylistType), typeProperty.ClrType);
Assert.Equal(typeof(string), typeProperty.GetTypeMapping().Converter!.ProviderClrType);
Assert.Equal("TEXT", typeProperty.GetColumnType());
Assert.Equal(20, typeProperty.GetMaxLength());
Assert.False(typeProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheNameAndDescriptionLengths()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
// Act
IProperty nameProperty = entityType.GetProperty(nameof(PlaylistEntity.Name));
IProperty descriptionProperty = entityType.GetProperty(nameof(PlaylistEntity.Description));
// Assert
Assert.False(nameProperty.IsNullable);
Assert.Equal(255, nameProperty.GetMaxLength());
Assert.True(descriptionProperty.IsNullable);
Assert.Equal(2000, descriptionProperty.GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheRequiredColumns()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
// Act
IProperty userIdProperty = entityType.GetProperty(nameof(PlaylistEntity.UserId));
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(PlaylistEntity.CreatedBy));
IProperty entryCountProperty = entityType.GetProperty(nameof(PlaylistEntity.EntryCount));
// Assert
Assert.False(userIdProperty.IsNullable);
Assert.False(createdOnUtcProperty.IsNullable);
Assert.False(createdByProperty.IsNullable);
Assert.False(entryCountProperty.IsNullable);
Assert.Equal(0, entryCountProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheNullableAuditColumns()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
// Act
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(PlaylistEntity.UpdatedBy));
// Assert
Assert.True(updatedOnUtcProperty.IsNullable);
Assert.True(updatedByProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
Assert.Null(updatedByProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheVersionAsAConcurrencyTokenStartingAtZero()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
// Act
IProperty versionProperty = entityType.GetProperty(nameof(PlaylistEntity.Version));
// Assert
Assert.True(versionProperty.IsConcurrencyToken);
Assert.Equal(0L, versionProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheEntriesRelationshipWithCascadeDelete()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
IEntityType entryEntityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
// Act
INavigation entriesNavigation = Assert.Single(entityType.GetNavigations());
IForeignKey entriesForeignKey = Assert.Single(entryEntityType.GetForeignKeys());
// Assert
Assert.Equal(nameof(PlaylistEntity.Entries), entriesNavigation.Name);
Assert.Equal(typeof(PlaylistEntryEntity), entriesNavigation.TargetEntityType.ClrType);
Assert.True(entriesNavigation.IsCollection);
Assert.Equal(typeof(PlaylistEntity), entriesForeignKey.PrincipalEntityType.ClrType);
Assert.Equal(nameof(PlaylistEntryEntity.PlaylistId), entriesForeignKey.Properties[0].Name);
Assert.Equal(DeleteBehavior.Cascade, entriesForeignKey.DeleteBehavior);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheMostRecentActivityIndex()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
// Act
IIndex activityIndex = Assert.Single(
entityType.GetIndexes(),
index => index.Properties.Select(property => property.Name).SequenceEqual(
[
nameof(PlaylistEntity.UserId),
nameof(PlaylistEntity.UpdatedOnUtc)
]));
// Assert
Assert.False(activityIndex.IsUnique);
Assert.Equal(2, activityIndex.Properties.Count);
}
[Fact]
public void Configure_WhenApplied_ShouldOrderEveryColumnAsConfigured()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(PlaylistEntity))!;
// Act
IProperty idProperty = entityType.GetProperty(nameof(PlaylistEntity.Id));
IProperty userIdProperty = entityType.GetProperty(nameof(PlaylistEntity.UserId));
IProperty nameProperty = entityType.GetProperty(nameof(PlaylistEntity.Name));
IProperty descriptionProperty = entityType.GetProperty(nameof(PlaylistEntity.Description));
IProperty typeProperty = entityType.GetProperty(nameof(PlaylistEntity.Type));
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(PlaylistEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(PlaylistEntity.UpdatedBy));
IProperty versionProperty = entityType.GetProperty(nameof(PlaylistEntity.Version));
IProperty entryCountProperty = entityType.GetProperty(nameof(PlaylistEntity.EntryCount));
// Assert
Assert.Equal(0, idProperty.GetColumnOrder());
Assert.Equal(1, userIdProperty.GetColumnOrder());
Assert.Equal(2, nameProperty.GetColumnOrder());
Assert.Equal(3, descriptionProperty.GetColumnOrder());
Assert.Equal(4, typeProperty.GetColumnOrder());
Assert.Equal(5, createdOnUtcProperty.GetColumnOrder());
Assert.Equal(6, createdByProperty.GetColumnOrder());
Assert.Equal(7, updatedOnUtcProperty.GetColumnOrder());
Assert.Equal(8, updatedByProperty.GetColumnOrder());
Assert.Equal(9, versionProperty.GetColumnOrder());
Assert.Equal(10, entryCountProperty.GetColumnOrder());
}
}
@@ -0,0 +1,212 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Playlists;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
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="PlaylistEntryConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistEntryConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="PlaylistEntryConfigurationTests"/> class.
/// </summary>
public PlaylistEntryConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
/// <summary>
/// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits.
/// </summary>
private IModel DesignTimeModel => _context.GetService<IDesignTimeModel>().Model;
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("PlaylistEntries", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldNotGenerateTheIdValueAndOrderItFirst()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(PlaylistEntryEntity))!;
// Act
IProperty idProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.Id));
// Assert
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
Assert.Equal(0, idProperty.GetColumnOrder());
}
[Fact]
public void Configure_WhenApplied_ShouldStoreTheMediaItemTypeAsABoundedRequiredString()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
// Act
IProperty mediaItemTypeProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.MediaItemType));
// Assert
Assert.Equal(typeof(PlaylistMediaItemType), mediaItemTypeProperty.ClrType);
Assert.Equal(typeof(string), mediaItemTypeProperty.GetTypeMapping().Converter!.ProviderClrType);
Assert.Equal("TEXT", mediaItemTypeProperty.GetColumnType());
Assert.Equal(20, mediaItemTypeProperty.GetMaxLength());
Assert.False(mediaItemTypeProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheRequiredColumns()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
// Act
IProperty playlistIdProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.PlaylistId));
IProperty mediaItemIdProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.MediaItemId));
IProperty positionProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.Position));
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.CreatedBy));
// Assert
Assert.False(playlistIdProperty.IsNullable);
Assert.False(mediaItemIdProperty.IsNullable);
Assert.False(positionProperty.IsNullable);
Assert.False(createdOnUtcProperty.IsNullable);
Assert.False(createdByProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheNullableAuditColumns()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
// Act
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.UpdatedBy));
// Assert
Assert.True(updatedOnUtcProperty.IsNullable);
Assert.True(updatedByProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
Assert.Null(updatedByProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheUniquePositionIndex()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
// Act
IIndex positionIndex = Assert.Single(
entityType.GetIndexes(),
index => index.Properties.Select(property => property.Name).SequenceEqual(
[
nameof(PlaylistEntryEntity.PlaylistId),
nameof(PlaylistEntryEntity.Position)
]));
// Assert
Assert.True(positionIndex.IsUnique);
Assert.Equal(2, positionIndex.Properties.Count);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureTheMediaItemLookupIndex()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
// Act
IIndex mediaItemIndex = Assert.Single(
entityType.GetIndexes(),
index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(PlaylistEntryEntity.MediaItemId)]));
// Assert
Assert.False(mediaItemIndex.IsUnique);
}
[Fact]
public void Configure_WhenApplied_ShouldOwnTheEntryThroughThePlaylistWithCascadeDelete()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
// Act
IForeignKey playlistForeignKey = Assert.Single(entityType.GetForeignKeys());
// Assert
Assert.Equal(typeof(PlaylistEntity), playlistForeignKey.PrincipalEntityType.ClrType);
Assert.Equal(nameof(PlaylistEntryEntity.PlaylistId), playlistForeignKey.Properties[0].Name);
Assert.Equal(DeleteBehavior.Cascade, playlistForeignKey.DeleteBehavior);
}
[Fact]
public void Configure_WhenApplied_ShouldNotReferenceTheMediaItemByAForeignKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
// Act
List<IForeignKey> foreignKeys = [.. entityType.GetForeignKeys()];
// Assert
// The media item is referenced by Id only, so an entry survives the deletion of the item it references.
Assert.DoesNotContain(foreignKeys, foreignKey => foreignKey.Properties.Any(property => property.Name == nameof(PlaylistEntryEntity.MediaItemId)));
}
[Fact]
public void Configure_WhenApplied_ShouldOrderEveryColumnAsConfigured()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(PlaylistEntryEntity))!;
// Act
IProperty idProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.Id));
IProperty playlistIdProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.PlaylistId));
IProperty mediaItemIdProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.MediaItemId));
IProperty mediaItemTypeProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.MediaItemType));
IProperty positionProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.Position));
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.UpdatedBy));
// Assert
Assert.Equal(0, idProperty.GetColumnOrder());
Assert.Equal(1, playlistIdProperty.GetColumnOrder());
Assert.Equal(2, mediaItemIdProperty.GetColumnOrder());
Assert.Equal(3, mediaItemTypeProperty.GetColumnOrder());
Assert.Equal(4, positionProperty.GetColumnOrder());
Assert.Equal(5, createdOnUtcProperty.GetColumnOrder());
Assert.Equal(6, createdByProperty.GetColumnOrder());
Assert.Equal(7, updatedOnUtcProperty.GetColumnOrder());
Assert.Equal(8, updatedByProperty.GetColumnOrder());
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
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="PluginConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PluginConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="PluginConfigurationTests"/> class.
/// </summary>
public PluginConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PluginEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("Plugins", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PluginEntity))!;
// Act
IProperty nameProperty = entityType.GetProperty(nameof(PluginEntity.Name));
IProperty authorProperty = entityType.GetProperty(nameof(PluginEntity.Author));
IProperty versionProperty = entityType.GetProperty(nameof(PluginEntity.Version));
IProperty loadStatusProperty = entityType.GetProperty(nameof(PluginEntity.LoadStatus));
// Assert
Assert.False(nameProperty.IsNullable);
Assert.Equal(255, nameProperty.GetMaxLength());
Assert.False(authorProperty.IsNullable);
Assert.Equal(255, authorProperty.GetMaxLength());
Assert.False(versionProperty.IsNullable);
Assert.Equal(50, versionProperty.GetMaxLength());
Assert.Equal(typeof(PluginLoadStatus), loadStatusProperty.ClrType);
Assert.Equal("TEXT", loadStatusProperty.GetColumnType());
Assert.Equal(20, loadStatusProperty.GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(PluginEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PluginEntity.CreatedOnUtc));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PluginEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
}
@@ -0,0 +1,73 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.DataAccess.Core.UoW;
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="RoleConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RoleConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="RoleConfigurationTests"/> class.
/// </summary>
public RoleConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(RoleEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("Roles", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRoleNameAsRequired()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(RoleEntity))!;
// Act
IProperty roleNameProperty = entityType.GetProperty(nameof(RoleEntity.RoleName));
// Assert
Assert.False(roleNameProperty.IsNullable);
Assert.Equal(100, roleNameProperty.GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(RoleEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(RoleEntity.CreatedOnUtc));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(RoleEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
}
@@ -0,0 +1,85 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.DataAccess.Core.UoW;
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="RolePermissionConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RolePermissionConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="RolePermissionConfigurationTests"/> class.
/// </summary>
public RolePermissionConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndCompositeKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(RolePermissionEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("RolePermissions", tableName);
Assert.Equal([nameof(RolePermissionEntity.RoleId), nameof(RolePermissionEntity.PermissionId)], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldIgnoreTheIdProperty()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(RolePermissionEntity))!;
// Act
IProperty? idProperty = entityType.FindProperty(nameof(RolePermissionEntity.Id));
// Assert
Assert.Null(idProperty);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRelationshipsWithCascadeDelete()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(RolePermissionEntity))!;
// Act
List<IForeignKey> foreignKeys = entityType.GetForeignKeys().ToList();
// Assert
Assert.Equal(2, foreignKeys.Count);
Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(RoleEntity) && foreignKey.DeleteBehavior == DeleteBehavior.Cascade);
Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(PermissionEntity) && foreignKey.DeleteBehavior == DeleteBehavior.Cascade);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnRoleIdAndPermissionId()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(RolePermissionEntity))!;
// Act
IIndex index = Assert.Single(entityType.GetIndexes(), candidate => candidate.Properties.Select(property => property.Name).SequenceEqual([nameof(RolePermissionEntity.RoleId), nameof(RolePermissionEntity.PermissionId)]));
// Assert
Assert.True(index.IsUnique);
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.DataAccess.Core.UoW;
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="TagConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TagConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="TagConfigurationTests"/> class.
/// </summary>
public TagConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TagEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("Tags", tableName);
Assert.Equal([nameof(TagEntity.Name)], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureNameAsRequired()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TagEntity))!;
// Act
IProperty nameProperty = entityType.GetProperty(nameof(TagEntity.Name));
// Assert
Assert.False(nameProperty.IsNullable);
Assert.Equal(50, nameProperty.GetMaxLength());
}
}
@@ -0,0 +1,183 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
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="TrackConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TrackConfigurationTests : IDisposable
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="TrackConfigurationTests"/> class.
/// </summary>
public TrackConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("Tracks", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
// Act
IProperty idProperty = entityType.GetProperty(nameof(TrackEntity.Id));
// Assert
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
// Act
IProperty pathProperty = entityType.GetProperty(nameof(TrackEntity.Path));
IProperty titleProperty = entityType.GetProperty(nameof(TrackEntity.Title));
IProperty originalTitleProperty = entityType.GetProperty(nameof(TrackEntity.OriginalTitle));
IProperty descriptionProperty = entityType.GetProperty(nameof(TrackEntity.Description));
IProperty releaseCountryProperty = entityType.GetProperty(nameof(TrackEntity.ReleaseCountry));
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.WorkTitle));
// Assert
Assert.False(pathProperty.IsNullable);
Assert.Equal(2048, pathProperty.GetMaxLength());
Assert.False(titleProperty.IsNullable);
Assert.Equal(255, titleProperty.GetMaxLength());
Assert.Equal(255, originalTitleProperty.GetMaxLength());
Assert.Equal(2000, descriptionProperty.GetMaxLength());
Assert.Equal(typeof(ReleaseCountry?), releaseCountryProperty.ClrType);
Assert.Equal("TEXT", releaseCountryProperty.GetColumnType());
Assert.Equal(2, releaseCountryProperty.GetMaxLength());
Assert.Equal(50, scriptProperty.GetMaxLength());
Assert.Equal(typeof(MusicKey?), keyProperty.ClrType);
Assert.Equal("TEXT", keyProperty.GetColumnType());
Assert.Equal(50, keyProperty.GetMaxLength());
Assert.Equal(50, audioCodecProperty.GetMaxLength());
Assert.Equal(255, workProperty.GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAlbumRelationshipWithCascadeDelete()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
// Act
List<IForeignKey> foreignKeys = [.. entityType.GetForeignKeys()];
// Assert
IForeignKey albumForeignKey = Assert.Single(foreignKeys);
Assert.Equal(nameof(TrackEntity.AlbumId), albumForeignKey.Properties.Single().Name);
Assert.Equal(typeof(AlbumEntity), albumForeignKey.PrincipalEntityType.ClrType);
Assert.Equal(DeleteBehavior.Cascade, albumForeignKey.DeleteBehavior);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOwnedTypesForMoodsIsrcsAndRatings()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
// Act
List<IEntityType> ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)];
// Assert
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");
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureManyToManyJoinTablesForTagsAndGenres()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
// Act
List<ISkipNavigation> skipNavigations = [.. entityType.GetSkipNavigations()];
// Assert
Assert.Equal(2, skipNavigations.Count);
Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(TrackEntity.Tags) && navigation.JoinEntityType.GetTableName() == "TrackTags");
Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(TrackEntity.Genres) && navigation.JoinEntityType.GetTableName() == "TrackGenres");
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureIndexesOnAlbumIdTrackNumberAndLibraryIdPath()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
// Act
List<IIndex> indexes = [.. entityType.GetIndexes()];
// Assert
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackEntity.AlbumId), nameof(TrackEntity.TrackNumber)]));
IIndex pathIndex = Assert.Single(indexes.Where(index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackEntity.LibraryId), nameof(TrackEntity.Path)])));
Assert.True(pathIndex.IsUnique);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(TrackEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(TrackEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(TrackEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.False(createdByProperty.IsNullable);
Assert.True(updatedOnUtcProperty.IsNullable);
}
/// <summary>
/// Disposes the database context.
/// </summary>
public void Dispose()
{
_context.Dispose();
}
}
@@ -0,0 +1,118 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
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="TrackContributorConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TrackContributorConfigurationTests : IDisposable
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="TrackContributorConfigurationTests"/> class.
/// </summary>
public TrackContributorConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("TrackContributors", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
// Act
IProperty idProperty = entityType.GetProperty(nameof(TrackContributorEntity.Id));
// Assert
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
// Act
IProperty trackIdProperty = entityType.GetProperty(nameof(TrackContributorEntity.TrackId));
IProperty mediaContributorIdProperty = entityType.GetProperty(nameof(TrackContributorEntity.MediaContributorId));
IProperty roleProperty = entityType.GetProperty(nameof(TrackContributorEntity.Role));
// Assert
Assert.False(trackIdProperty.IsNullable);
Assert.False(mediaContributorIdProperty.IsNullable);
Assert.False(roleProperty.IsNullable);
Assert.Equal(typeof(MediaContributorRole), roleProperty.ClrType);
Assert.Equal("TEXT", roleProperty.GetColumnType());
Assert.Equal(50, roleProperty.GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureUniqueIndexAndContributorLookupIndex()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
// Act
List<IIndex> indexes = [.. entityType.GetIndexes()];
// Assert
IIndex uniquenessIndex = Assert.Single(indexes.Where(index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackContributorEntity.TrackId), nameof(TrackContributorEntity.MediaContributorId), nameof(TrackContributorEntity.Role)])));
Assert.True(uniquenessIndex.IsUnique);
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackContributorEntity.MediaContributorId)]));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(TrackContributorEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(TrackContributorEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(TrackContributorEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.False(createdByProperty.IsNullable);
Assert.True(updatedOnUtcProperty.IsNullable);
}
/// <summary>
/// Disposes the database context.
/// </summary>
public void Dispose()
{
_context.Dispose();
}
}
@@ -0,0 +1,115 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
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="UserConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="UserConfigurationTests"/> class.
/// </summary>
public UserConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("Users", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserEntity))!;
// Act
IProperty usernameProperty = entityType.GetProperty(nameof(UserEntity.Username));
IProperty passwordProperty = entityType.GetProperty(nameof(UserEntity.Password));
IProperty tempPasswordProperty = entityType.GetProperty(nameof(UserEntity.TempPassword));
IProperty totpSecretProperty = entityType.GetProperty(nameof(UserEntity.TotpSecret));
// Assert
Assert.False(usernameProperty.IsNullable);
Assert.Equal(255, usernameProperty.GetMaxLength());
Assert.False(passwordProperty.IsNullable);
Assert.Null(tempPasswordProperty.GetDefaultValue());
Assert.Null(totpSecretProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRelationshipsWithCascadeDelete()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserEntity))!;
// Act
List<INavigation> navigations = entityType.GetNavigations().ToList();
List<IForeignKey> referencingForeignKeys = entityType.GetReferencingForeignKeys().ToList();
// Assert
Assert.Contains(navigations, navigation => navigation.Name == nameof(UserEntity.Libraries) && navigation.IsCollection);
Assert.Contains(navigations, navigation => navigation.Name == nameof(UserEntity.UserRole) && !navigation.IsCollection);
Assert.Contains(navigations, navigation => navigation.Name == nameof(UserEntity.UserPermissions) && navigation.IsCollection);
Assert.All(referencingForeignKeys, foreignKey => Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnUsername()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserEntity))!;
// Act
IIndex? usernameIndex = entityType.GetIndexes().SingleOrDefault(index => index.Properties.Any(property => property.Name == nameof(UserEntity.Username)));
// Assert
Assert.NotNull(usernameIndex);
Assert.True(usernameIndex!.IsUnique);
Assert.Equal(nameof(UserEntity.Username), usernameIndex.Properties[0].Name);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(UserEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(UserEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(UserEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(UserEntity.UpdatedBy));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.False(createdByProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
Assert.Null(updatedByProperty.GetDefaultValue());
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
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="UserPermissionConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserPermissionConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="UserPermissionConfigurationTests"/> class.
/// </summary>
public UserPermissionConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndCompositeKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserPermissionEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("UserPermissions", tableName);
Assert.Equal([nameof(UserPermissionEntity.UserId), nameof(UserPermissionEntity.PermissionId)], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldIgnoreTheIdProperty()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserPermissionEntity))!;
// Act
IProperty? idProperty = entityType.FindProperty(nameof(UserPermissionEntity.Id));
// Assert
Assert.Null(idProperty);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRelationshipsWithCascadeDelete()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserPermissionEntity))!;
// Act
List<IForeignKey> foreignKeys = [.. entityType.GetForeignKeys()];
// Assert
Assert.Equal(2, foreignKeys.Count);
Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(UserEntity) && foreignKey.DeleteBehavior == DeleteBehavior.Cascade);
Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(PermissionEntity) && foreignKey.DeleteBehavior == DeleteBehavior.Cascade);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnUserIdAndPermissionId()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserPermissionEntity))!;
// Act
IIndex index = Assert.Single(entityType.GetIndexes(), candidate => candidate.Properties.Select(property => property.Name).SequenceEqual([nameof(UserPermissionEntity.UserId), nameof(UserPermissionEntity.PermissionId)]));
// Assert
Assert.True(index.IsUnique);
}
}
@@ -0,0 +1,101 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
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="UserRoleConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserRoleConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="UserRoleConfigurationTests"/> class.
/// </summary>
public UserRoleConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserRoleEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("UserRoles", tableName);
Assert.Equal([nameof(UserRoleEntity.UserId)], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldIgnoreTheIdProperty()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserRoleEntity))!;
// Act
IProperty? idProperty = entityType.FindProperty(nameof(UserRoleEntity.Id));
// Assert
Assert.Null(idProperty);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRelationshipsWithCascadeDelete()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserRoleEntity))!;
// Act
List<IForeignKey> foreignKeys = [.. entityType.GetForeignKeys()];
// Assert
Assert.Equal(2, foreignKeys.Count);
Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(UserEntity) && foreignKey.DeleteBehavior == DeleteBehavior.Cascade);
Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(RoleEntity) && foreignKey.DeleteBehavior == DeleteBehavior.Cascade);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnUserIdAndRoleId()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserRoleEntity))!;
// Act
IIndex index = Assert.Single(entityType.GetIndexes(), candidate => candidate.Properties.Select(property => property.Name).SequenceEqual([nameof(UserRoleEntity.UserId), nameof(UserRoleEntity.RoleId)]));
// Assert
Assert.True(index.IsUnique);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserRoleEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(UserRoleEntity.CreatedOnUtc));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(UserRoleEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
}
@@ -0,0 +1,164 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
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="UserSettingsConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserSettingsConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="UserSettingsConfigurationTests"/> class.
/// </summary>
public UserSettingsConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
/// <summary>
/// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits.
/// </summary>
private IModel DesignTimeModel => _context.GetService<IDesignTimeModel>().Model;
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("UserSettings", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarPropertiesAsRequired()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!;
// Act
IProperty userIdProperty = entityType.GetProperty(nameof(UserSettingsEntity.UserId));
IProperty isPaginationEnabledProperty = entityType.GetProperty(nameof(UserSettingsEntity.IsPaginationEnabled));
IProperty itemsPerPageProperty = entityType.GetProperty(nameof(UserSettingsEntity.ItemsPerPage));
IProperty ignoreThePrefixProperty = entityType.GetProperty(nameof(UserSettingsEntity.ShouldIgnoreThePrefixForAlphaPicker));
IProperty vuMeterOrientationProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterOrientation));
IProperty vuMeterSegmentCountProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterSegmentCount));
IProperty vuMeterSegmentGapProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterSegmentGap));
IProperty vuMeterMediumThresholdProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterMediumThreshold));
IProperty vuMeterHighThresholdProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterHighThreshold));
IProperty vuMeterShowPeakProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterShowPeak));
IProperty vuMeterPeakHoldDurationProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterPeakHoldDurationInMilliseconds));
IProperty vuMeterReleasePerSecondProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterReleasePerSecond));
IProperty vuMeterPeakReleasePerSecondProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterPeakReleasePerSecond));
// Assert
Assert.False(userIdProperty.IsNullable);
Assert.False(isPaginationEnabledProperty.IsNullable);
Assert.False(itemsPerPageProperty.IsNullable);
Assert.False(ignoreThePrefixProperty.IsNullable);
Assert.False(vuMeterOrientationProperty.IsNullable);
Assert.False(vuMeterSegmentCountProperty.IsNullable);
Assert.False(vuMeterSegmentGapProperty.IsNullable);
Assert.False(vuMeterMediumThresholdProperty.IsNullable);
Assert.False(vuMeterHighThresholdProperty.IsNullable);
Assert.False(vuMeterShowPeakProperty.IsNullable);
Assert.False(vuMeterPeakHoldDurationProperty.IsNullable);
Assert.False(vuMeterReleasePerSecondProperty.IsNullable);
Assert.False(vuMeterPeakReleasePerSecondProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOneToOneRelationshipWithUser()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!;
// Act
IForeignKey foreignKey = Assert.Single(entityType.GetForeignKeys());
// Assert
Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior);
Assert.Equal(typeof(UserEntity), foreignKey.PrincipalEntityType.ClrType);
Assert.Equal(nameof(UserSettingsEntity.UserId), foreignKey.Properties[0].Name);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnUserId()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!;
// Act
IIndex userIdIndex = Assert.Single(entityType.GetIndexes());
// Assert
Assert.True(userIdIndex.IsUnique);
Assert.Equal(nameof(UserSettingsEntity.UserId), userIdIndex.Properties[0].Name);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(UserSettingsEntity.CreatedOnUtc));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(UserSettingsEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureVuMeterAndPlaybackStateColumnOrders()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(UserSettingsEntity))!;
// Act
IProperty vuMeterOrientationProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterOrientation));
IProperty vuMeterSegmentCountProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterSegmentCount));
IProperty vuMeterSegmentGapProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterSegmentGap));
IProperty vuMeterMediumThresholdProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterMediumThreshold));
IProperty vuMeterHighThresholdProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterHighThreshold));
IProperty vuMeterShowPeakProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterShowPeak));
IProperty vuMeterPeakHoldDurationProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterPeakHoldDurationInMilliseconds));
IProperty vuMeterReleasePerSecondProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterReleasePerSecond));
IProperty vuMeterPeakReleasePerSecondProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterPeakReleasePerSecond));
IProperty volumeProperty = entityType.GetProperty(nameof(UserSettingsEntity.Volume));
IProperty isMutedProperty = entityType.GetProperty(nameof(UserSettingsEntity.IsMuted));
// Assert
Assert.Equal(19, vuMeterOrientationProperty.GetColumnOrder());
Assert.Equal(20, vuMeterSegmentCountProperty.GetColumnOrder());
Assert.Equal(21, vuMeterSegmentGapProperty.GetColumnOrder());
Assert.Equal(22, vuMeterMediumThresholdProperty.GetColumnOrder());
Assert.Equal(23, vuMeterHighThresholdProperty.GetColumnOrder());
Assert.Equal(24, vuMeterShowPeakProperty.GetColumnOrder());
Assert.Equal(25, vuMeterPeakHoldDurationProperty.GetColumnOrder());
Assert.Equal(26, vuMeterReleasePerSecondProperty.GetColumnOrder());
Assert.Equal(27, vuMeterPeakReleasePerSecondProperty.GetColumnOrder());
Assert.Equal(28, volumeProperty.GetColumnOrder());
Assert.Equal(29, isMutedProperty.GetColumnOrder());
}
}
@@ -0,0 +1,81 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Common.Dapper;
using NSubstitute;
using System;
using System.Data;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Dapper;
/// <summary>
/// Contains unit tests for the <see cref="SqliteGuidTypeHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SqliteGuidTypeHandlerTests
{
private readonly SqliteGuidTypeHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="SqliteGuidTypeHandlerTests"/> class.
/// </summary>
public SqliteGuidTypeHandlerTests()
{
_sut = new SqliteGuidTypeHandler();
}
[Fact]
public void SetValue_WhenCalled_ShouldStoreTheGuidAsItsUpperCaseTextRepresentation()
{
// Arrange
IDbDataParameter parameter = Substitute.For<IDbDataParameter>();
Guid guid = Guid.NewGuid();
// Act
_sut.SetValue(parameter, guid);
// Assert
Assert.Equal(guid.ToString().ToUpperInvariant(), (string?)parameter.Value);
}
[Fact]
public void Parse_WhenValueIsGuid_ShouldReturnTheSameGuid()
{
// Arrange
Guid guid = Guid.NewGuid();
object value = guid;
// Act
Guid parsed = _sut.Parse(value);
// Assert
Assert.Equal(guid, parsed);
}
[Fact]
public void Parse_WhenValueIsGuidText_ShouldReturnTheParsedGuid()
{
// Arrange
Guid guid = Guid.NewGuid();
object value = guid.ToString();
// Act
Guid parsed = _sut.Parse(value);
// Assert
Assert.Equal(guid, parsed);
}
[Fact]
public void Parse_WhenValueIsNotValidGuidText_ShouldThrowFormatException()
{
// Arrange
object value = "not-a-guid";
// Act
Action act = () => _sut.Parse(value);
// Assert
Assert.Throws<FormatException>(act);
}
}
@@ -0,0 +1,78 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.DataAccess.Common.DependencyInjection;
using Lumina.DataAccess.Core.UoW;
using Lumina.DataAccess.UnitTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.DependencyInjection;
/// <summary>
/// Contains unit tests for the <see cref="DataAccessLayerServices"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DataAccessLayerServicesTests
{
[Fact]
public void AddDataAccessLayerServices_WhenBasePathExists_ShouldAddServices()
{
// Arrange
ServiceCollection services = new();
string basePath = Path.GetTempPath(); // Use a real existing path.
// Act
DataAccessLayerServices.AddDataAccessLayerServices(services);
// Assert
Assert.Contains(services, sd => sd.ServiceType == typeof(LuminaDbContext));
Assert.Contains(services, sd => sd.ServiceType == typeof(IUnitOfWork) && sd.ImplementationType == typeof(UnitOfWork));
}
[Fact]
public void AddDataAccessLayerServices_ShouldRegisterDbContextWithCorrectConnectionString()
{
// Arrange
ServiceCollection services = new();
// Act
DataAccessLayerServices.AddDataAccessLayerServices(services);
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
// Assert
ServiceDescriptor? descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
Assert.NotNull(descriptor);
ServiceProvider serviceProvider = services.BuildServiceProvider();
LuminaDbContext? context = serviceProvider.GetService<LuminaDbContext>();
Assert.NotNull(context);
Assert.Contains("Lumina.db", context.Database.GetDbConnection().ConnectionString);
}
[Fact]
public void AddDataAccessLayerServices_WhenCalled_ShouldExposeRepositoriesThroughUnitOfWork()
{
// Arrange
ServiceCollection services = new();
// Act
DataAccessLayerServices.AddDataAccessLayerServices(services);
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert
IUnitOfWork unitOfWork = serviceProvider.GetRequiredService<IUnitOfWork>();
Assert.NotNull(unitOfWork.BookRepository);
Assert.NotNull(unitOfWork.PermissionRepository);
}
}
@@ -0,0 +1,176 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Common.Interceptors;
using Lumina.DataAccess.Core.UoW;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Interceptors;
/// <summary>
/// Contains unit tests for the <see cref="UpdateAuditableEntitiesInterceptor"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateAuditableEntitiesInterceptorTests
{
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly UpdateAuditableEntitiesInterceptor _sut;
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryScanResultEntityFixture _libraryScanResultEntityFixture = new();
private readonly Guid _userId;
private readonly DateTime _fixedUtcNow;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAuditableEntitiesInterceptorTests"/> class.
/// </summary>
public UpdateAuditableEntitiesInterceptorTests()
{
_userId = Guid.NewGuid();
_fixedUtcNow = new DateTime(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc);
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockCurrentUserService.UserId.Returns(_userId);
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
_sut = new UpdateAuditableEntitiesInterceptor(_mockCurrentUserService, _mockDateTimeProvider);
}
[Fact]
public async Task SavingChangesAsync_WhenAddingAuditableEntity_ShouldSetCreationProperties()
{
// Arrange
LuminaDbContext context = CreateContext();
BookEntity book = _bookEntityFixture.Create();
// Act
context.Books.Add(book);
await context.SaveChangesAsync();
// Assert
Assert.Equal(_fixedUtcNow, book.CreatedOnUtc);
Assert.Equal(_userId, book.CreatedBy);
Assert.Null(book.UpdatedOnUtc);
Assert.Null(book.UpdatedBy);
}
[Fact]
public async Task SavingChangesAsync_WhenModifyingAuditableEntity_ShouldSetModificationProperties()
{
// Arrange
LuminaDbContext context = CreateContext();
BookEntity book = _bookEntityFixture.Create();
context.Books.Add(book);
await context.SaveChangesAsync();
// Act
book.Title = "Updated Title";
await context.SaveChangesAsync();
// Assert
Assert.Equal(_fixedUtcNow, book.UpdatedOnUtc);
Assert.Equal(_userId, book.UpdatedBy);
Assert.Equal(_fixedUtcNow, book.CreatedOnUtc);
Assert.Equal(_userId, book.CreatedBy);
}
[Fact]
public async Task SavingChangesAsync_WhenNoUserIsAuthenticated_ShouldLeaveCreationAndModificationUnattributed()
{
// Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null);
LuminaDbContext context = CreateContext();
BookEntity book = _bookEntityFixture.Create();
context.Books.Add(book);
await context.SaveChangesAsync();
// Act
book.Title = "Updated Title";
await context.SaveChangesAsync();
// Assert
Assert.Equal(Guid.Empty, book.CreatedBy);
Assert.Equal(Guid.Empty, book.UpdatedBy);
Assert.Equal(_fixedUtcNow, book.UpdatedOnUtc);
}
[Fact]
public async Task SavingChangesAsync_WhenInitializationSave_ShouldPreserveTheExplicitAuditValues()
{
// Arrange
LuminaDbContext context = CreateContext();
BookEntity book = _bookEntityFixture.Create();
DateTime initializationUtcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
book.CreatedOnUtc = initializationUtcNow;
book.CreatedBy = AuditIdentities.s_systemUserId;
book.UpdatedOnUtc = null;
book.UpdatedBy = null;
// Act
context.IsInitializationSave = true;
context.Books.Add(book);
await context.SaveChangesAsync();
context.IsInitializationSave = false;
// Assert
Assert.Equal(initializationUtcNow, book.CreatedOnUtc);
Assert.Equal(AuditIdentities.s_systemUserId, book.CreatedBy);
Assert.Null(book.UpdatedOnUtc);
Assert.Null(book.UpdatedBy);
}
[Fact]
public void SavingChanges_WhenAddingAuditableEntity_ShouldSetCreationProperties()
{
// Arrange
LuminaDbContext context = CreateContext();
BookEntity book = _bookEntityFixture.Create();
// Act
context.Books.Add(book);
context.SaveChanges();
// Assert
Assert.Equal(_fixedUtcNow, book.CreatedOnUtc);
Assert.Equal(_userId, book.CreatedBy);
Assert.Null(book.UpdatedOnUtc);
Assert.Null(book.UpdatedBy);
}
[Fact]
public async Task SavingChangesAsync_WhenTrackingNonAuditableEntity_ShouldNotThrow()
{
// Arrange
LuminaDbContext context = CreateContext();
LibraryScanResultEntity scanResult = _libraryScanResultEntityFixture.Create();
// Act
context.LibraryScanResults.Add(scanResult);
await context.SaveChangesAsync();
// Assert
Assert.Equal(EntityState.Unchanged, context.Entry(scanResult).State);
}
/// <summary>
/// Creates a <see cref="LuminaDbContext"/> that uses the interceptor under test.
/// </summary>
/// <returns>A configured <see cref="LuminaDbContext"/> instance.</returns>
private LuminaDbContext CreateContext()
{
DbContextOptions<LuminaDbContext> options = new DbContextOptionsBuilder<LuminaDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.AddInterceptors(_sut)
.Options;
return new LuminaDbContext(options);
}
}
@@ -0,0 +1,289 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Common.Persistence;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Persistence;
/// <summary>
/// Contains unit tests for the <see cref="CollectionReconciler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CollectionReconcilerTests
{
private readonly TagEntityFixture _tagEntityFixture = new();
private readonly IsbnEntityFixture _isbnEntityFixture = new();
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
[Fact]
public void Reconcile_WhenAnItemIsNew_ShouldAddItToTheTrackedCollection()
{
// Arrange
List<TagEntity> trackedTags = [];
List<TagEntity> incomingTags = [_tagEntityFixture.Create(name: "jazz")];
// Act
CollectionReconciler.Reconcile(
trackedTags,
incomingTags,
trackedTag => trackedTag.Name!,
incomingTag => incomingTag.Name!,
shouldReplace: (trackedTag, incomingTag) => false,
createNew: incomingTag => incomingTag);
// Assert
TagEntity addedTag = Assert.Single(trackedTags);
Assert.Same(incomingTags[0], addedTag);
}
[Fact]
public void Reconcile_WhenATrackedItemIsAbsentFromTheIncomingSet_ShouldRemoveIt()
{
// Arrange
TagEntity removedTag = _tagEntityFixture.Create(name: "rock");
TagEntity keptTag = _tagEntityFixture.Create(name: "jazz");
List<TagEntity> trackedTags = [removedTag, keptTag];
List<TagEntity> incomingTags = [_tagEntityFixture.Create(name: "jazz")];
// Act
CollectionReconciler.Reconcile(
trackedTags,
incomingTags,
trackedTag => trackedTag.Name!,
incomingTag => incomingTag.Name!,
shouldReplace: (trackedTag, incomingTag) => false,
createNew: incomingTag => incomingTag);
// Assert
TagEntity keptTrackedTag = Assert.Single(trackedTags);
Assert.Same(keptTag, keptTrackedTag);
Assert.DoesNotContain(removedTag, trackedTags);
}
[Fact]
public void Reconcile_WhenAMatchedItemDidNotChange_ShouldKeepTheSameTrackedInstance()
{
// Arrange
TagEntity trackedTag = _tagEntityFixture.Create(name: "rock");
List<TagEntity> trackedTags = [trackedTag];
List<TagEntity> incomingTags = [_tagEntityFixture.Create(name: "rock")];
// Act
CollectionReconciler.Reconcile(
trackedTags,
incomingTags,
existingTag => existingTag.Name!,
incomingTag => incomingTag.Name!,
shouldReplace: (existingTag, incomingTag) => false,
createNew: incomingTag => incomingTag);
// Assert
TagEntity keptTrackedTag = Assert.Single(trackedTags);
Assert.Same(trackedTag, keptTrackedTag);
}
[Fact]
public void Reconcile_WhenAMatchedItemChanged_ShouldReplaceOnlyThatItem()
{
// Arrange
IsbnEntity trackedIsbn = _isbnEntityFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn10);
IsbnEntity unchangedIsbn = _isbnEntityFixture.Create(value: "978-0-306-40615-7", format: IsbnFormat.Isbn13);
List<IsbnEntity> trackedIsbns = [trackedIsbn, unchangedIsbn];
IsbnEntity incomingChangedIsbn = _isbnEntityFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13);
IsbnEntity incomingUnchangedIsbn = _isbnEntityFixture.Create(value: "978-0-306-40615-7", format: IsbnFormat.Isbn13);
List<IsbnEntity> incomingIsbns = [incomingChangedIsbn, incomingUnchangedIsbn];
// Act
CollectionReconciler.Reconcile(
trackedIsbns,
incomingIsbns,
existingIsbn => existingIsbn.Value!,
incomingIsbn => incomingIsbn.Value!,
shouldReplace: (existingIsbn, incomingIsbn) => !existingIsbn.Equals(incomingIsbn),
createNew: incomingIsbn => incomingIsbn);
// Assert
Assert.Equal(2, trackedIsbns.Count);
Assert.DoesNotContain(trackedIsbn, trackedIsbns);
Assert.Contains(incomingChangedIsbn, trackedIsbns);
IsbnEntity keptIsbn = trackedIsbns.Single(isbn => isbn.Value == unchangedIsbn.Value);
Assert.Same(unchangedIsbn, keptIsbn);
}
[Fact]
public void Reconcile_WhenSeveralChangesAreRequested_ShouldApplyAddRemoveAndKeepInASinglePass()
{
// Arrange
BookContributorEntity removedContributor = _bookContributorEntityFixture.Create(role: MediaContributorRole.Author);
BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(role: MediaContributorRole.Illustrator);
List<BookContributorEntity> trackedContributors = [removedContributor, keptContributor];
BookContributorEntity incomingKeptContributor = _bookContributorEntityFixture.Create(
bookId: keptContributor.BookId,
mediaContributorId: keptContributor.MediaContributorId,
role: keptContributor.Role);
BookContributorEntity incomingNewContributor = _bookContributorEntityFixture.Create(role: MediaContributorRole.Translator);
List<BookContributorEntity> incomingContributors = [incomingKeptContributor, incomingNewContributor];
// Act
CollectionReconciler.Reconcile(
trackedContributors,
incomingContributors,
existingContributor => (existingContributor.MediaContributorId, existingContributor.Role),
incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role),
shouldReplace: (existingContributor, incomingContributor) => false,
createNew: incomingContributor => incomingContributor);
// Assert
Assert.Equal(2, trackedContributors.Count);
Assert.DoesNotContain(removedContributor, trackedContributors);
Assert.Same(keptContributor, trackedContributors.Single(contributor => contributor.MediaContributorId == keptContributor.MediaContributorId));
Assert.Same(incomingNewContributor, trackedContributors.Single(contributor => contributor.MediaContributorId == incomingNewContributor.MediaContributorId));
}
[Fact]
public void Reconcile_WhenTheIncomingSetIsEmpty_ShouldRemoveEveryTrackedItem()
{
// Arrange
List<TagEntity> trackedTags = [_tagEntityFixture.Create(name: "rock"), _tagEntityFixture.Create(name: "jazz")];
List<TagEntity> incomingTags = [];
// Act
CollectionReconciler.Reconcile(
trackedTags,
incomingTags,
trackedTag => trackedTag.Name!,
incomingTag => incomingTag.Name!,
shouldReplace: (trackedTag, incomingTag) => false,
createNew: incomingTag => incomingTag);
// Assert
Assert.Empty(trackedTags);
}
[Fact]
public void Reconcile_WhenTheTrackedCollectionIsEmpty_ShouldAddEveryIncomingItem()
{
// Arrange
List<TagEntity> trackedTags = [];
List<TagEntity> incomingTags = [_tagEntityFixture.Create(name: "rock"), _tagEntityFixture.Create(name: "jazz")];
// Act
CollectionReconciler.Reconcile(
trackedTags,
incomingTags,
trackedTag => trackedTag.Name!,
incomingTag => incomingTag.Name!,
shouldReplace: (trackedTag, incomingTag) => false,
createNew: incomingTag => incomingTag);
// Assert
Assert.Equal(2, trackedTags.Count);
Assert.Same(incomingTags[0], trackedTags.Single(tag => tag.Name == "rock"));
Assert.Same(incomingTags[1], trackedTags.Single(tag => tag.Name == "jazz"));
}
[Fact]
public void Reconcile_WhenTheTrackedCollectionHasDuplicateKeys_ShouldMatchTheFirstTrackedInstance()
{
// Arrange
TagEntity firstTrackedTag = _tagEntityFixture.Create(name: "rock");
TagEntity secondTrackedTag = _tagEntityFixture.Create(name: "rock");
List<TagEntity> trackedTags = [firstTrackedTag, secondTrackedTag];
List<TagEntity> incomingTags = [_tagEntityFixture.Create(name: "rock")];
// Act
CollectionReconciler.Reconcile(
trackedTags,
incomingTags,
trackedTag => trackedTag.Name!,
incomingTag => incomingTag.Name!,
shouldReplace: (trackedTag, incomingTag) => false,
createNew: incomingTag => incomingTag);
// Assert
Assert.Equal(2, trackedTags.Count);
Assert.Same(firstTrackedTag, trackedTags[0]);
Assert.Same(secondTrackedTag, trackedTags[1]);
}
[Fact]
public void Reconcile_WhenTheIncomingCollectionHasDuplicateNewKeys_ShouldAddOnlyOneItem()
{
// Arrange
List<TagEntity> trackedTags = [];
TagEntity firstIncomingTag = _tagEntityFixture.Create(name: "rock");
TagEntity secondIncomingTag = _tagEntityFixture.Create(name: "rock");
List<TagEntity> incomingTags = [firstIncomingTag, secondIncomingTag];
// Act
CollectionReconciler.Reconcile(
trackedTags,
incomingTags,
trackedTag => trackedTag.Name!,
incomingTag => incomingTag.Name!,
shouldReplace: (trackedTag, incomingTag) => false,
createNew: incomingTag => incomingTag);
// Assert
TagEntity addedTag = Assert.Single(trackedTags);
Assert.Same(firstIncomingTag, addedTag);
}
[Fact]
public void Reconcile_WhenAReplacedItemIsRematchedByALaterIncomingItem_ShouldReuseTheReplacement()
{
// Arrange
TagEntity trackedTag = _tagEntityFixture.Create(name: "rock");
List<TagEntity> trackedTags = [trackedTag];
TagEntity firstIncomingTag = _tagEntityFixture.Create(name: "rock");
TagEntity secondIncomingTag = _tagEntityFixture.Create(name: "rock");
List<TagEntity> incomingTags = [firstIncomingTag, secondIncomingTag];
// Act
CollectionReconciler.Reconcile(
trackedTags,
incomingTags,
existingTag => existingTag.Name!,
incomingTag => incomingTag.Name!,
shouldReplace: (existingTag, incomingTag) => !ReferenceEquals(existingTag, incomingTag),
createNew: incomingTag => incomingTag);
// Assert
TagEntity replacedTag = Assert.Single(trackedTags);
Assert.Same(secondIncomingTag, replacedTag);
Assert.DoesNotContain(trackedTags, trackedItem => ReferenceEquals(trackedItem, firstIncomingTag));
}
[Fact]
public void Reconcile_WhenANewItemIsAddedAndALaterIncomingItemReplacesIt_ShouldKeepASingleItem()
{
// Arrange
List<TagEntity> trackedTags = [];
TagEntity firstIncomingTag = _tagEntityFixture.Create(name: "rock");
TagEntity secondIncomingTag = _tagEntityFixture.Create(name: "rock");
List<TagEntity> incomingTags = [firstIncomingTag, secondIncomingTag];
// Act
CollectionReconciler.Reconcile(
trackedTags,
incomingTags,
trackedTag => trackedTag.Name!,
incomingTag => incomingTag.Name!,
shouldReplace: (trackedTag, incomingTag) => !ReferenceEquals(trackedTag, incomingTag),
createNew: incomingTag => incomingTag);
// Assert
// The item added for the first occurrence is indexed, so the second occurrence matches it instead of adding a duplicate.
TagEntity trackedTag = Assert.Single(trackedTags);
Assert.Same(secondIncomingTag, trackedTag);
Assert.DoesNotContain(trackedTags, trackedItem => ReferenceEquals(trackedItem, firstIncomingTag));
}
}
@@ -0,0 +1,142 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Persistence;
/// <summary>
/// Contains unit tests for the <see cref="EditableValuesCopier"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EditableValuesCopierTests
{
private readonly LuminaDbContext _mockContext = Create.MockedDbContextFor<LuminaDbContext>();
private readonly ArtistEntityFixture _artistEntityFixture = new();
[Fact]
public async Task CopyEditableValues_WhenCalled_ShouldCopyTheEditableScalarValuesOntoTheTrackedEntity()
{
// Arrange
ArtistEntity trackedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
_mockContext.Artists.Add(trackedArtist);
await _mockContext.SaveChangesAsync();
ArtistEntity incomingArtist = _artistEntityFixture.Create(id: trackedArtist.Id, name: "Updated Artist", includeAlbums: false, includeContributors: false);
incomingArtist.Website = "https://updated.example.com";
// Act
EditableValuesCopier.CopyEditableValues(_mockContext, trackedArtist, incomingArtist);
// Assert
Assert.Equal("Updated Artist", trackedArtist.Name);
Assert.Equal("https://updated.example.com", trackedArtist.Website);
}
[Fact]
public async Task CopyEditableValues_WhenCalled_ShouldPreserveTheStoredAuditColumns()
{
// Arrange
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
Guid storedCreatedBy = Guid.NewGuid();
DateTime storedUpdatedOnUtc = new(2021, 1, 2, 3, 4, 5, DateTimeKind.Utc);
Guid storedUpdatedBy = Guid.NewGuid();
ArtistEntity trackedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
trackedArtist.CreatedOnUtc = storedCreatedOnUtc;
trackedArtist.CreatedBy = storedCreatedBy;
trackedArtist.UpdatedOnUtc = storedUpdatedOnUtc;
trackedArtist.UpdatedBy = storedUpdatedBy;
_mockContext.Artists.Add(trackedArtist);
await _mockContext.SaveChangesAsync();
ArtistEntity incomingArtist = _artistEntityFixture.Create(id: trackedArtist.Id, includeAlbums: false, includeContributors: false);
incomingArtist.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
incomingArtist.CreatedBy = Guid.NewGuid();
incomingArtist.UpdatedOnUtc = DateTime.UtcNow;
incomingArtist.UpdatedBy = Guid.NewGuid();
// Act
EditableValuesCopier.CopyEditableValues(_mockContext, trackedArtist, incomingArtist);
// Assert
Assert.Equal(storedCreatedOnUtc, trackedArtist.CreatedOnUtc);
Assert.Equal(storedCreatedBy, trackedArtist.CreatedBy);
Assert.Equal(storedUpdatedOnUtc, trackedArtist.UpdatedOnUtc);
Assert.Equal(storedUpdatedBy, trackedArtist.UpdatedBy);
}
[Fact]
public async Task CopyEditableValues_WhenNoEditableValueChanged_ShouldNotMarkAnyEditablePropertyAsModified()
{
// Arrange
ArtistEntity trackedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
_mockContext.Artists.Add(trackedArtist);
await _mockContext.SaveChangesAsync();
ArtistEntity incomingArtist = _artistEntityFixture.Create(id: trackedArtist.Id, includeAlbums: false, includeContributors: false);
incomingArtist.Name = trackedArtist.Name;
incomingArtist.Website = trackedArtist.Website;
incomingArtist.MusicBrainzArtistId = trackedArtist.MusicBrainzArtistId;
incomingArtist.LibraryId = trackedArtist.LibraryId;
// Act
EditableValuesCopier.CopyEditableValues(_mockContext, trackedArtist, incomingArtist);
// Assert
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.Name).IsModified);
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.Website).IsModified);
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.MusicBrainzArtistId).IsModified);
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.LibraryId).IsModified);
// The primary key and the audit columns are owned by the persistence medium, so the copy never touches them either.
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.Id).IsModified);
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.CreatedOnUtc).IsModified);
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.CreatedBy).IsModified);
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.UpdatedOnUtc).IsModified);
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.UpdatedBy).IsModified);
}
[Theory]
[InlineData(false)] // The incoming entity carries a different, non-empty key.
[InlineData(true)] // The incoming entity carries an unset key.
public async Task CopyEditableValues_WhenTheIncomingKeyDoesNotMatchTheTrackedOne_ShouldPreserveTheTrackedIdentity(bool useUnsetKey)
{
// Arrange
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
Guid storedCreatedBy = Guid.NewGuid();
ArtistEntity trackedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
trackedArtist.CreatedOnUtc = storedCreatedOnUtc;
trackedArtist.CreatedBy = storedCreatedBy;
trackedArtist.UpdatedOnUtc = null;
trackedArtist.UpdatedBy = null;
_mockContext.Artists.Add(trackedArtist);
await _mockContext.SaveChangesAsync();
Guid trackedArtistId = trackedArtist.Id;
// The incoming entity carries a key that does not match the tracked one, a changed editable value, and hostile audit values.
Guid incomingId = useUnsetKey ? Guid.Empty : Guid.NewGuid();
ArtistEntity incomingArtist = _artistEntityFixture.Create(id: incomingId, name: "Updated Artist", includeAlbums: false, includeContributors: false);
incomingArtist.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
incomingArtist.CreatedBy = Guid.NewGuid();
incomingArtist.UpdatedOnUtc = DateTime.UtcNow;
incomingArtist.UpdatedBy = Guid.NewGuid();
// Act
EditableValuesCopier.CopyEditableValues(_mockContext, trackedArtist, incomingArtist);
// Assert
// The stored identity is never retargeted by the incoming key, the audit columns are untouched, and the editable values are still copied.
Assert.Equal(trackedArtistId, trackedArtist.Id);
Assert.NotEqual(incomingId, trackedArtist.Id);
Assert.Equal("Updated Artist", trackedArtist.Name);
Assert.Equal(storedCreatedOnUtc, trackedArtist.CreatedOnUtc);
Assert.Equal(storedCreatedBy, trackedArtist.CreatedBy);
Assert.Null(trackedArtist.UpdatedOnUtc);
Assert.Null(trackedArtist.UpdatedBy);
}
}
@@ -0,0 +1,467 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Persistence;
/// <summary>
/// Contains unit tests for the <see cref="SharedReferenceResolver"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SharedReferenceResolverTests
{
private readonly LuminaDbContext _mockContext = Create.MockedDbContextFor<LuminaDbContext>();
private readonly TagEntityFixture _tagEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
[Fact]
public async Task ResolveAsync_WhenANameIsNotStored_ShouldReturnTheIncomingInstance()
{
// Arrange
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
// Act
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(resolveResult.IsFailure);
Assert.Same(incomingTag, resolveResult.Value["jazz"]);
}
[Fact]
public async Task ResolveAsync_WhenANameIsAlreadyStoredAndTracked_ShouldReturnTheTrackedInstance()
{
// Arrange
TagEntity storedTag = _tagEntityFixture.Create(name: "jazz");
_mockContext.Set<TagEntity>().Add(storedTag);
await _mockContext.SaveChangesAsync();
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
// Act
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(resolveResult.IsFailure);
Assert.Same(storedTag, resolveResult.Value["jazz"]);
}
[Fact]
public async Task ResolveAsync_WhenANameIsAlreadyStoredButNotTracked_ShouldLoadTheStoredInstanceFromStorage()
{
// Arrange
TagEntity storedTag = _tagEntityFixture.Create(name: "jazz");
_mockContext.Set<TagEntity>().Add(storedTag);
await _mockContext.SaveChangesAsync();
// Detach the stored row, so that the resolution cannot take the tracked shortcut and must read it from the storage medium.
_mockContext.ChangeTracker.Clear();
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
// Act
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(resolveResult.IsFailure);
TagEntity resolvedTag = resolveResult.Value["jazz"];
// A different instance than the incoming one proves the row was materialized from the storage medium instead of the tracked shortcut.
Assert.NotSame(incomingTag, resolvedTag);
Assert.Equal("jazz", resolvedTag.Name);
}
[Fact]
public async Task ResolveAsync_WhenTheSameNameAppearsMoreThanOnce_ShouldCollapseItToASingleInstance()
{
// Arrange
TagEntity firstTag = _tagEntityFixture.Create(name: "jazz");
TagEntity secondTag = _tagEntityFixture.Create(name: "jazz");
// Act
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [firstTag, secondTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(resolveResult.IsFailure);
Assert.Single(resolveResult.Value);
Assert.Same(firstTag, resolveResult.Value["jazz"]);
}
[Fact]
public async Task ResolveAsync_WhenIncomingNamesDifferOnlyByCasing_ShouldCollapseThemToASingleInstance()
{
// Arrange
TagEntity firstTag = _tagEntityFixture.Create(name: "Horror");
TagEntity secondTag = _tagEntityFixture.Create(name: "horror");
// Act
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [firstTag, secondTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(resolveResult.IsFailure);
Assert.Single(resolveResult.Value);
Assert.Same(firstTag, resolveResult.Value["horror"]);
}
[Fact]
public async Task ResolveAsync_WhenAStoredNameDiffersOnlyByCasing_ShouldReturnTheStoredInstance()
{
// Arrange
TagEntity storedTag = _tagEntityFixture.Create(name: "horror");
_mockContext.Set<TagEntity>().Add(storedTag);
await _mockContext.SaveChangesAsync();
// Detach the stored row, so that the resolution cannot take the tracked shortcut and must read it from the storage medium.
_mockContext.ChangeTracker.Clear();
TagEntity incomingTag = _tagEntityFixture.Create(name: "Horror");
// Act
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(resolveResult.IsFailure);
TagEntity resolvedTag = resolveResult.Value["horror"];
// A different instance than the incoming one proves the stored row was reused instead of the incoming one being inserted.
Assert.NotSame(incomingTag, resolvedTag);
Assert.Equal("horror", resolvedTag.Name);
}
[Fact]
public async Task ResolveAsync_WhenIncomingNamesDifferOnlyByWhitespaceAndCasing_ShouldCollapseThemToTheNormalizedName()
{
// Arrange
TagEntity firstTag = _tagEntityFixture.Create(name: " Horror ");
TagEntity secondTag = _tagEntityFixture.Create(name: "HORROR");
TagEntity thirdTag = _tagEntityFixture.Create(name: "horror");
// Act
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [firstTag, secondTag, thirdTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(resolveResult.IsFailure);
Assert.Single(resolveResult.Value);
Assert.Same(firstTag, resolveResult.Value["horror"]);
}
[Fact]
public async Task ResolveAsync_WhenAStoredNormalizedNameExistsAndTheIncomingNameIsPaddedAndMixedCase_ShouldReturnTheStoredInstance()
{
// Arrange
TagEntity storedTag = _tagEntityFixture.Create(name: "horror");
_mockContext.Set<TagEntity>().Add(storedTag);
await _mockContext.SaveChangesAsync();
// Detach the stored row, so that the resolution cannot take the tracked shortcut and must read it from the storage medium.
_mockContext.ChangeTracker.Clear();
TagEntity incomingTag = _tagEntityFixture.Create(name: " HoRRoR ");
// Act
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(resolveResult.IsFailure);
Assert.Single(resolveResult.Value);
TagEntity resolvedTag = resolveResult.Value["horror"];
Assert.NotSame(incomingTag, resolvedTag);
Assert.Equal("horror", resolvedTag.Name);
}
[Fact]
public async Task ResolveAsync_WhenATrackedLegacyMixedCaseRowExistsAndTheIncomingNameIsNormalized_ShouldReturnTheTrackedInstance()
{
// Arrange
TagEntity trackedTag = _tagEntityFixture.Create(name: "Horror");
_mockContext.Set<TagEntity>().Add(trackedTag);
TagEntity incomingTag = _tagEntityFixture.Create(name: "horror");
// Act
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(resolveResult.IsFailure);
Assert.Same(trackedTag, resolveResult.Value["horror"]);
}
[Fact]
public async Task ResolveAsync_WhenANonAsciiUppercaseNameMatchesAStoredLowercaseName_ShouldReturnTheStoredInstance()
{
// Arrange
GenreEntity storedGenre = _genreEntityFixture.Create(name: "électro");
_mockContext.Set<GenreEntity>().Add(storedGenre);
await _mockContext.SaveChangesAsync();
// Detach the stored row, so that the resolution cannot take the tracked shortcut and must read it from the storage medium.
_mockContext.ChangeTracker.Clear();
GenreEntity incomingGenre = _genreEntityFixture.Create(name: "ÉLECTRO");
// Act
Result<IReadOnlyDictionary<string, GenreEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingGenre], Errors.Metadata.GenreNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(resolveResult.IsFailure);
Assert.Single(resolveResult.Value);
GenreEntity resolvedGenre = resolveResult.Value["électro"];
Assert.NotSame(incomingGenre, resolvedGenre);
Assert.Equal("électro", resolvedGenre.Name);
}
[Fact]
public async Task Normalize_WhenANameIsPaddedAndMixedCase_ShouldMapToTheResolvedInstance()
{
// Arrange
TagEntity resolvedTag = _tagEntityFixture.Create(name: "horror");
TagEntity incomingTag = _tagEntityFixture.Create(name: " HoRRoR ");
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [resolvedTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Act
IReadOnlyCollection<TagEntity> normalizedTags = SharedReferenceResolver.Normalize([incomingTag], resolveResult.Value);
// Assert
Assert.Same(resolvedTag, Assert.Single(normalizedTags));
}
[Fact]
public async Task ReconcileAsync_WhenAStoredNormalizedNameExistsAndTheIncomingNameIsPaddedAndMixedCase_ShouldReuseTheStoredInstance()
{
// Arrange
TagEntity storedTag = _tagEntityFixture.Create(name: "horror");
_mockContext.Set<TagEntity>().Add(storedTag);
await _mockContext.SaveChangesAsync();
List<TagEntity> trackedTags = [];
TagEntity incomingTag = _tagEntityFixture.Create(name: " HoRRoR ");
// Act
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Same(storedTag, Assert.Single(trackedTags));
}
[Fact]
public async Task ReconcileAsync_WhenANewNameIsRepeatedWithDifferentCasingAndWhitespace_ShouldAddASingleInstance()
{
// Arrange
List<TagEntity> trackedTags = [];
TagEntity firstTag = _tagEntityFixture.Create(name: " Horror ");
TagEntity secondTag = _tagEntityFixture.Create(name: "HORROR");
TagEntity thirdTag = _tagEntityFixture.Create(name: "horror");
// Act
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [firstTag, secondTag, thirdTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Same(firstTag, Assert.Single(trackedTags));
}
[Fact]
public async Task ResolveAsync_WhenThereAreNoIncomingEntities_ShouldReturnAnEmptyDictionary()
{
// Act
Result<IReadOnlyDictionary<string, GenreEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync<GenreEntity>(_mockContext, [], Errors.Metadata.GenreNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(resolveResult.IsFailure);
Assert.Empty(resolveResult.Value);
}
[Fact]
public async Task ReconcileAsync_WhenCalledWithAnotherSharedReferenceType_ShouldReconcileItTheSameWay()
{
// Arrange
List<GenreEntity> trackedGenres = [_genreEntityFixture.Create(name: "rock")];
GenreEntity incomingGenre = _genreEntityFixture.Create(name: "jazz");
// Act
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedGenres, [incomingGenre], Errors.Metadata.GenreNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Same(incomingGenre, Assert.Single(trackedGenres));
}
[Fact]
public async Task Normalize_WhenCalled_ShouldMapEveryEntityToItsResolvedInstance()
{
// Arrange
TagEntity firstTag = _tagEntityFixture.Create(name: "jazz");
TagEntity secondTag = _tagEntityFixture.Create(name: "jazz");
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [firstTag, secondTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Act
IReadOnlyCollection<TagEntity> normalizedTags = SharedReferenceResolver.Normalize([firstTag, secondTag], resolveResult.Value);
// Assert
TagEntity normalizedTag = Assert.Single(normalizedTags);
Assert.Same(firstTag, normalizedTag);
}
[Fact]
public async Task Normalize_WhenANameDiffersOnlyByCasingFromTheResolvedName_ShouldMapToTheResolvedInstance()
{
// Arrange
TagEntity resolvedTag = _tagEntityFixture.Create(name: "horror");
TagEntity incomingTag = _tagEntityFixture.Create(name: "Horror");
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [resolvedTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Act
IReadOnlyCollection<TagEntity> normalizedTags = SharedReferenceResolver.Normalize([incomingTag], resolveResult.Value);
// Assert
Assert.Same(resolvedTag, Assert.Single(normalizedTags));
}
[Fact]
public async Task ReconcileAsync_WhenANameIsNew_ShouldAddItToTheTrackedCollection()
{
// Arrange
List<TagEntity> trackedTags = [];
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
// Act
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Same(incomingTag, Assert.Single(trackedTags));
}
[Fact]
public async Task ReconcileAsync_WhenANameIsAlreadyStored_ShouldReuseTheStoredInstance()
{
// Arrange
TagEntity storedTag = _tagEntityFixture.Create(name: "jazz");
_mockContext.Set<TagEntity>().Add(storedTag);
await _mockContext.SaveChangesAsync();
List<TagEntity> trackedTags = [];
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
// Act
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Same(storedTag, Assert.Single(trackedTags));
}
[Fact]
public async Task ReconcileAsync_WhenATrackedNameIsMissingFromTheIncomingSet_ShouldRemoveIt()
{
// Arrange
TagEntity removedTag = _tagEntityFixture.Create(name: "rock");
TagEntity keptTag = _tagEntityFixture.Create(name: "jazz");
List<TagEntity> trackedTags = [removedTag, keptTag];
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
// Act
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Same(keptTag, Assert.Single(trackedTags));
Assert.DoesNotContain(removedTag, trackedTags);
}
[Fact]
public async Task ReconcileAsync_WhenTheSameNewNameAppearsMoreThanOnce_ShouldTrackASingleInstance()
{
// Arrange
List<TagEntity> trackedTags = [];
TagEntity firstTag = _tagEntityFixture.Create(name: "jazz");
TagEntity secondTag = _tagEntityFixture.Create(name: "jazz");
// Act
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [firstTag, secondTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Same(firstTag, Assert.Single(trackedTags));
}
[Fact]
public async Task ResolveAsync_WhenANameIsNull_ShouldReturnNameCannotBeEmptyError()
{
// Arrange
TagEntity incomingTag = _tagEntityFixture.Create(includeName: false);
// Act
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.True(resolveResult.IsFailure);
Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, resolveResult.FirstError);
}
[Fact]
public async Task ResolveAsync_WhenANameIsWhitespace_ShouldReturnNameCannotBeEmptyError()
{
// Arrange
TagEntity incomingTag = _tagEntityFixture.Create(name: " ");
// Act
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.True(resolveResult.IsFailure);
Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, resolveResult.FirstError);
}
[Fact]
public async Task ResolveAsync_WhenTheNameIsAlreadyTrackedButNotStored_ShouldReturnTheTrackedInstance()
{
// Arrange
TagEntity trackedTag = _tagEntityFixture.Create(name: "jazz");
_mockContext.Set<TagEntity>().Add(trackedTag);
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
// Act
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.False(resolveResult.IsFailure);
Assert.Same(trackedTag, resolveResult.Value["jazz"]);
}
[Fact]
public async Task ReconcileAsync_WhenANameIsNull_ShouldReturnNameCannotBeEmptyErrorWithoutChangingTheTrackedCollection()
{
// Arrange
List<TagEntity> trackedTags = [];
TagEntity incomingTag = _tagEntityFixture.Create(includeName: false);
// Act
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError);
Assert.Empty(trackedTags);
}
[Fact]
public async Task Normalize_WhenAnEntityCannotBeResolved_ShouldSkipIt()
{
// Arrange
TagEntity namedTag = _tagEntityFixture.Create(name: "jazz");
TagEntity unnamedTag = _tagEntityFixture.Create(includeName: false);
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [namedTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
// Act
IReadOnlyCollection<TagEntity> normalizedTags = SharedReferenceResolver.Normalize([namedTag, unnamedTag], resolveResult.Value);
// Assert
Assert.Same(namedTag, Assert.Single(normalizedTags));
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authentication;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Setup;
/// <summary>
/// Fake service for retrieving the current user's information during tests.
/// </summary>
[ExcludeFromCodeCoverage]
public class TestCurrentUserService : ICurrentUserService
{
private Guid userId;
public Guid? UserId => userId;
/// <summary>
/// Sets the test value of the user id.
/// </summary>
/// <param name="userId">The user id to use during tests.</param>
public void SetUserId(Guid userId)
{
this.userId = userId;
}
}
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Time;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Setup;
/// <summary>
/// Service for time related concerns.
/// </summary>
[ExcludeFromCodeCoverage]
public class TestDateTimeProvider : IDateTimeProvider
{
/// <summary>
/// The current UTC time.
/// </summary>
public DateTime UtcNow => DateTime.UtcNow;
}