mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 08:11:10 +00:00
Hardens test assertions and adds missing test coverage.
This commit is contained in:
1 parent
6b86fd5805
commit
1189bbaf36
489 files changed
+39982
-512
No files matched your search
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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());
|
||||
}
|
||||
}
|
||||
+88
@@ -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);
|
||||
}
|
||||
}
|
||||
+58
@@ -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());
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
#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="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);
|
||||
}
|
||||
|
||||
[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.DownloadMetadataFromWeb));
|
||||
|
||||
// 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());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureOwnedContentLocations()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
|
||||
|
||||
// Act
|
||||
List<IEntityType> ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)];
|
||||
|
||||
// Assert
|
||||
IEntityType contentLocationType = Assert.Single(ownedTypes);
|
||||
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_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());
|
||||
}
|
||||
}
|
||||
+91
@@ -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());
|
||||
}
|
||||
}
|
||||
+107
@@ -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());
|
||||
}
|
||||
}
|
||||
+94
@@ -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)]));
|
||||
}
|
||||
}
|
||||
+103
@@ -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());
|
||||
}
|
||||
}
|
||||
+90
@@ -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));
|
||||
}
|
||||
}
|
||||
+76
@@ -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());
|
||||
}
|
||||
}
|
||||
+84
@@ -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());
|
||||
}
|
||||
}
|
||||
+73
@@ -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());
|
||||
}
|
||||
}
|
||||
+85
@@ -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);
|
||||
}
|
||||
}
|
||||
+58
@@ -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());
|
||||
}
|
||||
}
|
||||
+115
@@ -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());
|
||||
}
|
||||
}
|
||||
+86
@@ -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);
|
||||
}
|
||||
}
|
||||
+101
@@ -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());
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#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="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);
|
||||
}
|
||||
|
||||
[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.IgnoreThePrefixForAlphaPicker));
|
||||
|
||||
// Assert
|
||||
Assert.False(userIdProperty.IsNullable);
|
||||
Assert.False(isPaginationEnabledProperty.IsNullable);
|
||||
Assert.False(itemsPerPageProperty.IsNullable);
|
||||
Assert.False(ignoreThePrefixProperty.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());
|
||||
}
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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_ShouldUseGuidEmptyForCreationAndSystemUserForModification()
|
||||
{
|
||||
// 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.Parse("11111111-1111-1111-1111-111111111111"), book.UpdatedBy);
|
||||
Assert.Equal(_fixedUtcNow, book.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.Books.Specifications;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Specifications;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookAlphaFilterSpecification"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The specification builds an expression that uses the SQLite GLOB function, which can only be evaluated by the Entity Framework SQLite provider,
|
||||
/// so the tests exercise the expression against a real SQLite database instead of evaluating it in memory.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookAlphaFilterSpecificationTests : IDisposable
|
||||
{
|
||||
private readonly string _connectionString;
|
||||
private readonly SqliteConnection _anchorConnection;
|
||||
private readonly LuminaDbContext _context;
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookAlphaFilterSpecificationTests"/> class.
|
||||
/// </summary>
|
||||
public BookAlphaFilterSpecificationTests()
|
||||
{
|
||||
_connectionString = $"Data Source=luminadataccess-alphaspec-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared";
|
||||
_anchorConnection = new SqliteConnection(_connectionString);
|
||||
_anchorConnection.Open();
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connectionString).Options);
|
||||
_context.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToExpression_WhenFilterAlphaKeyIsNull_ShouldMatchAllBooks()
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> books = await SeedBooksAsync(
|
||||
_bookEntityFixture.Create(title: "The Fellowship of the Ring"),
|
||||
_bookEntityFixture.Create(title: "1984"),
|
||||
_bookEntityFixture.Create(title: "@home"));
|
||||
BookAlphaFilterSpecification specification = new(null, false);
|
||||
|
||||
// Act
|
||||
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(3, matchingBooks.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToExpression_WhenFilterAlphaKeyIsALetter_ShouldMatchTitlesStartingWithThatLetter()
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> books = await SeedBooksAsync(
|
||||
_bookEntityFixture.Create(title: "The Fellowship of the Ring"),
|
||||
_bookEntityFixture.Create(title: "1984"),
|
||||
_bookEntityFixture.Create(title: "Zoo"));
|
||||
BookAlphaFilterSpecification specification = new("T", false);
|
||||
|
||||
// Act
|
||||
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
|
||||
|
||||
// Assert
|
||||
BookEntity matchedBook = Assert.Single(matchingBooks);
|
||||
Assert.Equal(books[0].Id, matchedBook.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToExpression_WhenFilterAlphaKeyIsALowercaseLetter_ShouldMatchTitlesStartingWithThatLetter()
|
||||
{
|
||||
// Arrange
|
||||
await SeedBooksAsync(
|
||||
_bookEntityFixture.Create(title: "Zoo"),
|
||||
_bookEntityFixture.Create(title: "moby dick"));
|
||||
BookAlphaFilterSpecification specification = new("Z", false);
|
||||
|
||||
// Act
|
||||
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
|
||||
|
||||
// Assert
|
||||
BookEntity matchedBook = Assert.Single(matchingBooks);
|
||||
Assert.Equal("Zoo", matchedBook.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToExpression_WhenFilterAlphaKeyIsNumber_ShouldMatchTitlesStartingWithADigit()
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> books = await SeedBooksAsync(
|
||||
_bookEntityFixture.Create(title: "1984"),
|
||||
_bookEntityFixture.Create(title: "The Fellowship of the Ring"));
|
||||
BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.NUMBER, false);
|
||||
|
||||
// Act
|
||||
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
|
||||
|
||||
// Assert
|
||||
BookEntity matchedBook = Assert.Single(matchingBooks);
|
||||
Assert.Equal(books[0].Id, matchedBook.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToExpression_WhenFilterAlphaKeyIsSymbol_ShouldMatchTitlesStartingWithANonAlphanumericCharacter()
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> books = await SeedBooksAsync(
|
||||
_bookEntityFixture.Create(title: "@home"),
|
||||
_bookEntityFixture.Create(title: "1984"),
|
||||
_bookEntityFixture.Create(title: "Zoo"));
|
||||
BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.SYMBOL, false);
|
||||
|
||||
// Act
|
||||
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
|
||||
|
||||
// Assert
|
||||
BookEntity matchedBook = Assert.Single(matchingBooks);
|
||||
Assert.Equal(books[0].Id, matchedBook.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToExpression_WhenIgnoreThePrefixIsTrue_ShouldStripTheLeadingThePrefix()
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> books = await SeedBooksAsync(
|
||||
_bookEntityFixture.Create(title: "The Fellowship of the Ring"),
|
||||
_bookEntityFixture.Create(title: "To Kill a Mockingbird"));
|
||||
BookAlphaFilterSpecification specification = new("T", true);
|
||||
|
||||
// Act
|
||||
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
|
||||
|
||||
// Assert
|
||||
BookEntity matchedBook = Assert.Single(matchingBooks);
|
||||
Assert.Equal(books[1].Id, matchedBook.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToExpression_WhenIgnoreThePrefixIsFalse_ShouldNotStripTheLeadingThePrefix()
|
||||
{
|
||||
// Arrange
|
||||
await SeedBooksAsync(
|
||||
_bookEntityFixture.Create(title: "The Fellowship of the Ring"),
|
||||
_bookEntityFixture.Create(title: "To Kill a Mockingbird"));
|
||||
BookAlphaFilterSpecification specification = new("T", false);
|
||||
|
||||
// Act
|
||||
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, matchingBooks.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToExpression_WhenTitleIsEmpty_ShouldFallBackToOriginalTitle()
|
||||
{
|
||||
// Arrange
|
||||
await SeedBooksAsync(_bookEntityFixture.Create(title: string.Empty, originalTitle: "The Real Title"));
|
||||
BookAlphaFilterSpecification specification = new("T", false);
|
||||
|
||||
// Act
|
||||
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
|
||||
|
||||
// Assert
|
||||
BookEntity matchedBook = Assert.Single(matchingBooks);
|
||||
Assert.Equal("The Real Title", matchedBook.OriginalTitle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists the provided books to the database.
|
||||
/// </summary>
|
||||
/// <param name="books">The books to persist.</param>
|
||||
/// <returns>The persisted books.</returns>
|
||||
private async Task<List<BookEntity>> SeedBooksAsync(params BookEntity[] books)
|
||||
{
|
||||
_context.Books.AddRange(books);
|
||||
await _context.SaveChangesAsync();
|
||||
return [.. books];
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
_anchorConnection.Dispose();
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.Books.Specifications;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Specifications;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookSearchSpecification"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookSearchSpecificationTests
|
||||
{
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenTitleContainsSearchTerm_ShouldMatchBook()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.Title = "The Fellowship of the Ring";
|
||||
book.OriginalTitle = null;
|
||||
BookSearchSpecification specification = new("Fellowship");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(book);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenOriginalTitleContainsSearchTerm_ShouldMatchBook()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.Title = "A Random Title";
|
||||
book.OriginalTitle = "Lord of the Rings: The Fellowship";
|
||||
BookSearchSpecification specification = new("Fellowship");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(book);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenOriginalTitleIsNull_ShouldMatchOnlyOnTitle()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.Title = "The Fellowship of the Ring";
|
||||
book.OriginalTitle = null;
|
||||
BookSearchSpecification specification = new("Ring");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(book);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenNeitherTitleNorOriginalTitleContainsSearchTerm_ShouldNotMatchBook()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.Title = "The Fellowship of the Ring";
|
||||
book.OriginalTitle = "The Two Towers";
|
||||
BookSearchSpecification specification = new("Hobbit");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(book);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenSearchTermIsNotPresent_ShouldFilterOutNonMatchingBooks()
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> books = _bookEntityFixture.CreateMany(3);
|
||||
books[0].Title = "The Fellowship of the Ring";
|
||||
books[1].Title = "The Two Towers";
|
||||
books[2].Title = "The Return of the King";
|
||||
BookSearchSpecification specification = new("Fellowship");
|
||||
|
||||
// Act
|
||||
IEnumerable<BookEntity> matchingBooks = books.AsQueryable().Where(specification.ToExpression());
|
||||
|
||||
// Assert
|
||||
BookEntity matchedBook = Assert.Single(matchingBooks);
|
||||
Assert.Equal(books[0].Title, matchedBook.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenTitleMatchesInDifferentCase_ShouldNotMatchCaseInsensitively()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.Title = "The Fellowship of the Ring";
|
||||
book.OriginalTitle = null;
|
||||
BookSearchSpecification specification = new("fellowship");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(book);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Common.Dapper;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DirectoryScanFingerprintRepository"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The repository executes parameterized raw SQL on a dedicated database connection, so the tests exercise it against a real SQLite database
|
||||
/// instead of the mocked in-memory context used by the Entity Framework based repositories.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DirectoryScanFingerprintRepositoryTests : IDisposable
|
||||
{
|
||||
private readonly string _connectionString;
|
||||
private readonly SqliteConnection _anchorConnection;
|
||||
private readonly LuminaDbContext _context;
|
||||
private readonly DirectoryScanFingerprintRepository _sut;
|
||||
private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DirectoryScanFingerprintRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public DirectoryScanFingerprintRepositoryTests()
|
||||
{
|
||||
DapperTypeHandlers.Register();
|
||||
_connectionString = $"Data Source=luminadataccess-fingerprint-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared";
|
||||
_anchorConnection = new SqliteConnection(_connectionString);
|
||||
_anchorConnection.Open();
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connectionString).Options);
|
||||
_context.Database.EnsureCreated();
|
||||
_sut = new DirectoryScanFingerprintRepository(_context);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMappedByLibraryIdAsync_WhenCalled_ShouldReturnFingerprintsOfTheLibraryMappedByPath()
|
||||
{
|
||||
// Arrange
|
||||
(Guid libraryId, _) = await SeedLibraryGraphAsync();
|
||||
UserEntity otherUser = _userEntityFixture.Create();
|
||||
_context.Users.Add(otherUser);
|
||||
Guid otherLibraryId = Guid.NewGuid();
|
||||
LibraryEntity otherLibrary = _libraryEntityFixture.Create(id: otherLibraryId, userId: otherUser.Id);
|
||||
_context.Libraries.Add(otherLibrary);
|
||||
|
||||
DirectoryScanFingerprintEntity firstFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1", lastWriteTimeUtc: DateTime.UtcNow.AddDays(-1));
|
||||
DirectoryScanFingerprintEntity secondFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir2", lastWriteTimeUtc: DateTime.UtcNow.AddDays(-2));
|
||||
DirectoryScanFingerprintEntity fingerprintOfOtherLibrary = _directoryScanFingerprintEntityFixture.Create(libraryId: otherLibraryId, path: "/dir3");
|
||||
_context.DirectoryScanFingerprints.AddRange(firstFingerprint, secondFingerprint, fingerprintOfOtherLibrary);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Dictionary<string, DirectoryScanFingerprintEntity>> result = await _sut.GetMappedByLibraryIdAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.True(result.Value.ContainsKey("/dir1"));
|
||||
Assert.True(result.Value.ContainsKey("/dir2"));
|
||||
Assert.False(result.Value.ContainsKey("/dir3"));
|
||||
Assert.Equal(firstFingerprint.Id, result.Value["/dir1"].Id);
|
||||
Assert.Equal(secondFingerprint.Id, result.Value["/dir2"].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMappedByLibraryIdAsync_WhenNoFingerprintsExist_ShouldReturnEmptyDictionary()
|
||||
{
|
||||
// Arrange
|
||||
(Guid libraryId, _) = await SeedLibraryGraphAsync();
|
||||
|
||||
// Act
|
||||
Result<Dictionary<string, DirectoryScanFingerprintEntity>> result = await _sut.GetMappedByLibraryIdAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertRangeAsync_WhenCalledWithNewFingerprints_ShouldInsertThemAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
(Guid libraryId, _) = await SeedLibraryGraphAsync();
|
||||
List<DirectoryScanFingerprintEntity> fingerprints =
|
||||
[
|
||||
_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId),
|
||||
_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId)
|
||||
];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertRangeAsync(fingerprints, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
Assert.Equal(2, await _context.DirectoryScanFingerprints.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertRangeAsync_WhenCalledWithExistingFingerprints_ShouldUpdateTheirLastWriteTime()
|
||||
{
|
||||
// Arrange
|
||||
(Guid libraryId, _) = await SeedLibraryGraphAsync();
|
||||
DirectoryScanFingerprintEntity existingFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1", lastWriteTimeUtc: DateTime.UtcNow.AddDays(-1));
|
||||
_context.DirectoryScanFingerprints.Add(existingFingerprint);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
DateTime newLastWriteTimeUtc = DateTime.UtcNow.AddDays(1);
|
||||
DirectoryScanFingerprintEntity updatedFingerprint = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
Path = "/dir1",
|
||||
LastWriteTimeUtc = newLastWriteTimeUtc
|
||||
};
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertRangeAsync([updatedFingerprint], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
DirectoryScanFingerprintEntity retrievedFingerprint = await _context.DirectoryScanFingerprints.AsNoTracking().SingleAsync();
|
||||
Assert.Equal(newLastWriteTimeUtc, retrievedFingerprint.LastWriteTimeUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertRangeAsync_WhenCollectionIsEmpty_ShouldReturnUpdatedWithoutUpserting()
|
||||
{
|
||||
// Arrange
|
||||
(Guid libraryId, _) = await SeedLibraryGraphAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertRangeAsync([], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
Assert.False(await _context.DirectoryScanFingerprints.AnyAsync());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the user and media library required by the foreign key of the fingerprints table.
|
||||
/// </summary>
|
||||
/// <returns>The seeded library Id and user Id.</returns>
|
||||
private async Task<(Guid LibraryId, Guid UserId)> SeedLibraryGraphAsync()
|
||||
{
|
||||
UserEntity user = _userEntityFixture.Create();
|
||||
_context.Users.Add(user);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(userId: user.Id);
|
||||
_context.Libraries.Add(library);
|
||||
await _context.SaveChangesAsync();
|
||||
return (library.Id, user.Id);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
_anchorConnection.Dispose();
|
||||
}
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly LibraryRepository _sut;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new LibraryRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenLibraryDoesNotExist_ShouldAddLibraryToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(library, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<LibraryEntity>? addedLibrary = _mockContext.ChangeTracker.Entries<LibraryEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == library.Id);
|
||||
Assert.NotNull(addedLibrary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenLibraryAlreadyExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create();
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(library, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryAlreadyExists, result.FirstError);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<LibraryEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenLibraryExists_ShouldReturnLibraryWithContentLocations()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create();
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<LibraryEntity?> result = await _sut.GetByIdAsync(library.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(library.Id, result.Value!.Id);
|
||||
Assert.Equal(library.ContentLocations.Count, result.Value.ContentLocations.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenLibraryDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<LibraryEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllEnabledAsync_WhenCalled_ShouldReturnOnlyEnabledLibraries()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity enabledLibrary = _libraryEntityFixture.Create(isEnabled: true);
|
||||
LibraryEntity disabledLibrary = _libraryEntityFixture.Create(isEnabled: false);
|
||||
_mockContext.Libraries.AddRange(enabledLibrary, disabledLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<LibraryEntity>> result = await _sut.GetAllEnabledAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryEntity retrievedLibrary = Assert.Single(result.Value);
|
||||
Assert.Equal(enabledLibrary.Id, retrievedLibrary.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllEnabledAndUnlockedAsync_WhenCalled_ShouldReturnOnlyEnabledAndUnlockedLibraries()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity enabledUnlockedLibrary = _libraryEntityFixture.Create(isEnabled: true, isLocked: false);
|
||||
LibraryEntity enabledLockedLibrary = _libraryEntityFixture.Create(isEnabled: true, isLocked: true);
|
||||
LibraryEntity disabledUnlockedLibrary = _libraryEntityFixture.Create(isEnabled: false, isLocked: false);
|
||||
_mockContext.Libraries.AddRange(enabledUnlockedLibrary, enabledLockedLibrary, disabledUnlockedLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<LibraryEntity>> result = await _sut.GetAllEnabledAndUnlockedAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryEntity retrievedLibrary = Assert.Single(result.Value);
|
||||
Assert.Equal(enabledUnlockedLibrary.Id, retrievedLibrary.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenCalled_ShouldReturnAllLibraries()
|
||||
{
|
||||
// Arrange
|
||||
List<LibraryEntity> libraries = _libraryEntityFixture.CreateMany(3);
|
||||
_mockContext.Libraries.AddRange(libraries);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<LibraryEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count());
|
||||
Assert.Equal(libraries, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenLibraryExists_ShouldUpdateScalarPropertiesAndContentLocations()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: ["/old/path"]);
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryEntity updatedLibrary = new()
|
||||
{
|
||||
Id = library.Id,
|
||||
UserId = library.UserId,
|
||||
Title = "Updated Title",
|
||||
LibraryType = library.LibraryType,
|
||||
ContentLocations = [new LibraryContentLocationEntity { Path = "/new/path" }],
|
||||
CreatedOnUtc = library.CreatedOnUtc,
|
||||
CreatedBy = library.CreatedBy,
|
||||
UpdatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = library.UserId
|
||||
};
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
LibraryEntity? retrievedLibrary = await _mockContext.Libraries.FindAsync(library.Id);
|
||||
Assert.NotNull(retrievedLibrary);
|
||||
Assert.Equal("Updated Title", retrievedLibrary!.Title);
|
||||
Assert.Single(retrievedLibrary.ContentLocations);
|
||||
Assert.Equal("/new/path", retrievedLibrary.ContentLocations.First().Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenLibraryDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(library, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenLibraryExists_ShouldRemoveItFromContextAndReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create();
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(library.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
|
||||
EntityEntry<LibraryEntity>? deletedLibrary = _mockContext.ChangeTracker.Entries<LibraryEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Deleted && entityEntry.Entity.Id == library.Id);
|
||||
Assert.NotNull(deletedLibrary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenLibraryDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScanRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly LibraryScanRepository _sut;
|
||||
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryScanRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new LibraryScanRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenLibraryScanDoesNotExist_ShouldAddScanToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(libraryScan, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<LibraryScanEntity>? addedScan = _mockContext.ChangeTracker.Entries<LibraryScanEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == libraryScan.Id);
|
||||
Assert.NotNull(addedScan);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenLibraryScanAlreadyExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create();
|
||||
_mockContext.LibraryScans.Add(libraryScan);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(libraryScan, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.LibraryScanAlreadyExists, result.FirstError);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<LibraryScanEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenLibraryScanExists_ShouldReturnScanWithLibraryAndUser()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create();
|
||||
_mockContext.LibraryScans.Add(libraryScan);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<LibraryScanEntity?> result = await _sut.GetByIdAsync(libraryScan.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(libraryScan.Id, result.Value!.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenLibraryScanDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<LibraryScanEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPastMonthScansByLibraryIdAsync_WhenCalled_ShouldReturnOnlyRecentScansOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create();
|
||||
LibraryScanEntity recentScan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, createdOnUtc: DateTime.UtcNow.AddDays(-1));
|
||||
LibraryScanEntity oldScan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, createdOnUtc: DateTime.UtcNow.AddMonths(-2));
|
||||
LibraryScanEntity scanOfAnotherLibrary = _libraryScanEntityFixture.Create(createdOnUtc: DateTime.UtcNow.AddDays(-1));
|
||||
_mockContext.LibraryScans.AddRange(recentScan, oldScan, scanOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<LibraryScanEntity>> result = await _sut.GetPastMonthScansByLibraryIdAsync(library.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryScanEntity retrievedScan = Assert.Single(result.Value);
|
||||
Assert.Equal(recentScan.Id, retrievedScan.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRunningScansAsync_WhenCalled_ShouldReturnOnlyRunningScans()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Running);
|
||||
LibraryScanEntity completedScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Completed);
|
||||
LibraryScanEntity pendingScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Pending);
|
||||
_mockContext.LibraryScans.AddRange(runningScan, completedScan, pendingScan);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<LibraryScanEntity>> result = await _sut.GetRunningScansAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryScanEntity retrievedScan = Assert.Single(result.Value);
|
||||
Assert.Equal(runningScan.Id, retrievedScan.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenLibraryScanExists_ShouldUpdateItsScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create();
|
||||
_mockContext.LibraryScans.Add(libraryScan);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryScanEntity updatedScan = new()
|
||||
{
|
||||
Id = libraryScan.Id,
|
||||
LibraryId = libraryScan.LibraryId,
|
||||
UserId = libraryScan.UserId,
|
||||
Status = LibraryScanJobStatus.Completed,
|
||||
Library = libraryScan.Library,
|
||||
User = libraryScan.User,
|
||||
CreatedOnUtc = libraryScan.CreatedOnUtc,
|
||||
CreatedBy = libraryScan.CreatedBy,
|
||||
UpdatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = libraryScan.UserId
|
||||
};
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedScan, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
LibraryScanEntity? retrievedScan = await _mockContext.LibraryScans.FindAsync(libraryScan.Id);
|
||||
Assert.NotNull(retrievedScan);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, retrievedScan!.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenLibraryScanDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(libraryScan, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.LibraryScanNotFound, result.FirstError);
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScanResultRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanResultRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly LibraryScanResultRepository _sut;
|
||||
private readonly LibraryScanResultEntityFixture _libraryScanResultEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanResultRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryScanResultRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new LibraryScanResultRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenCalled_ShouldAddScanResultToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanResultEntity libraryScanResult = _libraryScanResultEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(libraryScanResult, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<LibraryScanResultEntity>? addedScanResult = _mockContext.ChangeTracker.Entries<LibraryScanResultEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == libraryScanResult.Id);
|
||||
Assert.NotNull(addedScanResult);
|
||||
}
|
||||
}
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScanSnapshotRepository"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The repository executes parameterized raw SQL on a dedicated database connection, so the tests exercise it against a real SQLite database
|
||||
/// instead of the mocked in-memory context used by the Entity Framework based repositories.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanSnapshotRepositoryTests : IDisposable
|
||||
{
|
||||
private readonly string _connectionString;
|
||||
private readonly SqliteConnection _anchorConnection;
|
||||
private readonly LuminaDbContext _context;
|
||||
private readonly LibraryScanSnapshotRepository _sut;
|
||||
private readonly LibraryScanSnapshotEntityFixture _libraryScanSnapshotEntityFixture = new();
|
||||
private readonly LibraryScanStagingResultsEntityFixture _libraryScanStagingResultsEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanSnapshotRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryScanSnapshotRepositoryTests()
|
||||
{
|
||||
_connectionString = $"Data Source=luminadataccess-snapshot-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared";
|
||||
_anchorConnection = new SqliteConnection(_connectionString);
|
||||
_anchorConnection.Open();
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connectionString).Options);
|
||||
_context.Database.EnsureCreated();
|
||||
_sut = new LibraryScanSnapshotRepository(_context);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedPathsAsync_WhenSnapshotPathsAreMissingFromStaging_ShouldReturnThosePaths()
|
||||
{
|
||||
// Arrange
|
||||
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
|
||||
LibraryScanSnapshotEntity keptSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub");
|
||||
LibraryScanSnapshotEntity deletedSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/delete.epub");
|
||||
_context.LibraryScanSnapshots.AddRange(keptSnapshot, deletedSnapshot);
|
||||
LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/keep.epub");
|
||||
_context.LibraryScanStagingResults.Add(staging);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<string>> result = await _sut.GetDeletedPathsAsync(library.Id, scanId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
string deletedPath = Assert.Single(result.Value);
|
||||
Assert.Equal("/books/delete.epub", deletedPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedPathsAsync_WhenAllSnapshotPathsArePresentInStaging_ShouldReturnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
|
||||
LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub");
|
||||
_context.LibraryScanSnapshots.Add(snapshot);
|
||||
LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/keep.epub");
|
||||
_context.LibraryScanStagingResults.Add(staging);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<string>> result = await _sut.GetDeletedPathsAsync(library.Id, scanId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedPathsAsync_WhenStagingOfAnotherScanMatches_ShouldStillReturnThePaths()
|
||||
{
|
||||
// Arrange
|
||||
(UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
|
||||
LibraryScanEntity otherScan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Completed);
|
||||
_context.LibraryScans.Add(otherScan);
|
||||
LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub");
|
||||
_context.LibraryScanSnapshots.Add(snapshot);
|
||||
LibraryScanStagingResultsEntity stagingOfOtherScan = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: otherScan.Id, path: "/books/a.epub");
|
||||
_context.LibraryScanStagingResults.Add(stagingOfOtherScan);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<string>> result = await _sut.GetDeletedPathsAsync(library.Id, scanId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
string deletedPath = Assert.Single(result.Value);
|
||||
Assert.Equal("/books/a.epub", deletedPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathsAsync_WhenCalled_ShouldReturnAllSnapshotPathsOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
(_, LibraryEntity library, _) = await SeedScanGraphAsync();
|
||||
LibraryScanSnapshotEntity firstSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub");
|
||||
LibraryScanSnapshotEntity secondSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/b.epub");
|
||||
_context.LibraryScanSnapshots.AddRange(firstSnapshot, secondSnapshot);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<string>> result = await _sut.GetPathsAsync(library.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains("/books/a.epub", result.Value);
|
||||
Assert.Contains("/books/b.epub", result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathsAsync_WhenNoSnapshotsExist_ShouldReturnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
(_, LibraryEntity library, _) = await SeedScanGraphAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<string>> result = await _sut.GetPathsAsync(library.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplySnapshotSwapAsync_WhenCalled_ShouldAuditDeletedChangedAndNewItemsAndUpdateSnapshot()
|
||||
{
|
||||
// Arrange
|
||||
(UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
|
||||
|
||||
LibraryScanSnapshotEntity keptSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub", contentHash: 111, fileSize: 100, ticks: 1000);
|
||||
LibraryScanSnapshotEntity deletedSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/delete.epub", contentHash: 222, fileSize: 200, ticks: 2000);
|
||||
_context.LibraryScanSnapshots.AddRange(keptSnapshot, deletedSnapshot);
|
||||
|
||||
LibraryScanStagingResultsEntity unchangedStaging = _libraryScanStagingResultsEntityFixture.Create(
|
||||
libraryScanId: scanId, path: "/books/keep.epub", size: 100, ticks: 1000, contentHash: 999, needsRehash: false, isNew: false);
|
||||
LibraryScanStagingResultsEntity newStaging = _libraryScanStagingResultsEntityFixture.Create(
|
||||
libraryScanId: scanId, path: "/books/new.epub", size: 300, ticks: 3000, contentHash: 300, needsRehash: true, isNew: true);
|
||||
LibraryScanStagingResultsEntity modifiedStaging = _libraryScanStagingResultsEntityFixture.Create(
|
||||
libraryScanId: scanId, path: "/books/modified.epub", size: 400, ticks: 4000, contentHash: 400, needsRehash: true, isNew: false);
|
||||
_context.LibraryScanStagingResults.AddRange(unchangedStaging, newStaging, modifiedStaging);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.ApplySnapshotSwapAsync(library.Id, scanId, user.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
// audit entries: deleted, new and modified items
|
||||
List<LibraryScanResultEntity> scanResults = await _context.LibraryScanResults.AsNoTracking()
|
||||
.Where(scanResult => scanResult.LibraryScanId == scanId)
|
||||
.ToListAsync();
|
||||
Assert.Equal(3, scanResults.Count);
|
||||
Assert.Contains(scanResults, scanResult => scanResult.Path == "/books/delete.epub" && scanResult.Status == LibraryScanFileStatus.Deleted);
|
||||
Assert.Contains(scanResults, scanResult => scanResult.Path == "/books/new.epub" && scanResult.Status == LibraryScanFileStatus.New);
|
||||
Assert.Contains(scanResults, scanResult => scanResult.Path == "/books/modified.epub" && scanResult.Status == LibraryScanFileStatus.Modified);
|
||||
Assert.DoesNotContain(scanResults, scanResult => scanResult.Path == "/books/keep.epub");
|
||||
|
||||
// the snapshot now contains the kept, new and modified items and no longer contains the deleted one
|
||||
List<LibraryScanSnapshotEntity> snapshots = await _context.LibraryScanSnapshots.AsNoTracking()
|
||||
.Where(snapshot => snapshot.LibraryId == library.Id)
|
||||
.ToListAsync();
|
||||
Assert.Equal(3, snapshots.Count);
|
||||
Assert.Contains(snapshots, snapshot => snapshot.Path == "/books/keep.epub" && snapshot.ContentHash == 111);
|
||||
Assert.Contains(snapshots, snapshot => snapshot.Path == "/books/new.epub" && snapshot.ContentHash == 300);
|
||||
Assert.Contains(snapshots, snapshot => snapshot.Path == "/books/modified.epub" && snapshot.ContentHash == 400);
|
||||
Assert.DoesNotContain(snapshots, snapshot => snapshot.Path == "/books/delete.epub");
|
||||
|
||||
// the staging results of the scan have been cleared
|
||||
Assert.False(await _context.LibraryScanStagingResults.AsNoTracking().AnyAsync(staging => staging.LibraryScanId == scanId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplySnapshotSwapAsync_WhenNoStagingNeedsRehash_ShouldOnlyClearStagingAndAuditDeletedItems()
|
||||
{
|
||||
// Arrange
|
||||
(UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
|
||||
|
||||
LibraryScanSnapshotEntity keptSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub", contentHash: 111, fileSize: 100, ticks: 1000);
|
||||
_context.LibraryScanSnapshots.Add(keptSnapshot);
|
||||
LibraryScanStagingResultsEntity unchangedStaging = _libraryScanStagingResultsEntityFixture.Create(
|
||||
libraryScanId: scanId, path: "/books/keep.epub", size: 100, ticks: 1000, needsRehash: false, isNew: false);
|
||||
_context.LibraryScanStagingResults.Add(unchangedStaging);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.ApplySnapshotSwapAsync(library.Id, scanId, user.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
Assert.False(await _context.LibraryScanResults.AsNoTracking().AnyAsync());
|
||||
Assert.False(await _context.LibraryScanStagingResults.AsNoTracking().AnyAsync(staging => staging.LibraryScanId == scanId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the user, media library and media library scan required by the foreign keys of the snapshot and staging tables.
|
||||
/// </summary>
|
||||
/// <returns>The seeded user, media library and scan Id.</returns>
|
||||
private async Task<(UserEntity User, LibraryEntity Library, Guid ScanId)> SeedScanGraphAsync()
|
||||
{
|
||||
UserEntity user = _userEntityFixture.Create();
|
||||
_context.Users.Add(user);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(userId: user.Id);
|
||||
_context.Libraries.Add(library);
|
||||
LibraryScanEntity scan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Running);
|
||||
_context.LibraryScans.Add(scan);
|
||||
await _context.SaveChangesAsync();
|
||||
return (user, library, scan.Id);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
_anchorConnection.Dispose();
|
||||
}
|
||||
}
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScanStagingResultsRepository"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The repository executes parameterized raw SQL on a dedicated database connection, so the tests exercise it against a real SQLite database
|
||||
/// instead of the mocked in-memory context used by the Entity Framework based repositories.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanStagingResultsRepositoryTests : IDisposable
|
||||
{
|
||||
private readonly string _connectionString;
|
||||
private readonly SqliteConnection _anchorConnection;
|
||||
private readonly LuminaDbContext _context;
|
||||
private readonly LibraryScanStagingResultsRepository _sut;
|
||||
private readonly LibraryScanStagingResultsEntityFixture _libraryScanStagingResultsEntityFixture = new();
|
||||
private readonly LibraryScanSnapshotEntityFixture _libraryScanSnapshotEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanStagingResultsRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryScanStagingResultsRepositoryTests()
|
||||
{
|
||||
_connectionString = $"Data Source=luminadataccess-staging-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared";
|
||||
_anchorConnection = new SqliteConnection(_connectionString);
|
||||
_anchorConnection.Open();
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connectionString).Options);
|
||||
_context.Database.EnsureCreated();
|
||||
_sut = new LibraryScanStagingResultsRepository(_context);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertRangeAsync_WhenCalled_ShouldInsertAllEntitiesAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
(_, _, Guid scanId) = await SeedScanGraphAsync();
|
||||
List<LibraryScanStagingResultsEntity> stagingResults = _libraryScanStagingResultsEntityFixture.CreateMany(3);
|
||||
for (int i = 0; i < stagingResults.Count; i++)
|
||||
stagingResults[i] = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertRangeAsync(stagingResults, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
Assert.Equal(3, await _context.LibraryScanStagingResults.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertRangeAsync_WhenCollectionIsEmpty_ShouldReturnCreatedWithoutInserting()
|
||||
{
|
||||
// Arrange
|
||||
await SeedScanGraphAsync();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertRangeAsync([], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
Assert.False(await _context.LibraryScanStagingResults.AnyAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MarkChangesAgainstSnapshotAsync_WhenSnapshotHasSameSizeAndTicks_ShouldMarkAsUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
|
||||
LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub", contentHash: 111, fileSize: 100, ticks: 1000);
|
||||
_context.LibraryScanSnapshots.Add(snapshot);
|
||||
LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", size: 100, ticks: 1000);
|
||||
_context.LibraryScanStagingResults.Add(staging);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.MarkChangesAgainstSnapshotAsync(scanId, library.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
LibraryScanStagingResultsEntity markedStaging = await _context.LibraryScanStagingResults.AsNoTracking().SingleAsync();
|
||||
Assert.Equal(111UL, markedStaging.ContentHash);
|
||||
Assert.Equal(111UL, markedStaging.PreviousContentHash);
|
||||
Assert.False(markedStaging.NeedsRehash);
|
||||
Assert.False(markedStaging.IsNew);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MarkChangesAgainstSnapshotAsync_WhenSnapshotHasDifferentSizeOrTicks_ShouldMarkAsChanged()
|
||||
{
|
||||
// Arrange
|
||||
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
|
||||
LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub", contentHash: 222, fileSize: 100, ticks: 1000);
|
||||
_context.LibraryScanSnapshots.Add(snapshot);
|
||||
LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", size: 500, ticks: 5000);
|
||||
_context.LibraryScanStagingResults.Add(staging);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.MarkChangesAgainstSnapshotAsync(scanId, library.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
LibraryScanStagingResultsEntity markedStaging = await _context.LibraryScanStagingResults.AsNoTracking().SingleAsync();
|
||||
Assert.Equal(222UL, markedStaging.ContentHash);
|
||||
Assert.Equal(222UL, markedStaging.PreviousContentHash);
|
||||
Assert.True(markedStaging.NeedsRehash);
|
||||
Assert.False(markedStaging.IsNew);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MarkChangesAgainstSnapshotAsync_WhenNoSnapshotExists_ShouldKeepTheItemMarkedAsNew()
|
||||
{
|
||||
// Arrange
|
||||
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
|
||||
// the file system discovery job seeds new items with no hash and marks them as new, needing a rehash
|
||||
LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", contentHash: 0, previousContentHash: 0, needsRehash: true, isNew: true);
|
||||
_context.LibraryScanStagingResults.Add(staging);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.MarkChangesAgainstSnapshotAsync(scanId, library.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
LibraryScanStagingResultsEntity markedStaging = await _context.LibraryScanStagingResults.AsNoTracking().SingleAsync();
|
||||
Assert.Equal(0UL, markedStaging.ContentHash);
|
||||
Assert.Equal(0UL, markedStaging.PreviousContentHash);
|
||||
Assert.True(markedStaging.NeedsRehash);
|
||||
Assert.True(markedStaging.IsNew);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFilesToHashCountAsync_WhenCalled_ShouldReturnOnlyStagingResultsNeedingRehash()
|
||||
{
|
||||
// Arrange
|
||||
(_, _, Guid scanId) = await SeedScanGraphAsync();
|
||||
LibraryScanStagingResultsEntity firstRehash = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, needsRehash: true);
|
||||
LibraryScanStagingResultsEntity secondRehash = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, needsRehash: true);
|
||||
LibraryScanStagingResultsEntity noRehash = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, needsRehash: false);
|
||||
_context.LibraryScanStagingResults.AddRange(firstRehash, secondRehash, noRehash);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<int> result = await _sut.GetFilesToHashCountAsync(scanId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFilesToHashPageAsync_WhenCalled_ShouldReturnOrderedPageOfStagingResultsNeedingRehash()
|
||||
{
|
||||
// Arrange
|
||||
(_, _, Guid scanId) = await SeedScanGraphAsync();
|
||||
LibraryScanStagingResultsEntity aFile = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", size: 10, ticks: 100, needsRehash: true);
|
||||
LibraryScanStagingResultsEntity bFile = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/b.epub", size: 20, ticks: 200, needsRehash: true);
|
||||
LibraryScanStagingResultsEntity noRehash = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/z.epub", needsRehash: false);
|
||||
_context.LibraryScanStagingResults.AddRange(aFile, bFile, noRehash);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<HashedFileSystemFileDto>> result = await _sut.GetFilesToHashPageAsync(scanId, null, 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Equal("/books/a.epub", result.Value[0].Path);
|
||||
Assert.Equal("/books/b.epub", result.Value[1].Path);
|
||||
Assert.Equal(10, result.Value[0].Size);
|
||||
Assert.Equal(20, result.Value[1].Size);
|
||||
Assert.Equal(100, result.Value[0].Ticks);
|
||||
Assert.Equal(200, result.Value[1].Ticks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFilesToHashPageAsync_WhenLastPathProvided_ShouldReturnOnlyResultsAfterIt()
|
||||
{
|
||||
// Arrange
|
||||
(_, _, Guid scanId) = await SeedScanGraphAsync();
|
||||
LibraryScanStagingResultsEntity aFile = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", needsRehash: true);
|
||||
LibraryScanStagingResultsEntity bFile = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/b.epub", needsRehash: true);
|
||||
_context.LibraryScanStagingResults.AddRange(aFile, bFile);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<HashedFileSystemFileDto>> result = await _sut.GetFilesToHashPageAsync(scanId, "/books/a.epub", 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
HashedFileSystemFileDto retrievedFile = Assert.Single(result.Value);
|
||||
Assert.Equal("/books/b.epub", retrievedFile.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateFileHashesAsync_WhenCalled_ShouldUpdateTheContentHashes()
|
||||
{
|
||||
// Arrange
|
||||
(_, _, Guid scanId) = await SeedScanGraphAsync();
|
||||
LibraryScanStagingResultsEntity firstStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", contentHash: 111);
|
||||
LibraryScanStagingResultsEntity secondStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/b.epub", contentHash: 222);
|
||||
_context.LibraryScanStagingResults.AddRange(firstStaging, secondStaging);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
List<HashedFileSystemFileDto> hashedFiles =
|
||||
[
|
||||
new HashedFileSystemFileDto { Path = "/books/a.epub", Size = 10, Ticks = 100, CurrentHash = 999, OldHash = 0 },
|
||||
new HashedFileSystemFileDto { Path = "/books/b.epub", Size = 20, Ticks = 200, CurrentHash = 888, OldHash = 0 }
|
||||
];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateFileHashesAsync(scanId, hashedFiles, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
List<LibraryScanStagingResultsEntity> stagingResults = await _context.LibraryScanStagingResults.AsNoTracking().OrderBy(staging => staging.Path).ToListAsync();
|
||||
Assert.Equal(999UL, stagingResults[0].ContentHash);
|
||||
Assert.Equal(888UL, stagingResults[1].ContentHash);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearForScanAsync_WhenCalled_ShouldRemoveOnlyTheStagingResultsOfTheScan()
|
||||
{
|
||||
// Arrange
|
||||
(UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
|
||||
LibraryScanEntity otherScan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Completed);
|
||||
_context.LibraryScans.Add(otherScan);
|
||||
LibraryScanStagingResultsEntity stagingOfScan = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId);
|
||||
LibraryScanStagingResultsEntity stagingOfOtherScan = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: otherScan.Id);
|
||||
_context.LibraryScanStagingResults.AddRange(stagingOfScan, stagingOfOtherScan);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.ClearForScanAsync(scanId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.False(await _context.LibraryScanStagingResults.AsNoTracking().AnyAsync(staging => staging.LibraryScanId == scanId));
|
||||
Assert.Single(await _context.LibraryScanStagingResults.AsNoTracking().Where(staging => staging.LibraryScanId == otherScan.Id).ToListAsync());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the user, media library and media library scan required by the foreign keys of the staging table.
|
||||
/// </summary>
|
||||
/// <returns>The seeded user, media library and scan Id.</returns>
|
||||
private async Task<(UserEntity User, LibraryEntity Library, Guid ScanId)> SeedScanGraphAsync()
|
||||
{
|
||||
UserEntity user = _userEntityFixture.Create();
|
||||
_context.Users.Add(user);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(userId: user.Id);
|
||||
_context.Libraries.Add(library);
|
||||
LibraryScanEntity scan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Running);
|
||||
_context.LibraryScans.Add(scan);
|
||||
await _context.SaveChangesAsync();
|
||||
return (user, library, scan.Id);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
_anchorConnection.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.UoW;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LuminaDbContext"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LuminaDbContextTests : IDisposable
|
||||
{
|
||||
private readonly string _connectionString;
|
||||
private readonly SqliteConnection _anchorConnection;
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaDbContextTests"/> class.
|
||||
/// </summary>
|
||||
public LuminaDbContextTests()
|
||||
{
|
||||
_connectionString = $"Data Source=luminadataccess-dbcontext-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared";
|
||||
_anchorConnection = new SqliteConnection(_connectionString);
|
||||
_anchorConnection.Open();
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connectionString).Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnModelCreating_WhenCalled_ShouldApplyAllEntityConfigurationsFromTheAssembly()
|
||||
{
|
||||
// Arrange
|
||||
IModel model = _context.Model;
|
||||
|
||||
// Act
|
||||
string[] tableNames = [.. model.GetEntityTypes().Select(entityType => entityType.GetTableName()).OfType<string>().OrderBy(name => name)];
|
||||
|
||||
// Assert
|
||||
// The count assertion fails when a table is added or removed, reminding to update the assertions below.
|
||||
Assert.Equal(23, tableNames.Length);
|
||||
Assert.Contains("Books", tableNames);
|
||||
Assert.Contains("Users", tableNames);
|
||||
Assert.Contains("UserSettings", tableNames);
|
||||
Assert.Contains("Roles", tableNames);
|
||||
Assert.Contains("Permissions", tableNames);
|
||||
Assert.Contains("UserRoles", tableNames);
|
||||
Assert.Contains("UserPermissions", tableNames);
|
||||
Assert.Contains("RolePermissions", tableNames);
|
||||
Assert.Contains("Libraries", tableNames);
|
||||
Assert.Contains("LibraryScans", tableNames);
|
||||
Assert.Contains("LibraryScanResults", tableNames);
|
||||
Assert.Contains("LibraryScanSnapshots", tableNames);
|
||||
Assert.Contains("LibraryScanStagingResults", tableNames);
|
||||
Assert.Contains("DirectoryScanFingerprints", tableNames);
|
||||
Assert.Contains("Plugins", tableNames);
|
||||
Assert.Contains("LibraryMetadataProviderConfigurations", tableNames);
|
||||
Assert.Contains("Tags", tableNames);
|
||||
Assert.Contains("Genres", tableNames);
|
||||
Assert.Contains("LibraryContentLocations", tableNames);
|
||||
Assert.Contains("BookTags", tableNames);
|
||||
Assert.Contains("BookGenres", tableNames);
|
||||
Assert.Contains("BookRatings", tableNames);
|
||||
Assert.Contains("BookISBNs", tableNames);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveChangesAsync_WhenAddingBook_ShouldPersistItToTheDatabase()
|
||||
{
|
||||
// Arrange
|
||||
_context.Database.EnsureCreated();
|
||||
BookEntity book = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = Guid.NewGuid(),
|
||||
Path = "/books/test.epub",
|
||||
Title = "Test Book",
|
||||
MetadataStatus = MetadataStatus.Pending,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedBy = null
|
||||
};
|
||||
_context.Books.Add(book);
|
||||
|
||||
// Act
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
BookEntity? retrievedBook = await _context.Books.FindAsync(book.Id);
|
||||
Assert.NotNull(retrievedBook);
|
||||
Assert.Equal("Test Book", retrievedBook!.Title);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
_anchorConnection.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user