mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 18:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+208
@@ -0,0 +1,208 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AlbumConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumConfigurationTests : IDisposable
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AlbumConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public AlbumConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Albums", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(AlbumEntity.Id));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty artistIdProperty = entityType.GetProperty(nameof(AlbumEntity.ArtistId));
|
||||
IProperty libraryIdProperty = entityType.GetProperty(nameof(AlbumEntity.LibraryId));
|
||||
IProperty titleProperty = entityType.GetProperty(nameof(AlbumEntity.Title));
|
||||
IProperty originalTitleProperty = entityType.GetProperty(nameof(AlbumEntity.OriginalTitle));
|
||||
IProperty descriptionProperty = entityType.GetProperty(nameof(AlbumEntity.Description));
|
||||
IProperty releaseCountryProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseCountry));
|
||||
IProperty releaseTypeProperty = entityType.FindNavigation(nameof(AlbumEntity.ReleaseTypes))!.TargetEntityType.GetProperty(nameof(AlbumReleaseTypeEntity.ReleaseType));
|
||||
IProperty releaseStatusProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseStatus));
|
||||
IProperty mediaFormatProperty = entityType.GetProperty(nameof(AlbumEntity.MediaFormat));
|
||||
IProperty barcodeProperty = entityType.GetProperty(nameof(AlbumEntity.Barcode));
|
||||
IProperty catalogNumberProperty = entityType.FindNavigation(nameof(AlbumEntity.CatalogNumbers))!.TargetEntityType.GetProperty(nameof(AlbumCatalogNumberEntity.CatalogNumber));
|
||||
IProperty languageCodeProperty = entityType.GetProperty(nameof(AlbumEntity.LanguageCode));
|
||||
|
||||
// Assert
|
||||
Assert.False(artistIdProperty.IsNullable);
|
||||
Assert.False(libraryIdProperty.IsNullable);
|
||||
Assert.False(titleProperty.IsNullable);
|
||||
Assert.Equal(255, titleProperty.GetMaxLength());
|
||||
Assert.Equal(255, originalTitleProperty.GetMaxLength());
|
||||
Assert.Equal(2000, descriptionProperty.GetMaxLength());
|
||||
Assert.Equal(typeof(ReleaseCountry?), releaseCountryProperty.ClrType);
|
||||
Assert.Equal("TEXT", releaseCountryProperty.GetColumnType());
|
||||
Assert.Equal(2, releaseCountryProperty.GetMaxLength());
|
||||
Assert.Equal(typeof(MusicReleaseType), releaseTypeProperty.ClrType);
|
||||
Assert.Equal("TEXT", releaseTypeProperty.GetColumnType());
|
||||
Assert.Equal(50, releaseTypeProperty.GetMaxLength());
|
||||
Assert.Equal(typeof(MusicReleaseStatus?), releaseStatusProperty.ClrType);
|
||||
Assert.Equal("TEXT", releaseStatusProperty.GetColumnType());
|
||||
Assert.Equal(50, releaseStatusProperty.GetMaxLength());
|
||||
Assert.Equal(typeof(MusicMediaFormat?), mediaFormatProperty.ClrType);
|
||||
Assert.Equal("TEXT", mediaFormatProperty.GetColumnType());
|
||||
Assert.Equal(50, mediaFormatProperty.GetMaxLength());
|
||||
Assert.Equal(13, barcodeProperty.GetMaxLength());
|
||||
Assert.Equal(50, catalogNumberProperty.GetMaxLength());
|
||||
Assert.True(languageCodeProperty.IsNullable);
|
||||
Assert.Equal(typeof(string), languageCodeProperty.ClrType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureArtistRelationshipWithCascadeDelete()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
List<IForeignKey> foreignKeys = [.. entityType.GetForeignKeys()];
|
||||
|
||||
// Assert
|
||||
IForeignKey artistForeignKey = Assert.Single(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(ArtistEntity));
|
||||
Assert.Equal(nameof(AlbumEntity.ArtistId), artistForeignKey.Properties.Single().Name);
|
||||
Assert.Equal(DeleteBehavior.Cascade, artistForeignKey.DeleteBehavior);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureOwnedAlbumRatings()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType ratingEntityType = _context.Model.GetEntityTypes()
|
||||
.Single(entityType => entityType.IsOwned() && entityType.ClrType == typeof(AudioRatingEntity) && entityType.GetTableName() == "AlbumRatings");
|
||||
|
||||
// Act
|
||||
string? tableName = ratingEntityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = ratingEntityType.FindPrimaryKey()!.Properties;
|
||||
IProperty valueProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.Value));
|
||||
IProperty maxValueProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.MaxValue));
|
||||
IProperty voteCountProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.VoteCount));
|
||||
IProperty sourceProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.Source));
|
||||
|
||||
// Assert
|
||||
Assert.Equal("AlbumRatings", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
Assert.Equal("decimal(3,2)", valueProperty.GetColumnType());
|
||||
Assert.False(valueProperty.IsNullable);
|
||||
Assert.Equal("decimal(3,2)", maxValueProperty.GetColumnType());
|
||||
Assert.False(maxValueProperty.IsNullable);
|
||||
Assert.True(voteCountProperty.IsNullable);
|
||||
Assert.Equal(typeof(AudioRatingSource?), sourceProperty.ClrType);
|
||||
Assert.Equal("TEXT", sourceProperty.GetColumnType());
|
||||
Assert.Equal(50, sourceProperty.GetMaxLength());
|
||||
Assert.True(sourceProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureManyToManyJoinTablesForTagsAndGenres()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
List<ISkipNavigation> skipNavigations = [.. entityType.GetSkipNavigations()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, skipNavigations.Count);
|
||||
ISkipNavigation tagsNavigation = Assert.Single(skipNavigations, navigation => navigation.Name == nameof(AlbumEntity.Tags));
|
||||
Assert.Equal("AlbumTags", tagsNavigation.JoinEntityType.GetTableName());
|
||||
Assert.Equal(["AlbumId", "TagId"], tagsNavigation.JoinEntityType.FindPrimaryKey()!.Properties.Select(property => property.Name));
|
||||
ISkipNavigation genresNavigation = Assert.Single(skipNavigations, navigation => navigation.Name == nameof(AlbumEntity.Genres));
|
||||
Assert.Equal("AlbumGenres", genresNavigation.JoinEntityType.GetTableName());
|
||||
Assert.Equal(["AlbumId", "GenreId"], genresNavigation.JoinEntityType.FindPrimaryKey()!.Properties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureIndexesOnArtistIdTitleAndLibraryIdTitle()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
List<IIndex> indexes = [.. entityType.GetIndexes()];
|
||||
|
||||
// Assert
|
||||
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(AlbumEntity.ArtistId), nameof(AlbumEntity.Title)]));
|
||||
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(AlbumEntity.LibraryId), nameof(AlbumEntity.Title)]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(AlbumEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(AlbumEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(AlbumEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(AlbumEntity.UpdatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
Assert.True(updatedOnUtcProperty.IsNullable);
|
||||
Assert.True(updatedByProperty.IsNullable);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the database context.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ArtistConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ArtistConfigurationTests : IDisposable
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ArtistConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public ArtistConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Artists", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(ArtistEntity.Id));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty libraryIdProperty = entityType.GetProperty(nameof(ArtistEntity.LibraryId));
|
||||
IProperty nameProperty = entityType.GetProperty(nameof(ArtistEntity.Name));
|
||||
IProperty websiteProperty = entityType.GetProperty(nameof(ArtistEntity.Website));
|
||||
IProperty musicBrainzArtistIdProperty = entityType.GetProperty(nameof(ArtistEntity.MusicBrainzArtistId));
|
||||
|
||||
// Assert
|
||||
Assert.False(libraryIdProperty.IsNullable);
|
||||
Assert.False(nameProperty.IsNullable);
|
||||
Assert.Equal(255, nameProperty.GetMaxLength());
|
||||
Assert.True(websiteProperty.IsNullable);
|
||||
Assert.Equal(2048, websiteProperty.GetMaxLength());
|
||||
Assert.True(musicBrainzArtistIdProperty.IsNullable);
|
||||
Assert.Equal(typeof(Guid?), musicBrainzArtistIdProperty.ClrType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureContributorsRelationshipWithCascadeDelete()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType contributorEntityType = _context.Model.FindEntityType(typeof(ArtistContributorEntity))!;
|
||||
|
||||
// Act
|
||||
List<IForeignKey> foreignKeys = [.. contributorEntityType.GetForeignKeys()];
|
||||
|
||||
// Assert
|
||||
IForeignKey artistForeignKey = Assert.Single(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(ArtistEntity));
|
||||
Assert.Equal(nameof(ArtistContributorEntity.ArtistId), artistForeignKey.Properties.Single().Name);
|
||||
Assert.Equal(DeleteBehavior.Cascade, artistForeignKey.DeleteBehavior);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnLibraryIdAndName()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!;
|
||||
|
||||
// Act
|
||||
List<IIndex> indexes = [.. entityType.GetIndexes()];
|
||||
|
||||
// Assert
|
||||
IIndex uniquenessIndex = Assert.Single(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(ArtistEntity.LibraryId), nameof(ArtistEntity.Name)]));
|
||||
Assert.True(uniquenessIndex.IsUnique);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(ArtistEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(ArtistEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(ArtistEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(ArtistEntity.UpdatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
Assert.True(updatedOnUtcProperty.IsNullable);
|
||||
Assert.True(updatedByProperty.IsNullable);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the database context.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookConfigurationTests
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public BookConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Books", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty titleProperty = entityType.GetProperty(nameof(BookEntity.Title));
|
||||
IProperty pathProperty = entityType.GetProperty(nameof(BookEntity.Path));
|
||||
IProperty formatProperty = entityType.GetProperty(nameof(BookEntity.Format));
|
||||
IProperty metadataStatusProperty = entityType.GetProperty(nameof(BookEntity.MetadataStatus));
|
||||
|
||||
// Assert
|
||||
Assert.False(titleProperty.IsNullable);
|
||||
Assert.Equal(255, titleProperty.GetMaxLength());
|
||||
Assert.False(pathProperty.IsNullable);
|
||||
Assert.Equal(2048, pathProperty.GetMaxLength());
|
||||
Assert.Equal(typeof(BookFormat?), formatProperty.ClrType);
|
||||
Assert.Equal("TEXT", formatProperty.GetColumnType());
|
||||
Assert.Equal(typeof(MetadataStatus), metadataStatusProperty.ClrType);
|
||||
Assert.Equal("TEXT", metadataStatusProperty.GetColumnType());
|
||||
Assert.Equal(20, metadataStatusProperty.GetMaxLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureOwnedTypesForRatingsAndIsbns()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!;
|
||||
|
||||
// Act
|
||||
List<IEntityType> ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, ownedTypes.Count);
|
||||
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(BookRatingEntity) && ownedType.GetTableName() == "BookRatings");
|
||||
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(IsbnEntity) && ownedType.GetTableName() == "BookISBNs");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureManyToManyJoinTablesForTagsAndGenres()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!;
|
||||
|
||||
// Act
|
||||
List<ISkipNavigation> skipNavigations = [.. entityType.GetSkipNavigations()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, skipNavigations.Count);
|
||||
Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(BookEntity.Tags) && navigation.JoinEntityType.GetTableName() == "BookTags");
|
||||
Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(BookEntity.Genres) && navigation.JoinEntityType.GetTableName() == "BookGenres");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureIndexesOnLibraryIdAndPath()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!;
|
||||
|
||||
// Act
|
||||
List<IIndex> indexes = [.. entityType.GetIndexes()];
|
||||
|
||||
// Assert
|
||||
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(BookEntity.LibraryId), nameof(BookEntity.Path)]));
|
||||
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(BookEntity.LibraryId), nameof(BookEntity.MetadataStatus)]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(BookEntity.CreatedOnUtc));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(BookEntity.UpdatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
|
||||
}
|
||||
}
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FavoriteConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteConfigurationTests
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FavoriteConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public FavoriteConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits.
|
||||
/// </summary>
|
||||
private IModel DesignTimeModel => _context.GetService<IDesignTimeModel>().Model;
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Favorites", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldNotGenerateTheIdValueAndOrderItFirst()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(FavoriteEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(FavoriteEntity.Id));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
|
||||
Assert.Equal(0, idProperty.GetColumnOrder());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureCascadingRelationshipWithUser()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
|
||||
|
||||
// Act
|
||||
IForeignKey userForeignKey = Assert.Single(entityType.GetForeignKeys());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(UserEntity), userForeignKey.PrincipalEntityType.ClrType);
|
||||
Assert.Equal(nameof(FavoriteEntity.UserId), userForeignKey.Properties[0].Name);
|
||||
Assert.Equal(DeleteBehavior.Cascade, userForeignKey.DeleteBehavior);
|
||||
Assert.True(userForeignKey.IsRequired);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldStoreTheMediaKindAsABoundedRequiredString()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty mediaKindProperty = entityType.GetProperty(nameof(FavoriteEntity.MediaKind));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(FavoriteMediaKind), mediaKindProperty.ClrType);
|
||||
Assert.Equal(typeof(string), mediaKindProperty.GetTypeMapping().Converter!.ProviderClrType);
|
||||
Assert.Equal("TEXT", mediaKindProperty.GetColumnType());
|
||||
Assert.Equal(20, mediaKindProperty.GetMaxLength());
|
||||
Assert.False(mediaKindProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheRequiredColumns()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty userIdProperty = entityType.GetProperty(nameof(FavoriteEntity.UserId));
|
||||
IProperty mediaItemIdProperty = entityType.GetProperty(nameof(FavoriteEntity.MediaItemId));
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(FavoriteEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(FavoriteEntity.CreatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.False(userIdProperty.IsNullable);
|
||||
Assert.False(mediaItemIdProperty.IsNullable);
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheNullableAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(FavoriteEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(FavoriteEntity.UpdatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.True(updatedOnUtcProperty.IsNullable);
|
||||
Assert.True(updatedByProperty.IsNullable);
|
||||
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
|
||||
Assert.Null(updatedByProperty.GetDefaultValue());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheUniqueBusinessKeyIndex()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
|
||||
|
||||
// Act
|
||||
IIndex businessKeyIndex = Assert.Single(
|
||||
entityType.GetIndexes(),
|
||||
index => index.Properties.Select(property => property.Name).SequenceEqual(
|
||||
[
|
||||
nameof(FavoriteEntity.UserId),
|
||||
nameof(FavoriteEntity.MediaKind),
|
||||
nameof(FavoriteEntity.MediaItemId)
|
||||
]));
|
||||
|
||||
// Assert
|
||||
Assert.True(businessKeyIndex.IsUnique);
|
||||
Assert.Equal(3, businessKeyIndex.Properties.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheListingIndexes()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(FavoriteEntity))!;
|
||||
|
||||
// Act
|
||||
IIndex everyKindListingIndex = Assert.Single(
|
||||
entityType.GetIndexes(),
|
||||
index => index.Properties.Select(property => property.Name).SequenceEqual(
|
||||
[
|
||||
nameof(FavoriteEntity.UserId),
|
||||
nameof(FavoriteEntity.CreatedOnUtc)
|
||||
]));
|
||||
IIndex oneKindListingIndex = Assert.Single(
|
||||
entityType.GetIndexes(),
|
||||
index => index.Properties.Select(property => property.Name).SequenceEqual(
|
||||
[
|
||||
nameof(FavoriteEntity.UserId),
|
||||
nameof(FavoriteEntity.MediaKind),
|
||||
nameof(FavoriteEntity.CreatedOnUtc)
|
||||
]));
|
||||
|
||||
// Assert
|
||||
Assert.False(everyKindListingIndex.IsUnique);
|
||||
Assert.False(oneKindListingIndex.IsUnique);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldOrderEveryColumnAsConfigured()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(FavoriteEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(FavoriteEntity.Id));
|
||||
IProperty userIdProperty = entityType.GetProperty(nameof(FavoriteEntity.UserId));
|
||||
IProperty mediaKindProperty = entityType.GetProperty(nameof(FavoriteEntity.MediaKind));
|
||||
IProperty mediaItemIdProperty = entityType.GetProperty(nameof(FavoriteEntity.MediaItemId));
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(FavoriteEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(FavoriteEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(FavoriteEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(FavoriteEntity.UpdatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(0, idProperty.GetColumnOrder());
|
||||
Assert.Equal(1, userIdProperty.GetColumnOrder());
|
||||
Assert.Equal(2, mediaKindProperty.GetColumnOrder());
|
||||
Assert.Equal(3, mediaItemIdProperty.GetColumnOrder());
|
||||
Assert.Equal(4, createdOnUtcProperty.GetColumnOrder());
|
||||
Assert.Equal(5, createdByProperty.GetColumnOrder());
|
||||
Assert.Equal(6, updatedOnUtcProperty.GetColumnOrder());
|
||||
Assert.Equal(7, updatedByProperty.GetColumnOrder());
|
||||
}
|
||||
}
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryBookReaderConfigurationConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryBookReaderConfigurationConfigurationTests
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryBookReaderConfigurationConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryBookReaderConfigurationConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryBookReaderConfigurationEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("LibraryBookReaderConfigurations", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureScalarPropertiesAsRequired()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryBookReaderConfigurationEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty libraryIdProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.LibraryId));
|
||||
IProperty pluginIdProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.PluginId));
|
||||
IProperty isEnabledProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.IsEnabled));
|
||||
|
||||
// Assert
|
||||
Assert.False(libraryIdProperty.IsNullable);
|
||||
Assert.False(pluginIdProperty.IsNullable);
|
||||
Assert.False(isEnabledProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureIndexOnLibraryIdAndPluginId()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryBookReaderConfigurationEntity))!;
|
||||
|
||||
// Act
|
||||
IIndex index = Assert.Single(entityType.GetIndexes());
|
||||
|
||||
// Assert
|
||||
Assert.Equal([nameof(LibraryBookReaderConfigurationEntity.LibraryId), nameof(LibraryBookReaderConfigurationEntity.PluginId)], index.Properties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryBookReaderConfigurationEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.CreatedOnUtc));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.UpdatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
|
||||
}
|
||||
}
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryConfigurationTests
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits.
|
||||
/// </summary>
|
||||
private IModel DesignTimeModel => _context.GetService<IDesignTimeModel>().Model;
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Libraries", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty titleProperty = entityType.GetProperty(nameof(LibraryEntity.Title));
|
||||
IProperty libraryTypeProperty = entityType.GetProperty(nameof(LibraryEntity.LibraryType));
|
||||
IProperty isEnabledProperty = entityType.GetProperty(nameof(LibraryEntity.IsEnabled));
|
||||
IProperty downloadMetadataProperty = entityType.GetProperty(nameof(LibraryEntity.CanDownloadMetadataFromWeb));
|
||||
IProperty shouldTrackConsumptionProgressProperty = entityType.GetProperty(nameof(LibraryEntity.ShouldTrackConsumptionProgress));
|
||||
IProperty completionThresholdPercentageProperty = entityType.GetProperty(nameof(LibraryEntity.CompletionThresholdPercentage));
|
||||
IProperty isContentOnSsdProperty = entityType.GetProperty(nameof(LibraryEntity.IsContentOnSsd));
|
||||
|
||||
// Assert
|
||||
Assert.False(titleProperty.IsNullable);
|
||||
Assert.Equal(255, titleProperty.GetMaxLength());
|
||||
Assert.Equal(typeof(LibraryType), libraryTypeProperty.ClrType);
|
||||
Assert.Equal("TEXT", libraryTypeProperty.GetColumnType());
|
||||
Assert.Equal(true, isEnabledProperty.GetDefaultValue());
|
||||
Assert.Equal(true, downloadMetadataProperty.GetDefaultValue());
|
||||
Assert.Equal(typeof(bool), shouldTrackConsumptionProgressProperty.ClrType);
|
||||
Assert.False(shouldTrackConsumptionProgressProperty.IsNullable);
|
||||
Assert.Equal(false, shouldTrackConsumptionProgressProperty.GetDefaultValue());
|
||||
Assert.Equal(typeof(int?), completionThresholdPercentageProperty.ClrType);
|
||||
Assert.True(completionThresholdPercentageProperty.IsNullable);
|
||||
Assert.Null(completionThresholdPercentageProperty.GetDefaultValue());
|
||||
Assert.Equal(typeof(bool), isContentOnSsdProperty.ClrType);
|
||||
Assert.False(isContentOnSsdProperty.IsNullable);
|
||||
Assert.Equal(false, isContentOnSsdProperty.GetDefaultValue());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureSsdContentColumnOrder()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty isContentOnSsdProperty = entityType.GetProperty(nameof(LibraryEntity.IsContentOnSsd));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(18, isContentOnSsdProperty.GetColumnOrder());
|
||||
Assert.Equal(nameof(LibraryEntity.IsContentOnSsd), isContentOnSsdProperty.GetColumnName());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigurePathTemplateFingerprint()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty fingerprintProperty = entityType.GetProperty(nameof(LibraryEntity.PathTemplateFingerprint));
|
||||
|
||||
// Assert
|
||||
Assert.True(fingerprintProperty.IsNullable);
|
||||
Assert.Equal(typeof(string), fingerprintProperty.ClrType);
|
||||
Assert.Equal(64, fingerprintProperty.GetMaxLength());
|
||||
Assert.Equal(11, fingerprintProperty.GetColumnOrder());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureConsumptionSettingsColumnOrders()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty shouldTrackProperty = entityType.GetProperty(nameof(LibraryEntity.ShouldTrackConsumptionProgress));
|
||||
IProperty completionThresholdProperty = entityType.GetProperty(nameof(LibraryEntity.CompletionThresholdPercentage));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(16, shouldTrackProperty.GetColumnOrder());
|
||||
Assert.Equal(17, completionThresholdProperty.GetColumnOrder());
|
||||
Assert.Equal(nameof(LibraryEntity.ShouldTrackConsumptionProgress), shouldTrackProperty.GetColumnName());
|
||||
Assert.Equal(nameof(LibraryEntity.CompletionThresholdPercentage), completionThresholdProperty.GetColumnName());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldMapConsumptionSettingsAsScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty shouldTrackConsumptionProgressProperty = entityType.GetProperty(nameof(LibraryEntity.ShouldTrackConsumptionProgress));
|
||||
IProperty completionThresholdPercentageProperty = entityType.GetProperty(nameof(LibraryEntity.CompletionThresholdPercentage));
|
||||
List<INavigation> navigations = [.. entityType.GetNavigations()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(LibraryEntity), shouldTrackConsumptionProgressProperty.DeclaringType.ClrType);
|
||||
Assert.Equal(typeof(LibraryEntity), completionThresholdPercentageProperty.DeclaringType.ClrType);
|
||||
Assert.DoesNotContain(navigations, navigation => navigation.Name == nameof(LibraryEntity.ShouldTrackConsumptionProgress));
|
||||
Assert.DoesNotContain(navigations, navigation => navigation.Name == nameof(LibraryEntity.CompletionThresholdPercentage));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldMapConsumptionSettingsToTheirOwnColumns()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
|
||||
|
||||
// Act
|
||||
string shouldTrackConsumptionProgressColumnName = entityType.GetProperty(nameof(LibraryEntity.ShouldTrackConsumptionProgress)).GetColumnName();
|
||||
string completionThresholdPercentageColumnName = entityType.GetProperty(nameof(LibraryEntity.CompletionThresholdPercentage)).GetColumnName();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(nameof(LibraryEntity.ShouldTrackConsumptionProgress), shouldTrackConsumptionProgressColumnName);
|
||||
Assert.Equal(nameof(LibraryEntity.CompletionThresholdPercentage), completionThresholdPercentageColumnName);
|
||||
Assert.NotEqual(shouldTrackConsumptionProgressColumnName, completionThresholdPercentageColumnName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureOwnedContentLocations()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
|
||||
|
||||
// Act
|
||||
IEntityType contentLocationType = Assert.Single(
|
||||
_context.Model.GetEntityTypes(),
|
||||
ownedType => ownedType.IsOwned()
|
||||
&& ownedType.ClrType == typeof(LibraryContentLocationEntity)
|
||||
&& ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(LibraryContentLocationEntity), contentLocationType.ClrType);
|
||||
Assert.Equal("LibraryContentLocations", contentLocationType.GetTableName());
|
||||
Assert.Equal(260, contentLocationType.GetProperty(nameof(LibraryContentLocationEntity.Path)).GetMaxLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureOwnedPathTemplateParts()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
|
||||
|
||||
// Act
|
||||
IEntityType partEntityType = Assert.Single(
|
||||
_context.Model.GetEntityTypes(),
|
||||
ownedType => ownedType.IsOwned()
|
||||
&& ownedType.ClrType == typeof(LibraryPathTemplatePartEntity)
|
||||
&& ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name);
|
||||
IForeignKey ownershipForeignKey = partEntityType.FindOwnership()!;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("LibraryPathTemplateParts", partEntityType.GetTableName());
|
||||
Assert.Equal(["Id"], partEntityType.FindPrimaryKey()!.Properties.Select(property => property.Name));
|
||||
|
||||
Assert.Equal(typeof(LibraryEntity), ownershipForeignKey.PrincipalEntityType.ClrType);
|
||||
Assert.Equal(["LibraryId"], ownershipForeignKey.Properties.Select(property => property.Name));
|
||||
Assert.True(ownershipForeignKey.IsRequired);
|
||||
|
||||
IIndex uniqueIndex = Assert.Single(
|
||||
partEntityType.GetIndexes(),
|
||||
index => index.Properties.Select(property => property.Name).SequenceEqual(["LibraryId", nameof(LibraryPathTemplatePartEntity.Position)]));
|
||||
Assert.True(uniqueIndex.IsUnique);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureOwnedPathTemplatePartColumns()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType partEntityType = DesignTimeModel.GetEntityTypes()
|
||||
.Single(entityType => entityType.IsOwned()
|
||||
&& entityType.ClrType == typeof(LibraryPathTemplatePartEntity)
|
||||
&& entityType.GetTableName() == "LibraryPathTemplateParts");
|
||||
|
||||
// Act
|
||||
IProperty positionProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Position));
|
||||
IProperty kindProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Kind));
|
||||
IProperty representationProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Representation));
|
||||
IProperty isOptionalProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.IsOptional));
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Position", positionProperty.GetColumnName());
|
||||
Assert.False(positionProperty.IsNullable);
|
||||
|
||||
Assert.Equal(typeof(LibraryPathPartKind), kindProperty.ClrType);
|
||||
Assert.Equal(typeof(string), kindProperty.GetTypeMapping().Converter!.ProviderClrType);
|
||||
Assert.Equal("TEXT", kindProperty.GetColumnType());
|
||||
Assert.Equal(32, kindProperty.GetMaxLength());
|
||||
Assert.False(kindProperty.IsNullable);
|
||||
|
||||
Assert.Equal(512, representationProperty.GetMaxLength());
|
||||
Assert.False(representationProperty.IsNullable);
|
||||
|
||||
Assert.Equal(typeof(bool), isOptionalProperty.ClrType);
|
||||
Assert.False(isOptionalProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureRelationships()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
|
||||
|
||||
// Act
|
||||
IForeignKey userForeignKey = Assert.Single(entityType.GetForeignKeys());
|
||||
List<INavigation> navigations = [.. entityType.GetNavigations()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(DeleteBehavior.Cascade, userForeignKey.DeleteBehavior);
|
||||
Assert.Equal(nameof(LibraryEntity.UserId), userForeignKey.Properties[0].Name);
|
||||
Assert.Contains(navigations, navigation => navigation.Name == nameof(LibraryEntity.User));
|
||||
Assert.Contains(navigations, navigation => navigation.Name == nameof(LibraryEntity.LibraryScans) && navigation.IsCollection);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.CreatedOnUtc));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.UpdatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditColumnOrders()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(LibraryEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(LibraryEntity.UpdatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(12, createdOnUtcProperty.GetColumnOrder());
|
||||
Assert.Equal(13, createdByProperty.GetColumnOrder());
|
||||
Assert.Equal(14, updatedOnUtcProperty.GetColumnOrder());
|
||||
Assert.Equal(15, updatedByProperty.GetColumnOrder());
|
||||
}
|
||||
}
|
||||
+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));
|
||||
}
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaConsumptionRecordConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaConsumptionRecordConfigurationTests
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaConsumptionRecordConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public MediaConsumptionRecordConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("MediaConsumptionRecords", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureCascadingRelationshipWithUser()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
|
||||
|
||||
// Act
|
||||
IForeignKey userForeignKey = Assert.Single(entityType.GetForeignKeys());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(UserEntity), userForeignKey.PrincipalEntityType.ClrType);
|
||||
Assert.Equal(nameof(MediaConsumptionRecordEntity.UserId), userForeignKey.Properties[0].Name);
|
||||
Assert.Equal(DeleteBehavior.Cascade, userForeignKey.DeleteBehavior);
|
||||
Assert.True(userForeignKey.IsRequired);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldStoreTheKindAndStatusAsBoundedStrings()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty mediaKindProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.MediaKind));
|
||||
IProperty statusProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.Status));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(MediaKind), mediaKindProperty.ClrType);
|
||||
Assert.Equal(typeof(string), mediaKindProperty.GetTypeMapping().Converter!.ProviderClrType);
|
||||
Assert.Equal("TEXT", mediaKindProperty.GetColumnType());
|
||||
Assert.Equal(20, mediaKindProperty.GetMaxLength());
|
||||
Assert.False(mediaKindProperty.IsNullable);
|
||||
|
||||
Assert.Equal(typeof(ConsumptionStatus), statusProperty.ClrType);
|
||||
Assert.Equal(typeof(string), statusProperty.GetTypeMapping().Converter!.ProviderClrType);
|
||||
Assert.Equal("TEXT", statusProperty.GetColumnType());
|
||||
Assert.Equal(20, statusProperty.GetMaxLength());
|
||||
Assert.False(statusProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldStoreTheOptionalPositionKindAsABoundedString()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty lastPositionKindProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.LastPositionKind));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(MediaPositionKind?), lastPositionKindProperty.ClrType);
|
||||
Assert.Equal(typeof(string), lastPositionKindProperty.GetTypeMapping().Converter!.ProviderClrType);
|
||||
Assert.Equal("TEXT", lastPositionKindProperty.GetColumnType());
|
||||
Assert.Equal(20, lastPositionKindProperty.GetMaxLength());
|
||||
Assert.True(lastPositionKindProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheRequiredColumns()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty mediaKindProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.MediaKind));
|
||||
IProperty statusProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.Status));
|
||||
IProperty startedOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.StartedOnUtc));
|
||||
IProperty lastActivityOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.LastActivityOnUtc));
|
||||
IProperty consumedDurationMillisecondsProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.ConsumedDurationMilliseconds));
|
||||
IProperty lastProgressFractionProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.LastProgressFraction));
|
||||
IProperty consecutivePagesReadProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.ConsecutivePagesRead));
|
||||
IProperty versionProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.Version));
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.CreatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.False(mediaKindProperty.IsNullable);
|
||||
Assert.False(statusProperty.IsNullable);
|
||||
Assert.False(startedOnUtcProperty.IsNullable);
|
||||
Assert.False(lastActivityOnUtcProperty.IsNullable);
|
||||
Assert.False(consumedDurationMillisecondsProperty.IsNullable);
|
||||
Assert.False(lastProgressFractionProperty.IsNullable);
|
||||
Assert.False(consecutivePagesReadProperty.IsNullable);
|
||||
Assert.False(versionProperty.IsNullable);
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheOptionalColumns()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty endedOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.EndedOnUtc));
|
||||
IProperty lastPositionKindProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.LastPositionKind));
|
||||
IProperty lastPositionTimeOffsetMillisecondsProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.LastPositionTimeOffsetMilliseconds));
|
||||
IProperty lastPositionLocationProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.LastPositionLocation));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.UpdatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.True(endedOnUtcProperty.IsNullable);
|
||||
Assert.True(lastPositionKindProperty.IsNullable);
|
||||
Assert.True(lastPositionTimeOffsetMillisecondsProperty.IsNullable);
|
||||
Assert.True(lastPositionLocationProperty.IsNullable);
|
||||
Assert.True(updatedOnUtcProperty.IsNullable);
|
||||
Assert.True(updatedByProperty.IsNullable);
|
||||
Assert.Equal(4096, lastPositionLocationProperty.GetMaxLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheConsecutivePagesReadDefault()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty consecutivePagesReadProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.ConsecutivePagesRead));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(0, consecutivePagesReadProperty.GetDefaultValue());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheVersionAsAConcurrencyToken()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty versionProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.Version));
|
||||
|
||||
// Assert
|
||||
Assert.True(versionProperty.IsConcurrencyToken);
|
||||
Assert.False(versionProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheHistoryAndStatisticsIndexes()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
|
||||
|
||||
// Act
|
||||
IIndex historyIndex = Assert.Single(
|
||||
entityType.GetIndexes(),
|
||||
index => index.Properties.Select(property => property.Name).SequenceEqual(
|
||||
[
|
||||
nameof(MediaConsumptionRecordEntity.UserId),
|
||||
nameof(MediaConsumptionRecordEntity.MediaKind),
|
||||
nameof(MediaConsumptionRecordEntity.MediaItemId),
|
||||
nameof(MediaConsumptionRecordEntity.LastActivityOnUtc)
|
||||
]));
|
||||
IIndex statisticsIndex = Assert.Single(
|
||||
entityType.GetIndexes(),
|
||||
index => index.Properties.Select(property => property.Name).SequenceEqual(
|
||||
[
|
||||
nameof(MediaConsumptionRecordEntity.UserId),
|
||||
nameof(MediaConsumptionRecordEntity.MediaKind),
|
||||
nameof(MediaConsumptionRecordEntity.StartedOnUtc)
|
||||
]));
|
||||
|
||||
// Assert
|
||||
Assert.False(historyIndex.IsUnique);
|
||||
Assert.False(statisticsIndex.IsUnique);
|
||||
// The two configured indexes are distinct, and neither of them is the foreign key index on the owner.
|
||||
Assert.NotSame(historyIndex, statisticsIndex);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaConsumptionRecordEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(MediaConsumptionRecordEntity.UpdatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
|
||||
Assert.Null(updatedByProperty.GetDefaultValue());
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaResumePointConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaResumePointConfigurationTests
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaResumePointConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public MediaResumePointConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("MediaResumePoints", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureCascadingRelationshipWithUser()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
|
||||
|
||||
// Act
|
||||
IForeignKey userForeignKey = Assert.Single(entityType.GetForeignKeys());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(UserEntity), userForeignKey.PrincipalEntityType.ClrType);
|
||||
Assert.Equal(nameof(MediaResumePointEntity.UserId), userForeignKey.Properties[0].Name);
|
||||
Assert.Equal(DeleteBehavior.Cascade, userForeignKey.DeleteBehavior);
|
||||
Assert.True(userForeignKey.IsRequired);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldStoreTheMediaKindAsABoundedString()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty mediaKindProperty = entityType.GetProperty(nameof(MediaResumePointEntity.MediaKind));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(MediaKind), mediaKindProperty.ClrType);
|
||||
Assert.Equal(typeof(string), mediaKindProperty.GetTypeMapping().Converter!.ProviderClrType);
|
||||
Assert.Equal("TEXT", mediaKindProperty.GetColumnType());
|
||||
Assert.Equal(20, mediaKindProperty.GetMaxLength());
|
||||
Assert.False(mediaKindProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldStoreThePositionKindAsABoundedRequiredString()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty lastPositionKindProperty = entityType.GetProperty(nameof(MediaResumePointEntity.LastPositionKind));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(MediaPositionKind), lastPositionKindProperty.ClrType);
|
||||
Assert.Equal(typeof(string), lastPositionKindProperty.GetTypeMapping().Converter!.ProviderClrType);
|
||||
Assert.Equal("TEXT", lastPositionKindProperty.GetColumnType());
|
||||
Assert.Equal(20, lastPositionKindProperty.GetMaxLength());
|
||||
Assert.False(lastPositionKindProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldBoundThePositionLocationLength()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty lastPositionLocationProperty = entityType.GetProperty(nameof(MediaResumePointEntity.LastPositionLocation));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(string), lastPositionLocationProperty.ClrType);
|
||||
Assert.Equal(4096, lastPositionLocationProperty.GetMaxLength());
|
||||
Assert.True(lastPositionLocationProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheRequiredColumns()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty mediaKindProperty = entityType.GetProperty(nameof(MediaResumePointEntity.MediaKind));
|
||||
IProperty lastPositionKindProperty = entityType.GetProperty(nameof(MediaResumePointEntity.LastPositionKind));
|
||||
IProperty lastProgressFractionProperty = entityType.GetProperty(nameof(MediaResumePointEntity.LastProgressFraction));
|
||||
IProperty lastConsumedOnUtcProperty = entityType.GetProperty(nameof(MediaResumePointEntity.LastConsumedOnUtc));
|
||||
IProperty versionProperty = entityType.GetProperty(nameof(MediaResumePointEntity.Version));
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(MediaResumePointEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(MediaResumePointEntity.CreatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.False(mediaKindProperty.IsNullable);
|
||||
Assert.False(lastPositionKindProperty.IsNullable);
|
||||
Assert.False(lastProgressFractionProperty.IsNullable);
|
||||
Assert.False(lastConsumedOnUtcProperty.IsNullable);
|
||||
Assert.False(versionProperty.IsNullable);
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheVersionAsAConcurrencyToken()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty versionProperty = entityType.GetProperty(nameof(MediaResumePointEntity.Version));
|
||||
|
||||
// Assert
|
||||
Assert.True(versionProperty.IsConcurrencyToken);
|
||||
Assert.False(versionProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheUniqueBusinessKeyIndex()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
|
||||
|
||||
// Act
|
||||
IIndex businessKeyIndex = Assert.Single(
|
||||
entityType.GetIndexes(),
|
||||
index => index.Properties.Select(property => property.Name).SequenceEqual(
|
||||
[
|
||||
nameof(MediaResumePointEntity.UserId),
|
||||
nameof(MediaResumePointEntity.MediaKind),
|
||||
nameof(MediaResumePointEntity.MediaItemId)
|
||||
]));
|
||||
|
||||
// Assert
|
||||
Assert.True(businessKeyIndex.IsUnique);
|
||||
Assert.Equal(3, businessKeyIndex.Properties.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MediaResumePointEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(MediaResumePointEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(MediaResumePointEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(MediaResumePointEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(MediaResumePointEntity.UpdatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
|
||||
Assert.Null(updatedByProperty.GetDefaultValue());
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicArtworkConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtworkConfigurationTests : IDisposable
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtworkConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public MusicArtworkConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("MusicArtwork", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Id));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty ownerTypeProperty = entityType.GetProperty(nameof(MusicArtworkEntity.OwnerType));
|
||||
IProperty ownerIdProperty = entityType.GetProperty(nameof(MusicArtworkEntity.OwnerId));
|
||||
IProperty artworkTypeProperty = entityType.GetProperty(nameof(MusicArtworkEntity.ArtworkType));
|
||||
IProperty ordinalProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Ordinal));
|
||||
IProperty fileNameProperty = entityType.GetProperty(nameof(MusicArtworkEntity.FileName));
|
||||
IProperty contentHashProperty = entityType.GetProperty(nameof(MusicArtworkEntity.ContentHash));
|
||||
IProperty statusProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Status));
|
||||
IProperty providerProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Provider));
|
||||
IProperty lastUpdateUtcProperty = entityType.GetProperty(nameof(MusicArtworkEntity.LastUpdateUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(ownerTypeProperty.IsNullable);
|
||||
Assert.Equal(typeof(MusicArtworkOwnerType), ownerTypeProperty.ClrType);
|
||||
Assert.Equal("TEXT", ownerTypeProperty.GetColumnType());
|
||||
Assert.Equal(50, ownerTypeProperty.GetMaxLength());
|
||||
Assert.False(ownerIdProperty.IsNullable);
|
||||
Assert.False(artworkTypeProperty.IsNullable);
|
||||
Assert.Equal(typeof(ArtworkType), artworkTypeProperty.ClrType);
|
||||
Assert.Equal("TEXT", artworkTypeProperty.GetColumnType());
|
||||
Assert.Equal(50, artworkTypeProperty.GetMaxLength());
|
||||
Assert.False(ordinalProperty.IsNullable);
|
||||
Assert.True(fileNameProperty.IsNullable);
|
||||
Assert.Equal(2048, fileNameProperty.GetMaxLength());
|
||||
Assert.False(contentHashProperty.IsNullable);
|
||||
Assert.False(statusProperty.IsNullable);
|
||||
Assert.Equal(typeof(ArtworkStatus), statusProperty.ClrType);
|
||||
Assert.Equal("TEXT", statusProperty.GetColumnType());
|
||||
Assert.Equal(20, statusProperty.GetMaxLength());
|
||||
Assert.True(providerProperty.IsNullable);
|
||||
Assert.Equal(100, providerProperty.GetMaxLength());
|
||||
Assert.True(lastUpdateUtcProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureUniqueOwnerArtworkIndex()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!;
|
||||
|
||||
// Act
|
||||
List<IIndex> indexes = [.. entityType.GetIndexes()];
|
||||
|
||||
// Assert
|
||||
IIndex uniqueIndex = Assert.Single(indexes, index => index.IsUnique);
|
||||
Assert.Equal(
|
||||
[nameof(MusicArtworkEntity.OwnerType), nameof(MusicArtworkEntity.OwnerId), nameof(MusicArtworkEntity.ArtworkType), nameof(MusicArtworkEntity.Ordinal)],
|
||||
uniqueIndex.Properties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureIndexOnStatus()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!;
|
||||
|
||||
// Act
|
||||
List<IIndex> indexes = [.. entityType.GetIndexes()];
|
||||
|
||||
// Assert
|
||||
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(MusicArtworkEntity.Status)]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(MusicArtworkEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(MusicArtworkEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(MusicArtworkEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(MusicArtworkEntity.UpdatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
Assert.True(updatedOnUtcProperty.IsNullable);
|
||||
Assert.True(updatedByProperty.IsNullable);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the database context.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicLibraryScanItemMetadataConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicLibraryScanItemMetadataConfigurationTests : IDisposable
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicLibraryScanItemMetadataConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public MusicLibraryScanItemMetadataConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("MusicLibraryScanItemMetadata", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.Id));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureRequiredScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty libraryScanIdProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.LibraryScanId));
|
||||
IProperty libraryIdProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.LibraryId));
|
||||
IProperty pathProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.Path));
|
||||
|
||||
// Assert
|
||||
Assert.False(libraryScanIdProperty.IsNullable);
|
||||
Assert.False(libraryIdProperty.IsNullable);
|
||||
Assert.False(pathProperty.IsNullable);
|
||||
Assert.Equal(2048, pathProperty.GetMaxLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureOptionalScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty artistNameProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ArtistName));
|
||||
IProperty releaseTypeProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReleaseType));
|
||||
IProperty releaseYearProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReleaseYear));
|
||||
IProperty releaseNameProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReleaseName));
|
||||
IProperty trackTitleProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.TrackTitle));
|
||||
IProperty audioCodecProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.AudioCodec));
|
||||
IProperty workTitleProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.WorkTitle));
|
||||
IProperty acoustIdProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.AcoustId));
|
||||
|
||||
// Assert
|
||||
Assert.True(artistNameProperty.IsNullable);
|
||||
Assert.Equal(255, artistNameProperty.GetMaxLength());
|
||||
Assert.True(releaseTypeProperty.IsNullable);
|
||||
Assert.Equal(typeof(MusicReleaseType?), releaseTypeProperty.ClrType);
|
||||
Assert.Equal("TEXT", releaseTypeProperty.GetColumnType());
|
||||
Assert.Equal(50, releaseTypeProperty.GetMaxLength());
|
||||
Assert.True(releaseYearProperty.IsNullable);
|
||||
Assert.Equal(255, releaseNameProperty.GetMaxLength());
|
||||
Assert.Equal(255, trackTitleProperty.GetMaxLength());
|
||||
Assert.Equal(50, audioCodecProperty.GetMaxLength());
|
||||
Assert.Equal(255, workTitleProperty.GetMaxLength());
|
||||
Assert.Equal(64, acoustIdProperty.GetMaxLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureReplayGainDecimalPrecision()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty trackGainProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainTrackGain));
|
||||
IProperty trackPeakProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainTrackPeak));
|
||||
IProperty albumGainProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainAlbumGain));
|
||||
IProperty albumPeakProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainAlbumPeak));
|
||||
|
||||
// Assert
|
||||
Assert.Equal("decimal(8,2)", trackGainProperty.GetColumnType());
|
||||
Assert.Equal("decimal(8,6)", trackPeakProperty.GetColumnType());
|
||||
Assert.Equal("decimal(8,2)", albumGainProperty.GetColumnType());
|
||||
Assert.Equal("decimal(8,6)", albumPeakProperty.GetColumnType());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureMoodsAsPrimitiveCollection()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty moodsProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.Moods));
|
||||
|
||||
// Assert
|
||||
Assert.True(moodsProperty.IsPrimitiveCollection);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureUniqueScanIdPathIndex()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
|
||||
|
||||
// Act
|
||||
List<IIndex> indexes = [.. entityType.GetIndexes()];
|
||||
|
||||
// Assert
|
||||
IIndex uniqueIndex = Assert.Single(indexes, index => index.IsUnique);
|
||||
Assert.Equal(
|
||||
[nameof(MusicLibraryScanItemMetadataEntity.LibraryScanId), nameof(MusicLibraryScanItemMetadataEntity.Path)],
|
||||
uniqueIndex.Properties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the database context.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
}
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PlaylistConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistConfigurationTests
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaylistConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public PlaylistConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits.
|
||||
/// </summary>
|
||||
private IModel DesignTimeModel => _context.GetService<IDesignTimeModel>().Model;
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Playlists", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldNotGenerateTheIdValueAndOrderItFirst()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(PlaylistEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(PlaylistEntity.Id));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
|
||||
Assert.Equal(0, idProperty.GetColumnOrder());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureCascadingRelationshipWithUser()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
|
||||
|
||||
// Act
|
||||
IForeignKey userForeignKey = Assert.Single(entityType.GetForeignKeys());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(UserEntity), userForeignKey.PrincipalEntityType.ClrType);
|
||||
Assert.Equal(nameof(PlaylistEntity.UserId), userForeignKey.Properties[0].Name);
|
||||
Assert.Equal(DeleteBehavior.Cascade, userForeignKey.DeleteBehavior);
|
||||
Assert.True(userForeignKey.IsRequired);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldStoreThePlaylistTypeAsABoundedRequiredString()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty typeProperty = entityType.GetProperty(nameof(PlaylistEntity.Type));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(PlaylistType), typeProperty.ClrType);
|
||||
Assert.Equal(typeof(string), typeProperty.GetTypeMapping().Converter!.ProviderClrType);
|
||||
Assert.Equal("TEXT", typeProperty.GetColumnType());
|
||||
Assert.Equal(20, typeProperty.GetMaxLength());
|
||||
Assert.False(typeProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheNameAndDescriptionLengths()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty nameProperty = entityType.GetProperty(nameof(PlaylistEntity.Name));
|
||||
IProperty descriptionProperty = entityType.GetProperty(nameof(PlaylistEntity.Description));
|
||||
|
||||
// Assert
|
||||
Assert.False(nameProperty.IsNullable);
|
||||
Assert.Equal(255, nameProperty.GetMaxLength());
|
||||
Assert.True(descriptionProperty.IsNullable);
|
||||
Assert.Equal(2000, descriptionProperty.GetMaxLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheRequiredColumns()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty userIdProperty = entityType.GetProperty(nameof(PlaylistEntity.UserId));
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(PlaylistEntity.CreatedBy));
|
||||
IProperty entryCountProperty = entityType.GetProperty(nameof(PlaylistEntity.EntryCount));
|
||||
|
||||
// Assert
|
||||
Assert.False(userIdProperty.IsNullable);
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
Assert.False(entryCountProperty.IsNullable);
|
||||
Assert.Equal(0, entryCountProperty.GetDefaultValue());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheNullableAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(PlaylistEntity.UpdatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.True(updatedOnUtcProperty.IsNullable);
|
||||
Assert.True(updatedByProperty.IsNullable);
|
||||
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
|
||||
Assert.Null(updatedByProperty.GetDefaultValue());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheVersionAsAConcurrencyTokenStartingAtZero()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty versionProperty = entityType.GetProperty(nameof(PlaylistEntity.Version));
|
||||
|
||||
// Assert
|
||||
Assert.True(versionProperty.IsConcurrencyToken);
|
||||
Assert.Equal(0L, versionProperty.GetDefaultValue());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheEntriesRelationshipWithCascadeDelete()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
|
||||
IEntityType entryEntityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
|
||||
|
||||
// Act
|
||||
INavigation entriesNavigation = Assert.Single(entityType.GetNavigations());
|
||||
IForeignKey entriesForeignKey = Assert.Single(entryEntityType.GetForeignKeys());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(nameof(PlaylistEntity.Entries), entriesNavigation.Name);
|
||||
Assert.Equal(typeof(PlaylistEntryEntity), entriesNavigation.TargetEntityType.ClrType);
|
||||
Assert.True(entriesNavigation.IsCollection);
|
||||
Assert.Equal(typeof(PlaylistEntity), entriesForeignKey.PrincipalEntityType.ClrType);
|
||||
Assert.Equal(nameof(PlaylistEntryEntity.PlaylistId), entriesForeignKey.Properties[0].Name);
|
||||
Assert.Equal(DeleteBehavior.Cascade, entriesForeignKey.DeleteBehavior);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheMostRecentActivityIndex()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!;
|
||||
|
||||
// Act
|
||||
IIndex activityIndex = Assert.Single(
|
||||
entityType.GetIndexes(),
|
||||
index => index.Properties.Select(property => property.Name).SequenceEqual(
|
||||
[
|
||||
nameof(PlaylistEntity.UserId),
|
||||
nameof(PlaylistEntity.UpdatedOnUtc)
|
||||
]));
|
||||
|
||||
// Assert
|
||||
Assert.False(activityIndex.IsUnique);
|
||||
Assert.Equal(2, activityIndex.Properties.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldOrderEveryColumnAsConfigured()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(PlaylistEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(PlaylistEntity.Id));
|
||||
IProperty userIdProperty = entityType.GetProperty(nameof(PlaylistEntity.UserId));
|
||||
IProperty nameProperty = entityType.GetProperty(nameof(PlaylistEntity.Name));
|
||||
IProperty descriptionProperty = entityType.GetProperty(nameof(PlaylistEntity.Description));
|
||||
IProperty typeProperty = entityType.GetProperty(nameof(PlaylistEntity.Type));
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(PlaylistEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(PlaylistEntity.UpdatedBy));
|
||||
IProperty versionProperty = entityType.GetProperty(nameof(PlaylistEntity.Version));
|
||||
IProperty entryCountProperty = entityType.GetProperty(nameof(PlaylistEntity.EntryCount));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(0, idProperty.GetColumnOrder());
|
||||
Assert.Equal(1, userIdProperty.GetColumnOrder());
|
||||
Assert.Equal(2, nameProperty.GetColumnOrder());
|
||||
Assert.Equal(3, descriptionProperty.GetColumnOrder());
|
||||
Assert.Equal(4, typeProperty.GetColumnOrder());
|
||||
Assert.Equal(5, createdOnUtcProperty.GetColumnOrder());
|
||||
Assert.Equal(6, createdByProperty.GetColumnOrder());
|
||||
Assert.Equal(7, updatedOnUtcProperty.GetColumnOrder());
|
||||
Assert.Equal(8, updatedByProperty.GetColumnOrder());
|
||||
Assert.Equal(9, versionProperty.GetColumnOrder());
|
||||
Assert.Equal(10, entryCountProperty.GetColumnOrder());
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PlaylistEntryConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistEntryConfigurationTests
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaylistEntryConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public PlaylistEntryConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits.
|
||||
/// </summary>
|
||||
private IModel DesignTimeModel => _context.GetService<IDesignTimeModel>().Model;
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("PlaylistEntries", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldNotGenerateTheIdValueAndOrderItFirst()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(PlaylistEntryEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.Id));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
|
||||
Assert.Equal(0, idProperty.GetColumnOrder());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldStoreTheMediaItemTypeAsABoundedRequiredString()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty mediaItemTypeProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.MediaItemType));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(PlaylistMediaItemType), mediaItemTypeProperty.ClrType);
|
||||
Assert.Equal(typeof(string), mediaItemTypeProperty.GetTypeMapping().Converter!.ProviderClrType);
|
||||
Assert.Equal("TEXT", mediaItemTypeProperty.GetColumnType());
|
||||
Assert.Equal(20, mediaItemTypeProperty.GetMaxLength());
|
||||
Assert.False(mediaItemTypeProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheRequiredColumns()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty playlistIdProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.PlaylistId));
|
||||
IProperty mediaItemIdProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.MediaItemId));
|
||||
IProperty positionProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.Position));
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.CreatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.False(playlistIdProperty.IsNullable);
|
||||
Assert.False(mediaItemIdProperty.IsNullable);
|
||||
Assert.False(positionProperty.IsNullable);
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheNullableAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.UpdatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.True(updatedOnUtcProperty.IsNullable);
|
||||
Assert.True(updatedByProperty.IsNullable);
|
||||
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
|
||||
Assert.Null(updatedByProperty.GetDefaultValue());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheUniquePositionIndex()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
|
||||
|
||||
// Act
|
||||
IIndex positionIndex = Assert.Single(
|
||||
entityType.GetIndexes(),
|
||||
index => index.Properties.Select(property => property.Name).SequenceEqual(
|
||||
[
|
||||
nameof(PlaylistEntryEntity.PlaylistId),
|
||||
nameof(PlaylistEntryEntity.Position)
|
||||
]));
|
||||
|
||||
// Assert
|
||||
Assert.True(positionIndex.IsUnique);
|
||||
Assert.Equal(2, positionIndex.Properties.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureTheMediaItemLookupIndex()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
|
||||
|
||||
// Act
|
||||
IIndex mediaItemIndex = Assert.Single(
|
||||
entityType.GetIndexes(),
|
||||
index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(PlaylistEntryEntity.MediaItemId)]));
|
||||
|
||||
// Assert
|
||||
Assert.False(mediaItemIndex.IsUnique);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldOwnTheEntryThroughThePlaylistWithCascadeDelete()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
|
||||
|
||||
// Act
|
||||
IForeignKey playlistForeignKey = Assert.Single(entityType.GetForeignKeys());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(PlaylistEntity), playlistForeignKey.PrincipalEntityType.ClrType);
|
||||
Assert.Equal(nameof(PlaylistEntryEntity.PlaylistId), playlistForeignKey.Properties[0].Name);
|
||||
Assert.Equal(DeleteBehavior.Cascade, playlistForeignKey.DeleteBehavior);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldNotReferenceTheMediaItemByAForeignKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!;
|
||||
|
||||
// Act
|
||||
List<IForeignKey> foreignKeys = [.. entityType.GetForeignKeys()];
|
||||
|
||||
// Assert
|
||||
// The media item is referenced by Id only, so an entry survives the deletion of the item it references.
|
||||
Assert.DoesNotContain(foreignKeys, foreignKey => foreignKey.Properties.Any(property => property.Name == nameof(PlaylistEntryEntity.MediaItemId)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldOrderEveryColumnAsConfigured()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(PlaylistEntryEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.Id));
|
||||
IProperty playlistIdProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.PlaylistId));
|
||||
IProperty mediaItemIdProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.MediaItemId));
|
||||
IProperty mediaItemTypeProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.MediaItemType));
|
||||
IProperty positionProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.Position));
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.UpdatedOnUtc));
|
||||
IProperty updatedByProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.UpdatedBy));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(0, idProperty.GetColumnOrder());
|
||||
Assert.Equal(1, playlistIdProperty.GetColumnOrder());
|
||||
Assert.Equal(2, mediaItemIdProperty.GetColumnOrder());
|
||||
Assert.Equal(3, mediaItemTypeProperty.GetColumnOrder());
|
||||
Assert.Equal(4, positionProperty.GetColumnOrder());
|
||||
Assert.Equal(5, createdOnUtcProperty.GetColumnOrder());
|
||||
Assert.Equal(6, createdByProperty.GetColumnOrder());
|
||||
Assert.Equal(7, updatedOnUtcProperty.GetColumnOrder());
|
||||
Assert.Equal(8, updatedByProperty.GetColumnOrder());
|
||||
}
|
||||
}
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TrackConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackConfigurationTests : IDisposable
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TrackConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public TrackConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Tracks", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(TrackEntity.Id));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty pathProperty = entityType.GetProperty(nameof(TrackEntity.Path));
|
||||
IProperty titleProperty = entityType.GetProperty(nameof(TrackEntity.Title));
|
||||
IProperty originalTitleProperty = entityType.GetProperty(nameof(TrackEntity.OriginalTitle));
|
||||
IProperty descriptionProperty = entityType.GetProperty(nameof(TrackEntity.Description));
|
||||
IProperty releaseCountryProperty = entityType.GetProperty(nameof(TrackEntity.ReleaseCountry));
|
||||
IProperty scriptProperty = entityType.GetProperty(nameof(TrackEntity.Script));
|
||||
IProperty keyProperty = entityType.GetProperty(nameof(TrackEntity.Key));
|
||||
IProperty audioCodecProperty = entityType.GetProperty(nameof(TrackEntity.AudioCodec));
|
||||
IProperty workProperty = entityType.GetProperty(nameof(TrackEntity.WorkTitle));
|
||||
|
||||
// Assert
|
||||
Assert.False(pathProperty.IsNullable);
|
||||
Assert.Equal(2048, pathProperty.GetMaxLength());
|
||||
Assert.False(titleProperty.IsNullable);
|
||||
Assert.Equal(255, titleProperty.GetMaxLength());
|
||||
Assert.Equal(255, originalTitleProperty.GetMaxLength());
|
||||
Assert.Equal(2000, descriptionProperty.GetMaxLength());
|
||||
Assert.Equal(typeof(ReleaseCountry?), releaseCountryProperty.ClrType);
|
||||
Assert.Equal("TEXT", releaseCountryProperty.GetColumnType());
|
||||
Assert.Equal(2, releaseCountryProperty.GetMaxLength());
|
||||
Assert.Equal(50, scriptProperty.GetMaxLength());
|
||||
Assert.Equal(typeof(MusicKey?), keyProperty.ClrType);
|
||||
Assert.Equal("TEXT", keyProperty.GetColumnType());
|
||||
Assert.Equal(50, keyProperty.GetMaxLength());
|
||||
Assert.Equal(50, audioCodecProperty.GetMaxLength());
|
||||
Assert.Equal(255, workProperty.GetMaxLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAlbumRelationshipWithCascadeDelete()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
List<IForeignKey> foreignKeys = [.. entityType.GetForeignKeys()];
|
||||
|
||||
// Assert
|
||||
IForeignKey albumForeignKey = Assert.Single(foreignKeys);
|
||||
Assert.Equal(nameof(TrackEntity.AlbumId), albumForeignKey.Properties.Single().Name);
|
||||
Assert.Equal(typeof(AlbumEntity), albumForeignKey.PrincipalEntityType.ClrType);
|
||||
Assert.Equal(DeleteBehavior.Cascade, albumForeignKey.DeleteBehavior);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureOwnedTypesForMoodsIsrcsAndRatings()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
List<IEntityType> ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(5, ownedTypes.Count);
|
||||
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackMoodEntity) && ownedType.GetTableName() == "TrackMoods");
|
||||
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackIsrcEntity) && ownedType.GetTableName() == "TrackIsrcs");
|
||||
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackWorkLanguageEntity) && ownedType.GetTableName() == "TrackWorkLanguages");
|
||||
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackWorkIswcEntity) && ownedType.GetTableName() == "TrackWorkIswcs");
|
||||
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(AudioRatingEntity) && ownedType.GetTableName() == "TrackRatings");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureManyToManyJoinTablesForTagsAndGenres()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
List<ISkipNavigation> skipNavigations = [.. entityType.GetSkipNavigations()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, skipNavigations.Count);
|
||||
Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(TrackEntity.Tags) && navigation.JoinEntityType.GetTableName() == "TrackTags");
|
||||
Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(TrackEntity.Genres) && navigation.JoinEntityType.GetTableName() == "TrackGenres");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureIndexesOnAlbumIdTrackNumberAndLibraryIdPath()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
List<IIndex> indexes = [.. entityType.GetIndexes()];
|
||||
|
||||
// Assert
|
||||
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackEntity.AlbumId), nameof(TrackEntity.TrackNumber)]));
|
||||
IIndex pathIndex = Assert.Single(indexes.Where(index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackEntity.LibraryId), nameof(TrackEntity.Path)])));
|
||||
Assert.True(pathIndex.IsUnique);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(TrackEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(TrackEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(TrackEntity.UpdatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
Assert.True(updatedOnUtcProperty.IsNullable);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the database context.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TrackContributorConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackContributorConfigurationTests : IDisposable
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TrackContributorConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public TrackContributorConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("TrackContributors", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty idProperty = entityType.GetProperty(nameof(TrackContributorEntity.Id));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty trackIdProperty = entityType.GetProperty(nameof(TrackContributorEntity.TrackId));
|
||||
IProperty mediaContributorIdProperty = entityType.GetProperty(nameof(TrackContributorEntity.MediaContributorId));
|
||||
IProperty roleProperty = entityType.GetProperty(nameof(TrackContributorEntity.Role));
|
||||
|
||||
// Assert
|
||||
Assert.False(trackIdProperty.IsNullable);
|
||||
Assert.False(mediaContributorIdProperty.IsNullable);
|
||||
Assert.False(roleProperty.IsNullable);
|
||||
Assert.Equal(typeof(MediaContributorRole), roleProperty.ClrType);
|
||||
Assert.Equal("TEXT", roleProperty.GetColumnType());
|
||||
Assert.Equal(50, roleProperty.GetMaxLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureUniqueIndexAndContributorLookupIndex()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
|
||||
|
||||
// Act
|
||||
List<IIndex> indexes = [.. entityType.GetIndexes()];
|
||||
|
||||
// Assert
|
||||
IIndex uniquenessIndex = Assert.Single(indexes.Where(index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackContributorEntity.TrackId), nameof(TrackContributorEntity.MediaContributorId), nameof(TrackContributorEntity.Role)])));
|
||||
Assert.True(uniquenessIndex.IsUnique);
|
||||
Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackContributorEntity.MediaContributorId)]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(TrackContributorEntity.CreatedOnUtc));
|
||||
IProperty createdByProperty = entityType.GetProperty(nameof(TrackContributorEntity.CreatedBy));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(TrackContributorEntity.UpdatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.False(createdByProperty.IsNullable);
|
||||
Assert.True(updatedOnUtcProperty.IsNullable);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the database context.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
}
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UserSettingsConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserSettingsConfigurationTests
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserSettingsConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public UserSettingsConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits.
|
||||
/// </summary>
|
||||
private IModel DesignTimeModel => _context.GetService<IDesignTimeModel>().Model;
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!;
|
||||
|
||||
// Act
|
||||
string? tableName = entityType.GetTableName();
|
||||
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("UserSettings", tableName);
|
||||
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureScalarPropertiesAsRequired()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty userIdProperty = entityType.GetProperty(nameof(UserSettingsEntity.UserId));
|
||||
IProperty isPaginationEnabledProperty = entityType.GetProperty(nameof(UserSettingsEntity.IsPaginationEnabled));
|
||||
IProperty itemsPerPageProperty = entityType.GetProperty(nameof(UserSettingsEntity.ItemsPerPage));
|
||||
IProperty ignoreThePrefixProperty = entityType.GetProperty(nameof(UserSettingsEntity.ShouldIgnoreThePrefixForAlphaPicker));
|
||||
IProperty vuMeterOrientationProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterOrientation));
|
||||
IProperty vuMeterSegmentCountProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterSegmentCount));
|
||||
IProperty vuMeterSegmentGapProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterSegmentGap));
|
||||
IProperty vuMeterMediumThresholdProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterMediumThreshold));
|
||||
IProperty vuMeterHighThresholdProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterHighThreshold));
|
||||
IProperty vuMeterShowPeakProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterShowPeak));
|
||||
IProperty vuMeterPeakHoldDurationProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterPeakHoldDurationInMilliseconds));
|
||||
IProperty vuMeterReleasePerSecondProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterReleasePerSecond));
|
||||
IProperty vuMeterPeakReleasePerSecondProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterPeakReleasePerSecond));
|
||||
|
||||
// Assert
|
||||
Assert.False(userIdProperty.IsNullable);
|
||||
Assert.False(isPaginationEnabledProperty.IsNullable);
|
||||
Assert.False(itemsPerPageProperty.IsNullable);
|
||||
Assert.False(ignoreThePrefixProperty.IsNullable);
|
||||
Assert.False(vuMeterOrientationProperty.IsNullable);
|
||||
Assert.False(vuMeterSegmentCountProperty.IsNullable);
|
||||
Assert.False(vuMeterSegmentGapProperty.IsNullable);
|
||||
Assert.False(vuMeterMediumThresholdProperty.IsNullable);
|
||||
Assert.False(vuMeterHighThresholdProperty.IsNullable);
|
||||
Assert.False(vuMeterShowPeakProperty.IsNullable);
|
||||
Assert.False(vuMeterPeakHoldDurationProperty.IsNullable);
|
||||
Assert.False(vuMeterReleasePerSecondProperty.IsNullable);
|
||||
Assert.False(vuMeterPeakReleasePerSecondProperty.IsNullable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureOneToOneRelationshipWithUser()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!;
|
||||
|
||||
// Act
|
||||
IForeignKey foreignKey = Assert.Single(entityType.GetForeignKeys());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior);
|
||||
Assert.Equal(typeof(UserEntity), foreignKey.PrincipalEntityType.ClrType);
|
||||
Assert.Equal(nameof(UserSettingsEntity.UserId), foreignKey.Properties[0].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnUserId()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!;
|
||||
|
||||
// Act
|
||||
IIndex userIdIndex = Assert.Single(entityType.GetIndexes());
|
||||
|
||||
// Assert
|
||||
Assert.True(userIdIndex.IsUnique);
|
||||
Assert.Equal(nameof(UserSettingsEntity.UserId), userIdIndex.Properties[0].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(UserSettingsEntity.CreatedOnUtc));
|
||||
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(UserSettingsEntity.UpdatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(createdOnUtcProperty.IsNullable);
|
||||
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenApplied_ShouldConfigureVuMeterAndPlaybackStateColumnOrders()
|
||||
{
|
||||
// Arrange
|
||||
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(UserSettingsEntity))!;
|
||||
|
||||
// Act
|
||||
IProperty vuMeterOrientationProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterOrientation));
|
||||
IProperty vuMeterSegmentCountProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterSegmentCount));
|
||||
IProperty vuMeterSegmentGapProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterSegmentGap));
|
||||
IProperty vuMeterMediumThresholdProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterMediumThreshold));
|
||||
IProperty vuMeterHighThresholdProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterHighThreshold));
|
||||
IProperty vuMeterShowPeakProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterShowPeak));
|
||||
IProperty vuMeterPeakHoldDurationProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterPeakHoldDurationInMilliseconds));
|
||||
IProperty vuMeterReleasePerSecondProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterReleasePerSecond));
|
||||
IProperty vuMeterPeakReleasePerSecondProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterPeakReleasePerSecond));
|
||||
IProperty volumeProperty = entityType.GetProperty(nameof(UserSettingsEntity.Volume));
|
||||
IProperty isMutedProperty = entityType.GetProperty(nameof(UserSettingsEntity.IsMuted));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(19, vuMeterOrientationProperty.GetColumnOrder());
|
||||
Assert.Equal(20, vuMeterSegmentCountProperty.GetColumnOrder());
|
||||
Assert.Equal(21, vuMeterSegmentGapProperty.GetColumnOrder());
|
||||
Assert.Equal(22, vuMeterMediumThresholdProperty.GetColumnOrder());
|
||||
Assert.Equal(23, vuMeterHighThresholdProperty.GetColumnOrder());
|
||||
Assert.Equal(24, vuMeterShowPeakProperty.GetColumnOrder());
|
||||
Assert.Equal(25, vuMeterPeakHoldDurationProperty.GetColumnOrder());
|
||||
Assert.Equal(26, vuMeterReleasePerSecondProperty.GetColumnOrder());
|
||||
Assert.Equal(27, vuMeterPeakReleasePerSecondProperty.GetColumnOrder());
|
||||
Assert.Equal(28, volumeProperty.GetColumnOrder());
|
||||
Assert.Equal(29, isMutedProperty.GetColumnOrder());
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Common.Dapper;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Dapper;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SqliteGuidTypeHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SqliteGuidTypeHandlerTests
|
||||
{
|
||||
private readonly SqliteGuidTypeHandler _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SqliteGuidTypeHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public SqliteGuidTypeHandlerTests()
|
||||
{
|
||||
_sut = new SqliteGuidTypeHandler();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetValue_WhenCalled_ShouldStoreTheGuidAsItsUpperCaseTextRepresentation()
|
||||
{
|
||||
// Arrange
|
||||
IDbDataParameter parameter = Substitute.For<IDbDataParameter>();
|
||||
Guid guid = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
_sut.SetValue(parameter, guid);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(guid.ToString().ToUpperInvariant(), (string?)parameter.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenValueIsGuid_ShouldReturnTheSameGuid()
|
||||
{
|
||||
// Arrange
|
||||
Guid guid = Guid.NewGuid();
|
||||
object value = guid;
|
||||
|
||||
// Act
|
||||
Guid parsed = _sut.Parse(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(guid, parsed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenValueIsGuidText_ShouldReturnTheParsedGuid()
|
||||
{
|
||||
// Arrange
|
||||
Guid guid = Guid.NewGuid();
|
||||
object value = guid.ToString();
|
||||
|
||||
// Act
|
||||
Guid parsed = _sut.Parse(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(guid, parsed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenValueIsNotValidGuidText_ShouldThrowFormatException()
|
||||
{
|
||||
// Arrange
|
||||
object value = "not-a-guid";
|
||||
|
||||
// Act
|
||||
Action act = () => _sut.Parse(value);
|
||||
|
||||
// Assert
|
||||
Assert.Throws<FormatException>(act);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.DataAccess.Common.DependencyInjection;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.DataAccess.UnitTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DataAccessLayerServices"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DataAccessLayerServicesTests
|
||||
{
|
||||
[Fact]
|
||||
public void AddDataAccessLayerServices_WhenBasePathExists_ShouldAddServices()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
string basePath = Path.GetTempPath(); // Use a real existing path.
|
||||
|
||||
// Act
|
||||
DataAccessLayerServices.AddDataAccessLayerServices(services);
|
||||
|
||||
// Assert
|
||||
Assert.Contains(services, sd => sd.ServiceType == typeof(LuminaDbContext));
|
||||
Assert.Contains(services, sd => sd.ServiceType == typeof(IUnitOfWork) && sd.ImplementationType == typeof(UnitOfWork));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddDataAccessLayerServices_ShouldRegisterDbContextWithCorrectConnectionString()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
DataAccessLayerServices.AddDataAccessLayerServices(services);
|
||||
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
|
||||
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
|
||||
|
||||
// Assert
|
||||
ServiceDescriptor? descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
|
||||
Assert.NotNull(descriptor);
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
LuminaDbContext? context = serviceProvider.GetService<LuminaDbContext>();
|
||||
|
||||
Assert.NotNull(context);
|
||||
Assert.Contains("Lumina.db", context.Database.GetDbConnection().ConnectionString);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddDataAccessLayerServices_WhenCalled_ShouldExposeRepositoriesThroughUnitOfWork()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
DataAccessLayerServices.AddDataAccessLayerServices(services);
|
||||
|
||||
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
|
||||
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
|
||||
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
// Assert
|
||||
IUnitOfWork unitOfWork = serviceProvider.GetRequiredService<IUnitOfWork>();
|
||||
Assert.NotNull(unitOfWork.BookRepository);
|
||||
Assert.NotNull(unitOfWork.PermissionRepository);
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Interceptors;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateAuditableEntitiesInterceptor"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAuditableEntitiesInterceptorTests
|
||||
{
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IDateTimeProvider _mockDateTimeProvider;
|
||||
private readonly UpdateAuditableEntitiesInterceptor _sut;
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly LibraryScanResultEntityFixture _libraryScanResultEntityFixture = new();
|
||||
private readonly Guid _userId;
|
||||
private readonly DateTime _fixedUtcNow;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAuditableEntitiesInterceptorTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateAuditableEntitiesInterceptorTests()
|
||||
{
|
||||
_userId = Guid.NewGuid();
|
||||
_fixedUtcNow = new DateTime(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc);
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
|
||||
_sut = new UpdateAuditableEntitiesInterceptor(_mockCurrentUserService, _mockDateTimeProvider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SavingChangesAsync_WhenAddingAuditableEntity_ShouldSetCreationProperties()
|
||||
{
|
||||
// Arrange
|
||||
LuminaDbContext context = CreateContext();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
context.Books.Add(book);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(_fixedUtcNow, book.CreatedOnUtc);
|
||||
Assert.Equal(_userId, book.CreatedBy);
|
||||
Assert.Null(book.UpdatedOnUtc);
|
||||
Assert.Null(book.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SavingChangesAsync_WhenModifyingAuditableEntity_ShouldSetModificationProperties()
|
||||
{
|
||||
// Arrange
|
||||
LuminaDbContext context = CreateContext();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
context.Books.Add(book);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
book.Title = "Updated Title";
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(_fixedUtcNow, book.UpdatedOnUtc);
|
||||
Assert.Equal(_userId, book.UpdatedBy);
|
||||
Assert.Equal(_fixedUtcNow, book.CreatedOnUtc);
|
||||
Assert.Equal(_userId, book.CreatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SavingChangesAsync_WhenNoUserIsAuthenticated_ShouldLeaveCreationAndModificationUnattributed()
|
||||
{
|
||||
// Arrange
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
LuminaDbContext context = CreateContext();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
context.Books.Add(book);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
book.Title = "Updated Title";
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(Guid.Empty, book.CreatedBy);
|
||||
Assert.Equal(Guid.Empty, book.UpdatedBy);
|
||||
Assert.Equal(_fixedUtcNow, book.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SavingChangesAsync_WhenInitializationSave_ShouldPreserveTheExplicitAuditValues()
|
||||
{
|
||||
// Arrange
|
||||
LuminaDbContext context = CreateContext();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
DateTime initializationUtcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
book.CreatedOnUtc = initializationUtcNow;
|
||||
book.CreatedBy = AuditIdentities.s_systemUserId;
|
||||
book.UpdatedOnUtc = null;
|
||||
book.UpdatedBy = null;
|
||||
|
||||
// Act
|
||||
context.IsInitializationSave = true;
|
||||
context.Books.Add(book);
|
||||
await context.SaveChangesAsync();
|
||||
context.IsInitializationSave = false;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(initializationUtcNow, book.CreatedOnUtc);
|
||||
Assert.Equal(AuditIdentities.s_systemUserId, book.CreatedBy);
|
||||
Assert.Null(book.UpdatedOnUtc);
|
||||
Assert.Null(book.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SavingChanges_WhenAddingAuditableEntity_ShouldSetCreationProperties()
|
||||
{
|
||||
// Arrange
|
||||
LuminaDbContext context = CreateContext();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
context.Books.Add(book);
|
||||
context.SaveChanges();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(_fixedUtcNow, book.CreatedOnUtc);
|
||||
Assert.Equal(_userId, book.CreatedBy);
|
||||
Assert.Null(book.UpdatedOnUtc);
|
||||
Assert.Null(book.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SavingChangesAsync_WhenTrackingNonAuditableEntity_ShouldNotThrow()
|
||||
{
|
||||
// Arrange
|
||||
LuminaDbContext context = CreateContext();
|
||||
LibraryScanResultEntity scanResult = _libraryScanResultEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
context.LibraryScanResults.Add(scanResult);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(EntityState.Unchanged, context.Entry(scanResult).State);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="LuminaDbContext"/> that uses the interceptor under test.
|
||||
/// </summary>
|
||||
/// <returns>A configured <see cref="LuminaDbContext"/> instance.</returns>
|
||||
private LuminaDbContext CreateContext()
|
||||
{
|
||||
DbContextOptions<LuminaDbContext> options = new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(_sut)
|
||||
.Options;
|
||||
return new LuminaDbContext(options);
|
||||
}
|
||||
}
|
||||
+289
@@ -0,0 +1,289 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Common.Persistence;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CollectionReconciler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CollectionReconcilerTests
|
||||
{
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly IsbnEntityFixture _isbnEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_WhenAnItemIsNew_ShouldAddItToTheTrackedCollection()
|
||||
{
|
||||
// Arrange
|
||||
List<TagEntity> trackedTags = [];
|
||||
List<TagEntity> incomingTags = [_tagEntityFixture.Create(name: "jazz")];
|
||||
|
||||
// Act
|
||||
CollectionReconciler.Reconcile(
|
||||
trackedTags,
|
||||
incomingTags,
|
||||
trackedTag => trackedTag.Name!,
|
||||
incomingTag => incomingTag.Name!,
|
||||
shouldReplace: (trackedTag, incomingTag) => false,
|
||||
createNew: incomingTag => incomingTag);
|
||||
|
||||
// Assert
|
||||
TagEntity addedTag = Assert.Single(trackedTags);
|
||||
Assert.Same(incomingTags[0], addedTag);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_WhenATrackedItemIsAbsentFromTheIncomingSet_ShouldRemoveIt()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity removedTag = _tagEntityFixture.Create(name: "rock");
|
||||
TagEntity keptTag = _tagEntityFixture.Create(name: "jazz");
|
||||
List<TagEntity> trackedTags = [removedTag, keptTag];
|
||||
List<TagEntity> incomingTags = [_tagEntityFixture.Create(name: "jazz")];
|
||||
|
||||
// Act
|
||||
CollectionReconciler.Reconcile(
|
||||
trackedTags,
|
||||
incomingTags,
|
||||
trackedTag => trackedTag.Name!,
|
||||
incomingTag => incomingTag.Name!,
|
||||
shouldReplace: (trackedTag, incomingTag) => false,
|
||||
createNew: incomingTag => incomingTag);
|
||||
|
||||
// Assert
|
||||
TagEntity keptTrackedTag = Assert.Single(trackedTags);
|
||||
Assert.Same(keptTag, keptTrackedTag);
|
||||
Assert.DoesNotContain(removedTag, trackedTags);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_WhenAMatchedItemDidNotChange_ShouldKeepTheSameTrackedInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity trackedTag = _tagEntityFixture.Create(name: "rock");
|
||||
List<TagEntity> trackedTags = [trackedTag];
|
||||
List<TagEntity> incomingTags = [_tagEntityFixture.Create(name: "rock")];
|
||||
|
||||
// Act
|
||||
CollectionReconciler.Reconcile(
|
||||
trackedTags,
|
||||
incomingTags,
|
||||
existingTag => existingTag.Name!,
|
||||
incomingTag => incomingTag.Name!,
|
||||
shouldReplace: (existingTag, incomingTag) => false,
|
||||
createNew: incomingTag => incomingTag);
|
||||
|
||||
// Assert
|
||||
TagEntity keptTrackedTag = Assert.Single(trackedTags);
|
||||
Assert.Same(trackedTag, keptTrackedTag);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_WhenAMatchedItemChanged_ShouldReplaceOnlyThatItem()
|
||||
{
|
||||
// Arrange
|
||||
IsbnEntity trackedIsbn = _isbnEntityFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn10);
|
||||
IsbnEntity unchangedIsbn = _isbnEntityFixture.Create(value: "978-0-306-40615-7", format: IsbnFormat.Isbn13);
|
||||
List<IsbnEntity> trackedIsbns = [trackedIsbn, unchangedIsbn];
|
||||
IsbnEntity incomingChangedIsbn = _isbnEntityFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13);
|
||||
IsbnEntity incomingUnchangedIsbn = _isbnEntityFixture.Create(value: "978-0-306-40615-7", format: IsbnFormat.Isbn13);
|
||||
List<IsbnEntity> incomingIsbns = [incomingChangedIsbn, incomingUnchangedIsbn];
|
||||
|
||||
// Act
|
||||
CollectionReconciler.Reconcile(
|
||||
trackedIsbns,
|
||||
incomingIsbns,
|
||||
existingIsbn => existingIsbn.Value!,
|
||||
incomingIsbn => incomingIsbn.Value!,
|
||||
shouldReplace: (existingIsbn, incomingIsbn) => !existingIsbn.Equals(incomingIsbn),
|
||||
createNew: incomingIsbn => incomingIsbn);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, trackedIsbns.Count);
|
||||
Assert.DoesNotContain(trackedIsbn, trackedIsbns);
|
||||
Assert.Contains(incomingChangedIsbn, trackedIsbns);
|
||||
IsbnEntity keptIsbn = trackedIsbns.Single(isbn => isbn.Value == unchangedIsbn.Value);
|
||||
Assert.Same(unchangedIsbn, keptIsbn);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_WhenSeveralChangesAreRequested_ShouldApplyAddRemoveAndKeepInASinglePass()
|
||||
{
|
||||
// Arrange
|
||||
BookContributorEntity removedContributor = _bookContributorEntityFixture.Create(role: MediaContributorRole.Author);
|
||||
BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(role: MediaContributorRole.Illustrator);
|
||||
List<BookContributorEntity> trackedContributors = [removedContributor, keptContributor];
|
||||
BookContributorEntity incomingKeptContributor = _bookContributorEntityFixture.Create(
|
||||
bookId: keptContributor.BookId,
|
||||
mediaContributorId: keptContributor.MediaContributorId,
|
||||
role: keptContributor.Role);
|
||||
BookContributorEntity incomingNewContributor = _bookContributorEntityFixture.Create(role: MediaContributorRole.Translator);
|
||||
List<BookContributorEntity> incomingContributors = [incomingKeptContributor, incomingNewContributor];
|
||||
|
||||
// Act
|
||||
CollectionReconciler.Reconcile(
|
||||
trackedContributors,
|
||||
incomingContributors,
|
||||
existingContributor => (existingContributor.MediaContributorId, existingContributor.Role),
|
||||
incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role),
|
||||
shouldReplace: (existingContributor, incomingContributor) => false,
|
||||
createNew: incomingContributor => incomingContributor);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, trackedContributors.Count);
|
||||
Assert.DoesNotContain(removedContributor, trackedContributors);
|
||||
Assert.Same(keptContributor, trackedContributors.Single(contributor => contributor.MediaContributorId == keptContributor.MediaContributorId));
|
||||
Assert.Same(incomingNewContributor, trackedContributors.Single(contributor => contributor.MediaContributorId == incomingNewContributor.MediaContributorId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_WhenTheIncomingSetIsEmpty_ShouldRemoveEveryTrackedItem()
|
||||
{
|
||||
// Arrange
|
||||
List<TagEntity> trackedTags = [_tagEntityFixture.Create(name: "rock"), _tagEntityFixture.Create(name: "jazz")];
|
||||
List<TagEntity> incomingTags = [];
|
||||
|
||||
// Act
|
||||
CollectionReconciler.Reconcile(
|
||||
trackedTags,
|
||||
incomingTags,
|
||||
trackedTag => trackedTag.Name!,
|
||||
incomingTag => incomingTag.Name!,
|
||||
shouldReplace: (trackedTag, incomingTag) => false,
|
||||
createNew: incomingTag => incomingTag);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(trackedTags);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_WhenTheTrackedCollectionIsEmpty_ShouldAddEveryIncomingItem()
|
||||
{
|
||||
// Arrange
|
||||
List<TagEntity> trackedTags = [];
|
||||
List<TagEntity> incomingTags = [_tagEntityFixture.Create(name: "rock"), _tagEntityFixture.Create(name: "jazz")];
|
||||
|
||||
// Act
|
||||
CollectionReconciler.Reconcile(
|
||||
trackedTags,
|
||||
incomingTags,
|
||||
trackedTag => trackedTag.Name!,
|
||||
incomingTag => incomingTag.Name!,
|
||||
shouldReplace: (trackedTag, incomingTag) => false,
|
||||
createNew: incomingTag => incomingTag);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, trackedTags.Count);
|
||||
Assert.Same(incomingTags[0], trackedTags.Single(tag => tag.Name == "rock"));
|
||||
Assert.Same(incomingTags[1], trackedTags.Single(tag => tag.Name == "jazz"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_WhenTheTrackedCollectionHasDuplicateKeys_ShouldMatchTheFirstTrackedInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity firstTrackedTag = _tagEntityFixture.Create(name: "rock");
|
||||
TagEntity secondTrackedTag = _tagEntityFixture.Create(name: "rock");
|
||||
List<TagEntity> trackedTags = [firstTrackedTag, secondTrackedTag];
|
||||
List<TagEntity> incomingTags = [_tagEntityFixture.Create(name: "rock")];
|
||||
|
||||
// Act
|
||||
CollectionReconciler.Reconcile(
|
||||
trackedTags,
|
||||
incomingTags,
|
||||
trackedTag => trackedTag.Name!,
|
||||
incomingTag => incomingTag.Name!,
|
||||
shouldReplace: (trackedTag, incomingTag) => false,
|
||||
createNew: incomingTag => incomingTag);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, trackedTags.Count);
|
||||
Assert.Same(firstTrackedTag, trackedTags[0]);
|
||||
Assert.Same(secondTrackedTag, trackedTags[1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_WhenTheIncomingCollectionHasDuplicateNewKeys_ShouldAddOnlyOneItem()
|
||||
{
|
||||
// Arrange
|
||||
List<TagEntity> trackedTags = [];
|
||||
TagEntity firstIncomingTag = _tagEntityFixture.Create(name: "rock");
|
||||
TagEntity secondIncomingTag = _tagEntityFixture.Create(name: "rock");
|
||||
List<TagEntity> incomingTags = [firstIncomingTag, secondIncomingTag];
|
||||
|
||||
// Act
|
||||
CollectionReconciler.Reconcile(
|
||||
trackedTags,
|
||||
incomingTags,
|
||||
trackedTag => trackedTag.Name!,
|
||||
incomingTag => incomingTag.Name!,
|
||||
shouldReplace: (trackedTag, incomingTag) => false,
|
||||
createNew: incomingTag => incomingTag);
|
||||
|
||||
// Assert
|
||||
TagEntity addedTag = Assert.Single(trackedTags);
|
||||
Assert.Same(firstIncomingTag, addedTag);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_WhenAReplacedItemIsRematchedByALaterIncomingItem_ShouldReuseTheReplacement()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity trackedTag = _tagEntityFixture.Create(name: "rock");
|
||||
List<TagEntity> trackedTags = [trackedTag];
|
||||
TagEntity firstIncomingTag = _tagEntityFixture.Create(name: "rock");
|
||||
TagEntity secondIncomingTag = _tagEntityFixture.Create(name: "rock");
|
||||
List<TagEntity> incomingTags = [firstIncomingTag, secondIncomingTag];
|
||||
|
||||
// Act
|
||||
CollectionReconciler.Reconcile(
|
||||
trackedTags,
|
||||
incomingTags,
|
||||
existingTag => existingTag.Name!,
|
||||
incomingTag => incomingTag.Name!,
|
||||
shouldReplace: (existingTag, incomingTag) => !ReferenceEquals(existingTag, incomingTag),
|
||||
createNew: incomingTag => incomingTag);
|
||||
|
||||
// Assert
|
||||
TagEntity replacedTag = Assert.Single(trackedTags);
|
||||
Assert.Same(secondIncomingTag, replacedTag);
|
||||
Assert.DoesNotContain(trackedTags, trackedItem => ReferenceEquals(trackedItem, firstIncomingTag));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_WhenANewItemIsAddedAndALaterIncomingItemReplacesIt_ShouldKeepASingleItem()
|
||||
{
|
||||
// Arrange
|
||||
List<TagEntity> trackedTags = [];
|
||||
TagEntity firstIncomingTag = _tagEntityFixture.Create(name: "rock");
|
||||
TagEntity secondIncomingTag = _tagEntityFixture.Create(name: "rock");
|
||||
List<TagEntity> incomingTags = [firstIncomingTag, secondIncomingTag];
|
||||
|
||||
// Act
|
||||
CollectionReconciler.Reconcile(
|
||||
trackedTags,
|
||||
incomingTags,
|
||||
trackedTag => trackedTag.Name!,
|
||||
incomingTag => incomingTag.Name!,
|
||||
shouldReplace: (trackedTag, incomingTag) => !ReferenceEquals(trackedTag, incomingTag),
|
||||
createNew: incomingTag => incomingTag);
|
||||
|
||||
// Assert
|
||||
// The item added for the first occurrence is indexed, so the second occurrence matches it instead of adding a duplicate.
|
||||
TagEntity trackedTag = Assert.Single(trackedTags);
|
||||
Assert.Same(secondIncomingTag, trackedTag);
|
||||
Assert.DoesNotContain(trackedTags, trackedItem => ReferenceEquals(trackedItem, firstIncomingTag));
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.DataAccess.Common.Persistence;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="EditableValuesCopier"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EditableValuesCopierTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task CopyEditableValues_WhenCalled_ShouldCopyTheEditableScalarValuesOntoTheTrackedEntity()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity trackedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
|
||||
_mockContext.Artists.Add(trackedArtist);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
ArtistEntity incomingArtist = _artistEntityFixture.Create(id: trackedArtist.Id, name: "Updated Artist", includeAlbums: false, includeContributors: false);
|
||||
incomingArtist.Website = "https://updated.example.com";
|
||||
|
||||
// Act
|
||||
EditableValuesCopier.CopyEditableValues(_mockContext, trackedArtist, incomingArtist);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Updated Artist", trackedArtist.Name);
|
||||
Assert.Equal("https://updated.example.com", trackedArtist.Website);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CopyEditableValues_WhenCalled_ShouldPreserveTheStoredAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
Guid storedCreatedBy = Guid.NewGuid();
|
||||
DateTime storedUpdatedOnUtc = new(2021, 1, 2, 3, 4, 5, DateTimeKind.Utc);
|
||||
Guid storedUpdatedBy = Guid.NewGuid();
|
||||
ArtistEntity trackedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
|
||||
trackedArtist.CreatedOnUtc = storedCreatedOnUtc;
|
||||
trackedArtist.CreatedBy = storedCreatedBy;
|
||||
trackedArtist.UpdatedOnUtc = storedUpdatedOnUtc;
|
||||
trackedArtist.UpdatedBy = storedUpdatedBy;
|
||||
_mockContext.Artists.Add(trackedArtist);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
ArtistEntity incomingArtist = _artistEntityFixture.Create(id: trackedArtist.Id, includeAlbums: false, includeContributors: false);
|
||||
incomingArtist.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
|
||||
incomingArtist.CreatedBy = Guid.NewGuid();
|
||||
incomingArtist.UpdatedOnUtc = DateTime.UtcNow;
|
||||
incomingArtist.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
EditableValuesCopier.CopyEditableValues(_mockContext, trackedArtist, incomingArtist);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(storedCreatedOnUtc, trackedArtist.CreatedOnUtc);
|
||||
Assert.Equal(storedCreatedBy, trackedArtist.CreatedBy);
|
||||
Assert.Equal(storedUpdatedOnUtc, trackedArtist.UpdatedOnUtc);
|
||||
Assert.Equal(storedUpdatedBy, trackedArtist.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CopyEditableValues_WhenNoEditableValueChanged_ShouldNotMarkAnyEditablePropertyAsModified()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity trackedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
|
||||
_mockContext.Artists.Add(trackedArtist);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
ArtistEntity incomingArtist = _artistEntityFixture.Create(id: trackedArtist.Id, includeAlbums: false, includeContributors: false);
|
||||
incomingArtist.Name = trackedArtist.Name;
|
||||
incomingArtist.Website = trackedArtist.Website;
|
||||
incomingArtist.MusicBrainzArtistId = trackedArtist.MusicBrainzArtistId;
|
||||
incomingArtist.LibraryId = trackedArtist.LibraryId;
|
||||
|
||||
// Act
|
||||
EditableValuesCopier.CopyEditableValues(_mockContext, trackedArtist, incomingArtist);
|
||||
|
||||
// Assert
|
||||
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.Name).IsModified);
|
||||
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.Website).IsModified);
|
||||
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.MusicBrainzArtistId).IsModified);
|
||||
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.LibraryId).IsModified);
|
||||
// The primary key and the audit columns are owned by the persistence medium, so the copy never touches them either.
|
||||
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.Id).IsModified);
|
||||
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.CreatedOnUtc).IsModified);
|
||||
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.CreatedBy).IsModified);
|
||||
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.UpdatedOnUtc).IsModified);
|
||||
Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.UpdatedBy).IsModified);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)] // The incoming entity carries a different, non-empty key.
|
||||
[InlineData(true)] // The incoming entity carries an unset key.
|
||||
public async Task CopyEditableValues_WhenTheIncomingKeyDoesNotMatchTheTrackedOne_ShouldPreserveTheTrackedIdentity(bool useUnsetKey)
|
||||
{
|
||||
// Arrange
|
||||
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
Guid storedCreatedBy = Guid.NewGuid();
|
||||
ArtistEntity trackedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
|
||||
trackedArtist.CreatedOnUtc = storedCreatedOnUtc;
|
||||
trackedArtist.CreatedBy = storedCreatedBy;
|
||||
trackedArtist.UpdatedOnUtc = null;
|
||||
trackedArtist.UpdatedBy = null;
|
||||
_mockContext.Artists.Add(trackedArtist);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
Guid trackedArtistId = trackedArtist.Id;
|
||||
|
||||
// The incoming entity carries a key that does not match the tracked one, a changed editable value, and hostile audit values.
|
||||
Guid incomingId = useUnsetKey ? Guid.Empty : Guid.NewGuid();
|
||||
ArtistEntity incomingArtist = _artistEntityFixture.Create(id: incomingId, name: "Updated Artist", includeAlbums: false, includeContributors: false);
|
||||
incomingArtist.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
|
||||
incomingArtist.CreatedBy = Guid.NewGuid();
|
||||
incomingArtist.UpdatedOnUtc = DateTime.UtcNow;
|
||||
incomingArtist.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
EditableValuesCopier.CopyEditableValues(_mockContext, trackedArtist, incomingArtist);
|
||||
|
||||
// Assert
|
||||
// The stored identity is never retargeted by the incoming key, the audit columns are untouched, and the editable values are still copied.
|
||||
Assert.Equal(trackedArtistId, trackedArtist.Id);
|
||||
Assert.NotEqual(incomingId, trackedArtist.Id);
|
||||
Assert.Equal("Updated Artist", trackedArtist.Name);
|
||||
Assert.Equal(storedCreatedOnUtc, trackedArtist.CreatedOnUtc);
|
||||
Assert.Equal(storedCreatedBy, trackedArtist.CreatedBy);
|
||||
Assert.Null(trackedArtist.UpdatedOnUtc);
|
||||
Assert.Null(trackedArtist.UpdatedBy);
|
||||
}
|
||||
}
|
||||
+467
@@ -0,0 +1,467 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.DataAccess.Common.Persistence;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SharedReferenceResolver"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SharedReferenceResolverTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenANameIsNotStored_ShouldReturnTheIncomingInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(resolveResult.IsFailure);
|
||||
Assert.Same(incomingTag, resolveResult.Value["jazz"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenANameIsAlreadyStoredAndTracked_ShouldReturnTheTrackedInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity storedTag = _tagEntityFixture.Create(name: "jazz");
|
||||
_mockContext.Set<TagEntity>().Add(storedTag);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(resolveResult.IsFailure);
|
||||
Assert.Same(storedTag, resolveResult.Value["jazz"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenANameIsAlreadyStoredButNotTracked_ShouldLoadTheStoredInstanceFromStorage()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity storedTag = _tagEntityFixture.Create(name: "jazz");
|
||||
_mockContext.Set<TagEntity>().Add(storedTag);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Detach the stored row, so that the resolution cannot take the tracked shortcut and must read it from the storage medium.
|
||||
_mockContext.ChangeTracker.Clear();
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(resolveResult.IsFailure);
|
||||
TagEntity resolvedTag = resolveResult.Value["jazz"];
|
||||
// A different instance than the incoming one proves the row was materialized from the storage medium instead of the tracked shortcut.
|
||||
Assert.NotSame(incomingTag, resolvedTag);
|
||||
Assert.Equal("jazz", resolvedTag.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenTheSameNameAppearsMoreThanOnce_ShouldCollapseItToASingleInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity firstTag = _tagEntityFixture.Create(name: "jazz");
|
||||
TagEntity secondTag = _tagEntityFixture.Create(name: "jazz");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [firstTag, secondTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(resolveResult.IsFailure);
|
||||
Assert.Single(resolveResult.Value);
|
||||
Assert.Same(firstTag, resolveResult.Value["jazz"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenIncomingNamesDifferOnlyByCasing_ShouldCollapseThemToASingleInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity firstTag = _tagEntityFixture.Create(name: "Horror");
|
||||
TagEntity secondTag = _tagEntityFixture.Create(name: "horror");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [firstTag, secondTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(resolveResult.IsFailure);
|
||||
Assert.Single(resolveResult.Value);
|
||||
Assert.Same(firstTag, resolveResult.Value["horror"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenAStoredNameDiffersOnlyByCasing_ShouldReturnTheStoredInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity storedTag = _tagEntityFixture.Create(name: "horror");
|
||||
_mockContext.Set<TagEntity>().Add(storedTag);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Detach the stored row, so that the resolution cannot take the tracked shortcut and must read it from the storage medium.
|
||||
_mockContext.ChangeTracker.Clear();
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: "Horror");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(resolveResult.IsFailure);
|
||||
TagEntity resolvedTag = resolveResult.Value["horror"];
|
||||
// A different instance than the incoming one proves the stored row was reused instead of the incoming one being inserted.
|
||||
Assert.NotSame(incomingTag, resolvedTag);
|
||||
Assert.Equal("horror", resolvedTag.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenIncomingNamesDifferOnlyByWhitespaceAndCasing_ShouldCollapseThemToTheNormalizedName()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity firstTag = _tagEntityFixture.Create(name: " Horror ");
|
||||
TagEntity secondTag = _tagEntityFixture.Create(name: "HORROR");
|
||||
TagEntity thirdTag = _tagEntityFixture.Create(name: "horror");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [firstTag, secondTag, thirdTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(resolveResult.IsFailure);
|
||||
Assert.Single(resolveResult.Value);
|
||||
Assert.Same(firstTag, resolveResult.Value["horror"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenAStoredNormalizedNameExistsAndTheIncomingNameIsPaddedAndMixedCase_ShouldReturnTheStoredInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity storedTag = _tagEntityFixture.Create(name: "horror");
|
||||
_mockContext.Set<TagEntity>().Add(storedTag);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Detach the stored row, so that the resolution cannot take the tracked shortcut and must read it from the storage medium.
|
||||
_mockContext.ChangeTracker.Clear();
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: " HoRRoR ");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(resolveResult.IsFailure);
|
||||
Assert.Single(resolveResult.Value);
|
||||
TagEntity resolvedTag = resolveResult.Value["horror"];
|
||||
Assert.NotSame(incomingTag, resolvedTag);
|
||||
Assert.Equal("horror", resolvedTag.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenATrackedLegacyMixedCaseRowExistsAndTheIncomingNameIsNormalized_ShouldReturnTheTrackedInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity trackedTag = _tagEntityFixture.Create(name: "Horror");
|
||||
_mockContext.Set<TagEntity>().Add(trackedTag);
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: "horror");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(resolveResult.IsFailure);
|
||||
Assert.Same(trackedTag, resolveResult.Value["horror"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenANonAsciiUppercaseNameMatchesAStoredLowercaseName_ShouldReturnTheStoredInstance()
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity storedGenre = _genreEntityFixture.Create(name: "électro");
|
||||
_mockContext.Set<GenreEntity>().Add(storedGenre);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Detach the stored row, so that the resolution cannot take the tracked shortcut and must read it from the storage medium.
|
||||
_mockContext.ChangeTracker.Clear();
|
||||
GenreEntity incomingGenre = _genreEntityFixture.Create(name: "ÉLECTRO");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, GenreEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingGenre], Errors.Metadata.GenreNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(resolveResult.IsFailure);
|
||||
Assert.Single(resolveResult.Value);
|
||||
GenreEntity resolvedGenre = resolveResult.Value["électro"];
|
||||
Assert.NotSame(incomingGenre, resolvedGenre);
|
||||
Assert.Equal("électro", resolvedGenre.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Normalize_WhenANameIsPaddedAndMixedCase_ShouldMapToTheResolvedInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity resolvedTag = _tagEntityFixture.Create(name: "horror");
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: " HoRRoR ");
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [resolvedTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Act
|
||||
IReadOnlyCollection<TagEntity> normalizedTags = SharedReferenceResolver.Normalize([incomingTag], resolveResult.Value);
|
||||
|
||||
// Assert
|
||||
Assert.Same(resolvedTag, Assert.Single(normalizedTags));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReconcileAsync_WhenAStoredNormalizedNameExistsAndTheIncomingNameIsPaddedAndMixedCase_ShouldReuseTheStoredInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity storedTag = _tagEntityFixture.Create(name: "horror");
|
||||
_mockContext.Set<TagEntity>().Add(storedTag);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
List<TagEntity> trackedTags = [];
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: " HoRRoR ");
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(storedTag, Assert.Single(trackedTags));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReconcileAsync_WhenANewNameIsRepeatedWithDifferentCasingAndWhitespace_ShouldAddASingleInstance()
|
||||
{
|
||||
// Arrange
|
||||
List<TagEntity> trackedTags = [];
|
||||
TagEntity firstTag = _tagEntityFixture.Create(name: " Horror ");
|
||||
TagEntity secondTag = _tagEntityFixture.Create(name: "HORROR");
|
||||
TagEntity thirdTag = _tagEntityFixture.Create(name: "horror");
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [firstTag, secondTag, thirdTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(firstTag, Assert.Single(trackedTags));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenThereAreNoIncomingEntities_ShouldReturnAnEmptyDictionary()
|
||||
{
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, GenreEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync<GenreEntity>(_mockContext, [], Errors.Metadata.GenreNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(resolveResult.IsFailure);
|
||||
Assert.Empty(resolveResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReconcileAsync_WhenCalledWithAnotherSharedReferenceType_ShouldReconcileItTheSameWay()
|
||||
{
|
||||
// Arrange
|
||||
List<GenreEntity> trackedGenres = [_genreEntityFixture.Create(name: "rock")];
|
||||
GenreEntity incomingGenre = _genreEntityFixture.Create(name: "jazz");
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedGenres, [incomingGenre], Errors.Metadata.GenreNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(incomingGenre, Assert.Single(trackedGenres));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Normalize_WhenCalled_ShouldMapEveryEntityToItsResolvedInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity firstTag = _tagEntityFixture.Create(name: "jazz");
|
||||
TagEntity secondTag = _tagEntityFixture.Create(name: "jazz");
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [firstTag, secondTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Act
|
||||
IReadOnlyCollection<TagEntity> normalizedTags = SharedReferenceResolver.Normalize([firstTag, secondTag], resolveResult.Value);
|
||||
|
||||
// Assert
|
||||
TagEntity normalizedTag = Assert.Single(normalizedTags);
|
||||
Assert.Same(firstTag, normalizedTag);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Normalize_WhenANameDiffersOnlyByCasingFromTheResolvedName_ShouldMapToTheResolvedInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity resolvedTag = _tagEntityFixture.Create(name: "horror");
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: "Horror");
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [resolvedTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Act
|
||||
IReadOnlyCollection<TagEntity> normalizedTags = SharedReferenceResolver.Normalize([incomingTag], resolveResult.Value);
|
||||
|
||||
// Assert
|
||||
Assert.Same(resolvedTag, Assert.Single(normalizedTags));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReconcileAsync_WhenANameIsNew_ShouldAddItToTheTrackedCollection()
|
||||
{
|
||||
// Arrange
|
||||
List<TagEntity> trackedTags = [];
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(incomingTag, Assert.Single(trackedTags));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReconcileAsync_WhenANameIsAlreadyStored_ShouldReuseTheStoredInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity storedTag = _tagEntityFixture.Create(name: "jazz");
|
||||
_mockContext.Set<TagEntity>().Add(storedTag);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
List<TagEntity> trackedTags = [];
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(storedTag, Assert.Single(trackedTags));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReconcileAsync_WhenATrackedNameIsMissingFromTheIncomingSet_ShouldRemoveIt()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity removedTag = _tagEntityFixture.Create(name: "rock");
|
||||
TagEntity keptTag = _tagEntityFixture.Create(name: "jazz");
|
||||
List<TagEntity> trackedTags = [removedTag, keptTag];
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(keptTag, Assert.Single(trackedTags));
|
||||
Assert.DoesNotContain(removedTag, trackedTags);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReconcileAsync_WhenTheSameNewNameAppearsMoreThanOnce_ShouldTrackASingleInstance()
|
||||
{
|
||||
// Arrange
|
||||
List<TagEntity> trackedTags = [];
|
||||
TagEntity firstTag = _tagEntityFixture.Create(name: "jazz");
|
||||
TagEntity secondTag = _tagEntityFixture.Create(name: "jazz");
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [firstTag, secondTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(firstTag, Assert.Single(trackedTags));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenANameIsNull_ShouldReturnNameCannotBeEmptyError()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(includeName: false);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(resolveResult.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, resolveResult.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenANameIsWhitespace_ShouldReturnNameCannotBeEmptyError()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: " ");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(resolveResult.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, resolveResult.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsync_WhenTheNameIsAlreadyTrackedButNotStored_ShouldReturnTheTrackedInstance()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity trackedTag = _tagEntityFixture.Create(name: "jazz");
|
||||
_mockContext.Set<TagEntity>().Add(trackedTag);
|
||||
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz");
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(resolveResult.IsFailure);
|
||||
Assert.Same(trackedTag, resolveResult.Value["jazz"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReconcileAsync_WhenANameIsNull_ShouldReturnNameCannotBeEmptyErrorWithoutChangingTheTrackedCollection()
|
||||
{
|
||||
// Arrange
|
||||
List<TagEntity> trackedTags = [];
|
||||
TagEntity incomingTag = _tagEntityFixture.Create(includeName: false);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError);
|
||||
Assert.Empty(trackedTags);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Normalize_WhenAnEntityCannotBeResolved_ShouldSkipIt()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity namedTag = _tagEntityFixture.Create(name: "jazz");
|
||||
TagEntity unnamedTag = _tagEntityFixture.Create(includeName: false);
|
||||
Result<IReadOnlyDictionary<string, TagEntity>> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [namedTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None);
|
||||
|
||||
// Act
|
||||
IReadOnlyCollection<TagEntity> normalizedTags = SharedReferenceResolver.Normalize([namedTag, unnamedTag], resolveResult.Value);
|
||||
|
||||
// Assert
|
||||
Assert.Same(namedTag, Assert.Single(normalizedTags));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Fake service for retrieving the current user's information during tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TestCurrentUserService : ICurrentUserService
|
||||
{
|
||||
private Guid userId;
|
||||
public Guid? UserId => userId;
|
||||
|
||||
/// <summary>
|
||||
/// Sets the test value of the user id.
|
||||
/// </summary>
|
||||
/// <param name="userId">The user id to use during tests.</param>
|
||||
public void SetUserId(Guid userId)
|
||||
{
|
||||
this.userId = userId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Service for time related concerns.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TestDateTimeProvider : IDateTimeProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// The current UTC time.
|
||||
/// </summary>
|
||||
public DateTime UtcNow => DateTime.UtcNow;
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.DataAccess.Core.Repositories.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
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.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PermissionRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PermissionRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly PermissionRepository _sut;
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PermissionRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public PermissionRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new PermissionRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenPermissionDoesNotExist_ShouldAddPermissionToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
PermissionEntity permissionModel = _permissionEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(permissionModel, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
// Check if the permission was added to the context's ChangeTracker.
|
||||
EntityEntry<PermissionEntity>? addedPermission = _mockContext.ChangeTracker.Entries<PermissionEntity>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == permissionModel.Id);
|
||||
Assert.NotNull(addedPermission);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenPermissionAlreadyExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
PermissionEntity permissionModel = _permissionEntityFixture.Create();
|
||||
|
||||
_mockContext.Permissions.Add(permissionModel);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(permissionModel, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Authorization.PermissionAlreadyExists, result.FirstError);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<PermissionEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenPermissionsExist_ShouldReturnAllPermissions()
|
||||
{
|
||||
// Arrange
|
||||
List<PermissionEntity> permissions = _permissionEntityFixture.CreateMany(3);
|
||||
_mockContext.Permissions.AddRange(permissions);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<PermissionEntity>> result = await _sut.GetAllAsync<BaseFilterDto>(cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(3, result.Value.Data.Count);
|
||||
Assert.Equal(permissions, result.Value.Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenNoPermissionsExist_ShouldReturnEmptyList()
|
||||
{
|
||||
// Act
|
||||
Result<PaginatedResultDto<PermissionEntity>> result = await _sut.GetAllAsync<BaseFilterDto>(cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value.Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenPermissionsExist_ShouldReturnMatchingPermissions()
|
||||
{
|
||||
// Arrange
|
||||
List<PermissionEntity> permissions = _permissionEntityFixture.CreateMany(3);
|
||||
_mockContext.Permissions.AddRange(permissions);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
List<Guid> requestedIds = [.. permissions.Take(2).Select(p => p.Id)];
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PermissionEntity>> result = await _sut.GetByIdsAsync(requestedIds, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(2, result.Value.Count());
|
||||
Assert.Equal(requestedIds, [.. result.Value.Select(p => p.Id)]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenNoPermissionsMatch_ShouldReturnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> requestedIds = [Guid.NewGuid(), Guid.NewGuid()];
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PermissionEntity>> result = await _sut.GetByIdsAsync(requestedIds, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.DataAccess.Core.Repositories.Authorization;
|
||||
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.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RolePermissionRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RolePermissionRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly RolePermissionRepository _sut;
|
||||
private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RolePermissionRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public RolePermissionRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new RolePermissionRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenCalled_ShouldAddRolePermissionToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
RolePermissionEntity rolePermissionModel = _rolePermissionEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(rolePermissionModel, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
// Check if the role permission was added to the context's ChangeTracker.
|
||||
EntityEntry<RolePermissionEntity>? addedRolePermission = _mockContext.ChangeTracker.Entries<RolePermissionEntity>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == rolePermissionModel.Id);
|
||||
Assert.NotNull(addedRolePermission);
|
||||
}
|
||||
}
|
||||
+383
@@ -0,0 +1,383 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.DataAccess.Core.Repositories.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
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.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RoleRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RoleRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly RoleRepository _sut;
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RoleRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public RoleRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new RoleRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenRoleDoesNotExist_ShouldAddRoleToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity role = _roleEntityFixture.Create(roleName: "Admin");
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(role, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
// Check if the role was added to the context's ChangeTracker.
|
||||
EntityEntry<RoleEntity>? addedRole = _mockContext.ChangeTracker.Entries<RoleEntity>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == role.Id);
|
||||
Assert.NotNull(addedRole);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenRoleWithSameIdExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity existingRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
|
||||
_mockContext.Roles.Add(existingRole);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
RoleEntity newRole = _roleEntityFixture.Create(id: existingRole.Id, roleName: "SuperAdmin");
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(newRole, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Authorization.RoleAlreadyExists, result.FirstError);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<RoleEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenRoleWithSameNameExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity existingRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
|
||||
_mockContext.Roles.Add(existingRole);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
RoleEntity newRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(newRole, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Authorization.RoleAlreadyExists, result.FirstError);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<RoleEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenRolesExist_ShouldReturnAllRoles()
|
||||
{
|
||||
// Arrange
|
||||
List<RoleEntity> roles =
|
||||
[
|
||||
_roleEntityFixture.Create(roleName: "Admin"),
|
||||
_roleEntityFixture.Create(roleName: "User")
|
||||
];
|
||||
|
||||
_mockContext.Roles.AddRange(roles);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<RoleEntity>> result = await _sut.GetAllAsync<BaseFilterDto>(cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(2, result.Value.Data.Count);
|
||||
Assert.Equal(roles, result.Value.Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenNoRolesExist_ShouldReturnEmptyList()
|
||||
{
|
||||
// Act
|
||||
Result<PaginatedResultDto<RoleEntity>> result = await _sut.GetAllAsync<BaseFilterDto>(cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value.Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByNameAsync_WhenRoleExists_ShouldReturnRoleWithPermissions()
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity role = _roleEntityFixture.Create(roleName: "Admin");
|
||||
RolePermissionEntity rolePermission = _rolePermissionEntityFixture.Create(role: role, roleId: role.Id);
|
||||
role.RolePermissions = [rolePermission];
|
||||
|
||||
_mockContext.Roles.Add(role);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<RoleEntity?> result = await _sut.GetByNameAsync("Admin", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(role.Id, result.Value!.Id);
|
||||
Assert.Equal("Admin", result.Value.RoleName);
|
||||
RolePermissionEntity loadedPermission = Assert.Single(result.Value.RolePermissions);
|
||||
Assert.Equal(rolePermission.PermissionId, loadedPermission.PermissionId);
|
||||
Assert.NotNull(loadedPermission.Permission);
|
||||
Assert.Equal(rolePermission.Permission.Id, loadedPermission.Permission.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByNameAsync_WhenRoleDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<RoleEntity?> result = await _sut.GetByNameAsync("NonExistentRole", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenRoleExists_ShouldReturnRoleWithPermissions()
|
||||
{
|
||||
// Arrange
|
||||
RolePermissionEntity rolePermission = _rolePermissionEntityFixture.Create();
|
||||
RoleEntity role = rolePermission.Role;
|
||||
role.RolePermissions = [rolePermission];
|
||||
|
||||
_mockContext.Roles.Add(role);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<RoleEntity?> result = await _sut.GetByIdAsync(role.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(role.Id, result.Value!.Id);
|
||||
Assert.Equal(role.RoleName, result.Value.RoleName);
|
||||
Assert.Equal(role.CreatedOnUtc, result.Value.CreatedOnUtc);
|
||||
Assert.Equal(role.CreatedBy, result.Value.CreatedBy);
|
||||
RolePermissionEntity loadedPermission = Assert.Single(result.Value.RolePermissions);
|
||||
Assert.Equal(rolePermission.PermissionId, loadedPermission.PermissionId);
|
||||
Assert.Equal(role.Id, loadedPermission.RoleId);
|
||||
Assert.NotNull(loadedPermission.Permission);
|
||||
Assert.Equal(rolePermission.Permission.Id, loadedPermission.Permission.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenRoleDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<RoleEntity?> result = await _sut.GetByIdAsync(nonExistentId, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenRoleExists_ShouldUpdateRoleAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity existingRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
|
||||
_mockContext.Roles.Add(existingRole);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
RoleEntity updatedRole = _roleEntityFixture.Create(id: existingRole.Id, roleName: "SuperAdmin", createdBy: existingRole.CreatedBy, createdOnUtc: existingRole.CreatedOnUtc);
|
||||
updatedRole.UpdatedOnUtc = DateTime.UtcNow;
|
||||
updatedRole.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedRole, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<RoleEntity>? updatedEntry = _mockContext.ChangeTracker.Entries<RoleEntity>()
|
||||
.FirstOrDefault(e => e.Entity.Id == existingRole.Id);
|
||||
Assert.NotNull(updatedEntry);
|
||||
Assert.Equal("SuperAdmin", updatedEntry!.Entity.RoleName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenRoleDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity nonExistentRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(nonExistentRole, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Authorization.RoleNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenRoleHasPermissions_ShouldUpdatePermissionsAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
RolePermissionEntity rolePermission = _rolePermissionEntityFixture.Create();
|
||||
RoleEntity existingRole = rolePermission.Role;
|
||||
existingRole.RolePermissions = [rolePermission];
|
||||
|
||||
_mockContext.Roles.Add(existingRole);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
RolePermissionEntity newRolePermission = _rolePermissionEntityFixture.Create();
|
||||
RoleEntity updatedRole = _roleEntityFixture.Create(id: existingRole.Id, roleName: existingRole.RoleName, rolePermissions: [newRolePermission], includeRolePermissions: true, createdBy: existingRole.CreatedBy, createdOnUtc: existingRole.CreatedOnUtc);
|
||||
updatedRole.UpdatedOnUtc = DateTime.UtcNow;
|
||||
updatedRole.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedRole, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<RoleEntity>? updatedEntry = _mockContext.ChangeTracker.Entries<RoleEntity>()
|
||||
.FirstOrDefault(e => e.Entity.Id == existingRole.Id);
|
||||
Assert.NotNull(updatedEntry);
|
||||
RolePermissionEntity storedPermission = Assert.Single(updatedEntry!.Entity.RolePermissions);
|
||||
Assert.Equal(newRolePermission.PermissionId, storedPermission.PermissionId);
|
||||
Assert.Equal(existingRole.Id, storedPermission.RoleId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAPermissionIsStillPresent_ShouldKeepItsIdentityAndAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
RolePermissionEntity existingRolePermission = _rolePermissionEntityFixture.Create();
|
||||
DateTime keptCreatedOnUtc = new(2020, 5, 6, 7, 8, 9, DateTimeKind.Utc);
|
||||
existingRolePermission.CreatedOnUtc = keptCreatedOnUtc;
|
||||
RoleEntity existingRole = existingRolePermission.Role;
|
||||
existingRole.RolePermissions = [existingRolePermission];
|
||||
|
||||
_mockContext.Roles.Add(existingRole);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
RolePermissionEntity incomingRolePermission = _rolePermissionEntityFixture.Create(
|
||||
roleId: existingRole.Id,
|
||||
role: existingRole,
|
||||
permissionId: existingRolePermission.PermissionId,
|
||||
permission: existingRolePermission.Permission);
|
||||
|
||||
RoleEntity updatedRole = _roleEntityFixture.Create(id: existingRole.Id, roleName: existingRole.RoleName, rolePermissions: [incomingRolePermission], includeRolePermissions: true, createdBy: existingRole.CreatedBy, createdOnUtc: existingRole.CreatedOnUtc);
|
||||
updatedRole.UpdatedOnUtc = DateTime.UtcNow;
|
||||
updatedRole.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedRole, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<RoleEntity>? updatedEntry = _mockContext.ChangeTracker.Entries<RoleEntity>()
|
||||
.FirstOrDefault(e => e.Entity.Id == existingRole.Id);
|
||||
Assert.NotNull(updatedEntry);
|
||||
RolePermissionEntity retainedPermission = Assert.Single(updatedEntry!.Entity.RolePermissions);
|
||||
Assert.Equal(existingRolePermission.Id, retainedPermission.Id);
|
||||
Assert.Equal(keptCreatedOnUtc, retainedPermission.CreatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenRoleExists_ShouldDeleteRoleAndReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity existingRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
|
||||
_mockContext.Roles.Add(existingRole);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(existingRole.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
|
||||
EntityEntry<RoleEntity>? deletedEntry = _mockContext.ChangeTracker.Entries<RoleEntity>()
|
||||
.FirstOrDefault(e => e.Entity.Id == existingRole.Id);
|
||||
Assert.NotNull(deletedEntry);
|
||||
Assert.Equal(EntityState.Deleted, deletedEntry!.State);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenRoleDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(nonExistentId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Authorization.RoleNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenRoleHasPermissions_ShouldDeleteRoleWithPermissions()
|
||||
{
|
||||
// Arrange
|
||||
RolePermissionEntity rolePermission = _rolePermissionEntityFixture.Create();
|
||||
RoleEntity existingRole = rolePermission.Role;
|
||||
existingRole.RolePermissions = [rolePermission];
|
||||
|
||||
_mockContext.Roles.Add(existingRole);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(existingRole.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
|
||||
EntityEntry<RoleEntity>? deletedEntry = _mockContext.ChangeTracker.Entries<RoleEntity>()
|
||||
.FirstOrDefault(e => e.Entity.Id == existingRole.Id);
|
||||
Assert.NotNull(deletedEntry);
|
||||
Assert.Equal(EntityState.Deleted, deletedEntry!.State);
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.DataAccess.Core.Repositories.Authorization;
|
||||
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.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UserRoleRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserRoleRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly UserRoleRepository _sut;
|
||||
private readonly UserRoleEntityFixture _userRoleEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserRoleRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public UserRoleRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new UserRoleRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenUserRoleIsValid_ShouldAddToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
UserRoleEntity userRole = _userRoleEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(userRole, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<UserRoleEntity>? addedUserRole = _mockContext.ChangeTracker.Entries<UserRoleEntity>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == userRole.Id);
|
||||
Assert.NotNull(addedUserRole);
|
||||
Assert.Equal(EntityState.Added, addedUserRole!.State);
|
||||
}
|
||||
}
|
||||
+1993
File diff suppressed because it is too large.
Load diff
+134
@@ -0,0 +1,134 @@
|
||||
#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.BookLibrary.Specifications;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.BookLibrary.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_ShouldMatchCaseInsensitively()
|
||||
{
|
||||
// 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_WhenOriginalTitleMatchesInDifferentCase_ShouldMatchCaseInsensitively()
|
||||
{
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
+538
@@ -0,0 +1,538 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
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="LibraryRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly LibraryRepository _sut;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryPathTemplatePartEntityFixture _libraryPathTemplatePartEntityFixture = 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: 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: 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<PaginatedResultDto<LibraryEntity>> result = await _sut.GetAllAsync<BaseFilterDto>(cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Data.Count);
|
||||
Assert.Equal(libraries, result.Value.Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenLibraryExists_ShouldUpdateScalarPropertiesAndContentLocations()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: ["/old/path"]);
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
|
||||
id: library.Id,
|
||||
userId: library.UserId,
|
||||
title: "Updated Title",
|
||||
libraryType: library.LibraryType,
|
||||
contentLocations: ["/new/path"]);
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenLibraryHasPathTemplateParts_ShouldAddLibraryAndItsPartsToContext()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
|
||||
LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Separator, representation: "/", isOptional: false);
|
||||
LibraryPathTemplatePartEntity thirdPart = _libraryPathTemplatePartEntityFixture.Create(position: 2, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(
|
||||
contentLocations: [],
|
||||
pathTemplateParts: [firstPart, secondPart, thirdPart],
|
||||
pathTemplateFingerprint: "path-template-fingerprint");
|
||||
|
||||
// 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);
|
||||
Assert.Equal("path-template-fingerprint", addedLibrary!.Entity.PathTemplateFingerprint);
|
||||
|
||||
List<EntityEntry<LibraryPathTemplatePartEntity>> partEntries = [.. _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
|
||||
.Where(entityEntry => entityEntry.State == EntityState.Added)];
|
||||
Assert.Equal(3, partEntries.Count);
|
||||
Assert.Equal([0, 1, 2], partEntries.Select(entityEntry => entityEntry.Entity.Position).OrderBy(position => position));
|
||||
|
||||
LibraryPathTemplatePartEntity storedFirstPart = partEntries.Single(entityEntry => entityEntry.Entity.Position == 0).Entity;
|
||||
Assert.Equal(LibraryPathPartKind.Artist, storedFirstPart.Kind);
|
||||
Assert.Equal("{0}", storedFirstPart.Representation);
|
||||
Assert.False(storedFirstPart.IsOptional);
|
||||
|
||||
LibraryPathTemplatePartEntity storedSecondPart = partEntries.Single(entityEntry => entityEntry.Entity.Position == 1).Entity;
|
||||
Assert.Equal(LibraryPathPartKind.Separator, storedSecondPart.Kind);
|
||||
Assert.Equal("/", storedSecondPart.Representation);
|
||||
Assert.False(storedSecondPart.IsOptional);
|
||||
|
||||
LibraryPathTemplatePartEntity storedThirdPart = partEntries.Single(entityEntry => entityEntry.Entity.Position == 2).Entity;
|
||||
Assert.Equal(LibraryPathPartKind.Series, storedThirdPart.Kind);
|
||||
Assert.Equal("{0}", storedThirdPart.Representation);
|
||||
Assert.True(storedThirdPart.IsOptional);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenPathTemplatePartRepresentationChanges_ShouldReplaceThatPart()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplatePartEntity keptPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
|
||||
LibraryPathTemplatePartEntity replacedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [keptPart, replacedPart]);
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryPathTemplatePartEntity replacementPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{1}", isOptional: false);
|
||||
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
|
||||
id: library.Id,
|
||||
userId: library.UserId,
|
||||
contentLocations: [],
|
||||
pathTemplateParts: [keptPart, replacementPart]);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<LibraryPathTemplatePartEntity>? replacedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
|
||||
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart));
|
||||
Assert.NotNull(replacedEntry);
|
||||
Assert.Equal(EntityState.Deleted, replacedEntry!.State);
|
||||
|
||||
EntityEntry<LibraryPathTemplatePartEntity>? keptEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
|
||||
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, keptPart));
|
||||
Assert.NotNull(keptEntry);
|
||||
Assert.Equal(EntityState.Unchanged, keptEntry!.State);
|
||||
|
||||
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
|
||||
Assert.False(retrievedResult.IsFailure);
|
||||
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
|
||||
Assert.Equal(2, retrievedLibrary.PathTemplateParts.Count);
|
||||
Assert.Equal("{0}", retrievedLibrary.PathTemplateParts.Single(part => part.Position == 0).Representation);
|
||||
Assert.Equal("{1}", retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1).Representation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenPathTemplatePartKindChanges_ShouldReplaceThatPart()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplatePartEntity keptPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
|
||||
LibraryPathTemplatePartEntity replacedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [keptPart, replacedPart]);
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryPathTemplatePartEntity replacementPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: false);
|
||||
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
|
||||
id: library.Id,
|
||||
userId: library.UserId,
|
||||
contentLocations: [],
|
||||
pathTemplateParts: [keptPart, replacementPart]);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<LibraryPathTemplatePartEntity>? replacedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
|
||||
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart));
|
||||
Assert.NotNull(replacedEntry);
|
||||
Assert.Equal(EntityState.Deleted, replacedEntry!.State);
|
||||
|
||||
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
|
||||
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
|
||||
Assert.Equal(LibraryPathPartKind.Series, retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1).Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenPathTemplatePartIsOptionalChanges_ShouldReplaceThatPart()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplatePartEntity keptPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
|
||||
LibraryPathTemplatePartEntity replacedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: false);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [keptPart, replacedPart]);
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryPathTemplatePartEntity replacementPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true);
|
||||
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
|
||||
id: library.Id,
|
||||
userId: library.UserId,
|
||||
contentLocations: [],
|
||||
pathTemplateParts: [keptPart, replacementPart]);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<LibraryPathTemplatePartEntity>? replacedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
|
||||
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart));
|
||||
Assert.NotNull(replacedEntry);
|
||||
Assert.Equal(EntityState.Deleted, replacedEntry!.State);
|
||||
|
||||
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
|
||||
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
|
||||
Assert.True(retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1).IsOptional);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenPathTemplatePartPositionIsRemoved_ShouldRemoveThatPart()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
|
||||
LibraryPathTemplatePartEntity removedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
|
||||
LibraryPathTemplatePartEntity thirdPart = _libraryPathTemplatePartEntityFixture.Create(position: 2, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [firstPart, removedPart, thirdPart]);
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
|
||||
id: library.Id,
|
||||
userId: library.UserId,
|
||||
contentLocations: [],
|
||||
pathTemplateParts: [firstPart, thirdPart]);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<LibraryPathTemplatePartEntity>? removedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
|
||||
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, removedPart));
|
||||
Assert.NotNull(removedEntry);
|
||||
Assert.Equal(EntityState.Deleted, removedEntry!.State);
|
||||
|
||||
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
|
||||
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
|
||||
Assert.Equal(2, retrievedLibrary.PathTemplateParts.Count);
|
||||
Assert.Equal([0, 2], retrievedLibrary.PathTemplateParts.Select(part => part.Position).OrderBy(position => position));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenPathTemplatePartPositionIsAdded_ShouldAddThatPart()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
|
||||
LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [firstPart, secondPart]);
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryPathTemplatePartEntity addedPart = _libraryPathTemplatePartEntityFixture.Create(position: 2, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true);
|
||||
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
|
||||
id: library.Id,
|
||||
userId: library.UserId,
|
||||
contentLocations: [],
|
||||
pathTemplateParts: [firstPart, secondPart, addedPart]);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<LibraryPathTemplatePartEntity>? addedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
|
||||
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, addedPart));
|
||||
Assert.NotNull(addedEntry);
|
||||
Assert.Equal(EntityState.Added, addedEntry!.State);
|
||||
|
||||
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
|
||||
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
|
||||
Assert.Equal(3, retrievedLibrary.PathTemplateParts.Count);
|
||||
Assert.Equal([0, 1, 2], retrievedLibrary.PathTemplateParts.Select(part => part.Position).OrderBy(position => position));
|
||||
|
||||
LibraryPathTemplatePartEntity storedAddedPart = retrievedLibrary.PathTemplateParts.Single(part => part.Position == 2);
|
||||
Assert.Equal(LibraryPathPartKind.Series, storedAddedPart.Kind);
|
||||
Assert.Equal("{0}", storedAddedPart.Representation);
|
||||
Assert.True(storedAddedPart.IsOptional);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenPathTemplatePartsAreUnchanged_ShouldKeepExistingParts()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
|
||||
LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [firstPart, secondPart]);
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryPathTemplatePartEntity equivalentFirstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
|
||||
LibraryPathTemplatePartEntity equivalentSecondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
|
||||
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
|
||||
id: library.Id,
|
||||
userId: library.UserId,
|
||||
contentLocations: [],
|
||||
pathTemplateParts: [equivalentFirstPart, equivalentSecondPart]);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
Assert.DoesNotContain(
|
||||
_mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>(),
|
||||
entityEntry => entityEntry.State == EntityState.Added || entityEntry.State == EntityState.Deleted);
|
||||
|
||||
EntityEntry<LibraryPathTemplatePartEntity>? firstEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
|
||||
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, firstPart));
|
||||
Assert.NotNull(firstEntry);
|
||||
Assert.Equal(EntityState.Unchanged, firstEntry!.State);
|
||||
|
||||
EntityEntry<LibraryPathTemplatePartEntity>? secondEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
|
||||
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, secondPart));
|
||||
Assert.NotNull(secondEntry);
|
||||
Assert.Equal(EntityState.Unchanged, secondEntry!.State);
|
||||
|
||||
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
|
||||
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
|
||||
Assert.Equal(2, retrievedLibrary.PathTemplateParts.Count);
|
||||
Assert.Same(firstPart, retrievedLibrary.PathTemplateParts.Single(part => part.Position == 0));
|
||||
Assert.Same(secondPart, retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenPathTemplateFingerprintChanges_ShouldUpdateIt()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [], pathTemplateFingerprint: "old-fingerprint");
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
|
||||
id: library.Id,
|
||||
userId: library.UserId,
|
||||
contentLocations: [],
|
||||
pathTemplateParts: [],
|
||||
pathTemplateFingerprint: "new-fingerprint");
|
||||
|
||||
// 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("new-fingerprint", retrievedLibrary!.PathTemplateFingerprint);
|
||||
}
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
#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: 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: 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 GetActiveScansAsync_WhenCalled_ShouldReturnPendingAndRunningScansOnly()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Running);
|
||||
LibraryScanEntity pendingScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Pending);
|
||||
LibraryScanEntity completedScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Completed);
|
||||
LibraryScanEntity canceledScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Canceled);
|
||||
LibraryScanEntity failedScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Failed);
|
||||
_mockContext.LibraryScans.AddRange(runningScan, pendingScan, completedScan, canceledScan, failedScan);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<LibraryScanEntity>> result = await _sut.GetActiveScansAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count());
|
||||
Assert.Contains(result.Value, libraryScan => libraryScan.Id == runningScan.Id);
|
||||
Assert.Contains(result.Value, libraryScan => libraryScan.Id == pendingScan.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenLibraryScanExists_ShouldUpdateItsScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create();
|
||||
_mockContext.LibraryScans.Add(libraryScan);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryScanEntity updatedScan = _libraryScanEntityFixture.Create(id: libraryScan.Id, libraryId: libraryScan.LibraryId, userId: libraryScan.UserId, status: LibraryScanJobStatus.Completed, libraryEntity: libraryScan.Library, createdOnUtc: libraryScan.CreatedOnUtc);
|
||||
updatedScan.UpdatedOnUtc = DateTime.UtcNow;
|
||||
updatedScan.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);
|
||||
}
|
||||
}
|
||||
+416
@@ -0,0 +1,416 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.Repositories.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
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.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ConsumptionStatisticsRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ConsumptionStatisticsRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly ConsumptionStatisticsRepository _sut;
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ConsumptionStatisticsRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public ConsumptionStatisticsRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new ConsumptionStatisticsRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenCalled_ShouldReturnOnlyTheRecordsOfTheUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity firstRecord = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
|
||||
MediaConsumptionRecordEntity secondRecord = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
|
||||
MediaConsumptionRecordEntity recordOfAnotherUser = _mediaConsumptionRecordEntityFixture.Create(userId: Guid.NewGuid());
|
||||
_mockContext.MediaConsumptionRecords.AddRange(firstRecord, secondRecord, recordOfAnotherUser);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForUserAsync(userId, null, null, null, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.All(result.Value, record => Assert.Equal(userId, record.UserId));
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == recordOfAnotherUser.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenNoFilterIsProvided_ShouldReturnEveryRecordOfTheUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity movieRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId,
|
||||
libraryId: Guid.NewGuid(),
|
||||
mediaKind: MediaKind.Movie,
|
||||
startedOnUtc: new DateTime(2024, 6, 1, 10, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity bookRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId,
|
||||
libraryId: Guid.NewGuid(),
|
||||
mediaKind: MediaKind.Book,
|
||||
startedOnUtc: new DateTime(2025, 6, 1, 10, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity trackRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId,
|
||||
libraryId: Guid.NewGuid(),
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
startedOnUtc: new DateTime(2026, 6, 1, 10, 0, 0, DateTimeKind.Utc));
|
||||
_mockContext.MediaConsumptionRecords.AddRange(movieRecord, bookRecord, trackRecord);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForUserAsync(userId, null, null, null, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count);
|
||||
Assert.Equal(
|
||||
new[] { movieRecord.Id, bookRecord.Id, trackRecord.Id }.OrderBy(id => id),
|
||||
result.Value.Select(record => record.Id).OrderBy(id => id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenLibraryFilterIsProvided_ShouldReturnOnlyTheRecordsOfThatLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity firstRecordOfLibrary = _mediaConsumptionRecordEntityFixture.Create(userId: userId, libraryId: libraryId);
|
||||
MediaConsumptionRecordEntity secondRecordOfLibrary = _mediaConsumptionRecordEntityFixture.Create(userId: userId, libraryId: libraryId);
|
||||
MediaConsumptionRecordEntity recordOfAnotherLibrary = _mediaConsumptionRecordEntityFixture.Create(userId: userId, libraryId: Guid.NewGuid());
|
||||
MediaConsumptionRecordEntity recordOfAnotherUserInTheLibrary = _mediaConsumptionRecordEntityFixture.Create(userId: Guid.NewGuid(), libraryId: libraryId);
|
||||
_mockContext.MediaConsumptionRecords.AddRange(
|
||||
firstRecordOfLibrary, secondRecordOfLibrary, recordOfAnotherLibrary, recordOfAnotherUserInTheLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForUserAsync(userId, libraryId, null, null, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.All(result.Value, record => Assert.Equal(libraryId, record.LibraryId));
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == recordOfAnotherLibrary.Id);
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == recordOfAnotherUserInTheLibrary.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenMediaKindFilterIsProvided_ShouldReturnOnlyTheRecordsOfThatKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity movieRecord = _mediaConsumptionRecordEntityFixture.Create(userId: userId, mediaKind: MediaKind.Movie);
|
||||
MediaConsumptionRecordEntity anotherMovieRecord = _mediaConsumptionRecordEntityFixture.Create(userId: userId, mediaKind: MediaKind.Movie);
|
||||
MediaConsumptionRecordEntity bookRecord = _mediaConsumptionRecordEntityFixture.Create(userId: userId, mediaKind: MediaKind.Book);
|
||||
MediaConsumptionRecordEntity recordOfAnotherUser = _mediaConsumptionRecordEntityFixture.Create(userId: Guid.NewGuid(), mediaKind: MediaKind.Movie);
|
||||
_mockContext.MediaConsumptionRecords.AddRange(movieRecord, anotherMovieRecord, bookRecord, recordOfAnotherUser);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForUserAsync(userId, null, MediaKind.Movie, null, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.All(result.Value, record => Assert.Equal(MediaKind.Movie, record.MediaKind));
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == bookRecord.Id);
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == recordOfAnotherUser.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenFromUtcIsProvided_ShouldReturnOnlyTheRecordsStartedAtOrAfterIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
DateTime fromUtc = new(2025, 1, 10, 12, 0, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity recordBeforeTheRange = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, startedOnUtc: fromUtc.AddMilliseconds(-1));
|
||||
MediaConsumptionRecordEntity recordAtTheBoundary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, startedOnUtc: fromUtc);
|
||||
MediaConsumptionRecordEntity recordAfterTheBoundary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, startedOnUtc: fromUtc.AddDays(1));
|
||||
_mockContext.MediaConsumptionRecords.AddRange(recordBeforeTheRange, recordAtTheBoundary, recordAfterTheBoundary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForUserAsync(userId, null, null, fromUtc, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
// The boundary is inclusive, in the same way the indexed range scan of the storage medium treats it.
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, record => record.Id == recordAtTheBoundary.Id);
|
||||
Assert.Contains(result.Value, record => record.Id == recordAfterTheBoundary.Id);
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == recordBeforeTheRange.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenToUtcIsProvided_ShouldReturnOnlyTheRecordsStartedAtOrBeforeIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
DateTime toUtc = new(2025, 1, 20, 12, 0, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity recordBeforeTheBoundary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, startedOnUtc: toUtc.AddDays(-1));
|
||||
MediaConsumptionRecordEntity recordAtTheBoundary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, startedOnUtc: toUtc);
|
||||
MediaConsumptionRecordEntity recordAfterTheRange = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, startedOnUtc: toUtc.AddMilliseconds(1));
|
||||
_mockContext.MediaConsumptionRecords.AddRange(recordBeforeTheBoundary, recordAtTheBoundary, recordAfterTheRange);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForUserAsync(userId, null, null, null, toUtc, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
// The boundary is inclusive, in the same way the indexed range scan of the storage medium treats it.
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, record => record.Id == recordBeforeTheBoundary.Id);
|
||||
Assert.Contains(result.Value, record => record.Id == recordAtTheBoundary.Id);
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == recordAfterTheRange.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenAllFiltersAreProvided_ShouldApplyEveryFilter()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
DateTime fromUtc = new(2025, 1, 10, 0, 0, 0, DateTimeKind.Utc);
|
||||
DateTime toUtc = new(2025, 1, 20, 0, 0, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity matchingRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity recordOfAnotherLibrary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, libraryId: Guid.NewGuid(), mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity recordOfAnotherKind = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, libraryId: libraryId, mediaKind: MediaKind.Book, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity recordBeforeTheRange = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: fromUtc.AddDays(-1));
|
||||
MediaConsumptionRecordEntity recordAfterTheRange = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: toUtc.AddDays(1));
|
||||
MediaConsumptionRecordEntity matchingRecordOfAnotherUser = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(), libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
_mockContext.MediaConsumptionRecords.AddRange(
|
||||
matchingRecord, recordOfAnotherLibrary, recordOfAnotherKind, recordBeforeTheRange, recordAfterTheRange, matchingRecordOfAnotherUser);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForUserAsync(userId, libraryId, MediaKind.Movie, fromUtc, toUtc, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
MediaConsumptionRecordEntity returnedRecord = Assert.Single(result.Value);
|
||||
Assert.Equal(matchingRecord.Id, returnedRecord.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenNothingMatches_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, libraryId: Guid.NewGuid(), mediaKind: MediaKind.Book, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
_mockContext.MediaConsumptionRecords.Add(record);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForUserAsync(
|
||||
userId, Guid.NewGuid(), MediaKind.Movie, new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc), new DateTime(2025, 1, 31, 0, 0, 0, DateTimeKind.Utc), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForAllUsersAsync_WhenCalled_ShouldReturnTheRecordsOfEveryUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstUserId = Guid.NewGuid();
|
||||
Guid secondUserId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity firstUserRecord = _mediaConsumptionRecordEntityFixture.Create(userId: firstUserId, mediaKind: MediaKind.Movie);
|
||||
MediaConsumptionRecordEntity secondUserMovieRecord = _mediaConsumptionRecordEntityFixture.Create(userId: secondUserId, mediaKind: MediaKind.Movie);
|
||||
MediaConsumptionRecordEntity secondUserBookRecord = _mediaConsumptionRecordEntityFixture.Create(userId: secondUserId, mediaKind: MediaKind.Book);
|
||||
_mockContext.MediaConsumptionRecords.AddRange(firstUserRecord, secondUserMovieRecord, secondUserBookRecord);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForAllUsersAsync(null, null, null, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count);
|
||||
Assert.Contains(result.Value, record => record.Id == firstUserRecord.Id);
|
||||
Assert.Contains(result.Value, record => record.Id == secondUserMovieRecord.Id);
|
||||
Assert.Contains(result.Value, record => record.Id == secondUserBookRecord.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForAllUsersAsync_WhenLibraryFilterIsProvided_ShouldReturnTheRecordsOfThatLibraryOfEveryUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity firstUserRecord = _mediaConsumptionRecordEntityFixture.Create(userId: Guid.NewGuid(), libraryId: libraryId);
|
||||
MediaConsumptionRecordEntity secondUserRecord = _mediaConsumptionRecordEntityFixture.Create(userId: Guid.NewGuid(), libraryId: libraryId);
|
||||
MediaConsumptionRecordEntity otherLibraryRecord = _mediaConsumptionRecordEntityFixture.Create(userId: Guid.NewGuid(), libraryId: Guid.NewGuid());
|
||||
_mockContext.MediaConsumptionRecords.AddRange(firstUserRecord, secondUserRecord, otherLibraryRecord);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForAllUsersAsync(libraryId, null, null, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.All(result.Value, record => Assert.Equal(libraryId, record.LibraryId));
|
||||
// The filter is applied across every user, instead of one user at a time.
|
||||
Assert.Contains(result.Value, record => record.UserId == firstUserRecord.UserId);
|
||||
Assert.Contains(result.Value, record => record.UserId == secondUserRecord.UserId);
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == otherLibraryRecord.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForAllUsersAsync_WhenMediaKindFilterIsProvided_ShouldReturnTheRecordsOfThatKindOfEveryUser()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionRecordEntity firstUserMovieRecord = _mediaConsumptionRecordEntityFixture.Create(userId: Guid.NewGuid(), mediaKind: MediaKind.Movie);
|
||||
MediaConsumptionRecordEntity secondUserMovieRecord = _mediaConsumptionRecordEntityFixture.Create(userId: Guid.NewGuid(), mediaKind: MediaKind.Movie);
|
||||
MediaConsumptionRecordEntity bookRecord = _mediaConsumptionRecordEntityFixture.Create(userId: Guid.NewGuid(), mediaKind: MediaKind.Book);
|
||||
_mockContext.MediaConsumptionRecords.AddRange(firstUserMovieRecord, secondUserMovieRecord, bookRecord);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForAllUsersAsync(null, MediaKind.Movie, null, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.All(result.Value, record => Assert.Equal(MediaKind.Movie, record.MediaKind));
|
||||
Assert.Contains(result.Value, record => record.UserId == firstUserMovieRecord.UserId);
|
||||
Assert.Contains(result.Value, record => record.UserId == secondUserMovieRecord.UserId);
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == bookRecord.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForAllUsersAsync_WhenFromUtcIsProvided_ShouldReturnOnlyTheRecordsStartedAtOrAfterIt()
|
||||
{
|
||||
// Arrange
|
||||
DateTime fromUtc = new(2025, 1, 10, 12, 0, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity recordBeforeTheRange = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(), startedOnUtc: fromUtc.AddMilliseconds(-1));
|
||||
MediaConsumptionRecordEntity recordAtTheBoundary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(), startedOnUtc: fromUtc);
|
||||
MediaConsumptionRecordEntity recordAfterTheBoundary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(), startedOnUtc: fromUtc.AddDays(1));
|
||||
_mockContext.MediaConsumptionRecords.AddRange(recordBeforeTheRange, recordAtTheBoundary, recordAfterTheBoundary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForAllUsersAsync(null, null, fromUtc, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, record => record.Id == recordAtTheBoundary.Id);
|
||||
Assert.Contains(result.Value, record => record.Id == recordAfterTheBoundary.Id);
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == recordBeforeTheRange.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForAllUsersAsync_WhenToUtcIsProvided_ShouldReturnOnlyTheRecordsStartedAtOrBeforeIt()
|
||||
{
|
||||
// Arrange
|
||||
DateTime toUtc = new(2025, 1, 20, 12, 0, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity recordBeforeTheBoundary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(), startedOnUtc: toUtc.AddDays(-1));
|
||||
MediaConsumptionRecordEntity recordAtTheBoundary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(), startedOnUtc: toUtc);
|
||||
MediaConsumptionRecordEntity recordAfterTheRange = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(), startedOnUtc: toUtc.AddMilliseconds(1));
|
||||
_mockContext.MediaConsumptionRecords.AddRange(recordBeforeTheBoundary, recordAtTheBoundary, recordAfterTheRange);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForAllUsersAsync(null, null, null, toUtc, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, record => record.Id == recordBeforeTheBoundary.Id);
|
||||
Assert.Contains(result.Value, record => record.Id == recordAtTheBoundary.Id);
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == recordAfterTheRange.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForAllUsersAsync_WhenAllFiltersAreProvided_ShouldApplyEveryFilterAcrossUsers()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
DateTime fromUtc = new(2025, 1, 10, 0, 0, 0, DateTimeKind.Utc);
|
||||
DateTime toUtc = new(2025, 1, 20, 0, 0, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity matchingFirstUserRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(), libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity matchingSecondUserRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(), libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 16, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity recordOfAnotherLibrary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(), libraryId: Guid.NewGuid(), mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity recordOfAnotherKind = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(), libraryId: libraryId, mediaKind: MediaKind.Book, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity recordOutsideTheRange = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(), libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: toUtc.AddDays(1));
|
||||
_mockContext.MediaConsumptionRecords.AddRange(
|
||||
matchingFirstUserRecord, matchingSecondUserRecord, recordOfAnotherLibrary, recordOfAnotherKind, recordOutsideTheRange);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForAllUsersAsync(libraryId, MediaKind.Movie, fromUtc, toUtc, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, record => record.Id == matchingFirstUserRecord.Id);
|
||||
Assert.Contains(result.Value, record => record.Id == matchingSecondUserRecord.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForAllUsersAsync_WhenNothingMatches_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(), libraryId: Guid.NewGuid(), mediaKind: MediaKind.Book, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
_mockContext.MediaConsumptionRecords.Add(record);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await _sut.GetForAllUsersAsync(
|
||||
Guid.NewGuid(), MediaKind.Movie, new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc), new DateTime(2025, 1, 31, 0, 0, 0, DateTimeKind.Utc), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
}
|
||||
+609
@@ -0,0 +1,609 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.Repositories.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
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.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaConsumptionRecordRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaConsumptionRecordRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly MediaConsumptionRecordRepository _sut;
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaConsumptionRecordRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public MediaConsumptionRecordRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new MediaConsumptionRecordRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenRecordIsNew_ShouldAddTheRecordToTheContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(record, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<MediaConsumptionRecordEntity>? addedRecord = _mockContext.ChangeTracker.Entries<MediaConsumptionRecordEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == record.Id);
|
||||
Assert.NotNull(addedRecord);
|
||||
Assert.Same(record, addedRecord.Entity);
|
||||
Assert.Equal(record.UserId, addedRecord.Entity.UserId);
|
||||
Assert.Equal(record.MediaItemId, addedRecord.Entity.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdForUserAsync_WhenRecordBelongsToTheUser_ShouldReturnTheRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(userId: userId, mediaKind: MediaKind.Movie);
|
||||
_mockContext.MediaConsumptionRecords.Add(record);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaConsumptionRecordEntity?> result = await _sut.GetByIdForUserAsync(record.Id, userId, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(record.Id, result.Value!.Id);
|
||||
Assert.Equal(userId, result.Value.UserId);
|
||||
Assert.Equal(MediaKind.Movie, result.Value.MediaKind);
|
||||
Assert.Equal(record.MediaItemId, result.Value.MediaItemId);
|
||||
Assert.Equal(record.LibraryId, result.Value.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdForUserAsync_WhenRecordBelongsToAnotherUser_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(userId: Guid.NewGuid());
|
||||
_mockContext.MediaConsumptionRecords.Add(record);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaConsumptionRecordEntity?> result = await _sut.GetByIdForUserAsync(record.Id, Guid.NewGuid(), cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdForUserAsync_WhenRecordDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<MediaConsumptionRecordEntity?> result = await _sut.GetByIdForUserAsync(Guid.NewGuid(), Guid.NewGuid(), cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdForUserAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnTheRecordAndLeaveTheTrackedRowUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
|
||||
_mockContext.MediaConsumptionRecords.Add(record);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaConsumptionRecordEntity?> result = await _sut.GetByIdForUserAsync(record.Id, userId, shouldTrackEntities: false, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(record.Id, result.Value!.Id);
|
||||
Assert.Equal(record.UserId, result.Value.UserId);
|
||||
// The in-memory medium behind the mocked context does not materialize a distinct instance for a no-tracking query, so the detached
|
||||
// identity of the returned record is asserted against the real SQLite provider in the integration tests. What is asserted here is
|
||||
// that the read is served and leaves the row the context already tracks exactly as it was stored.
|
||||
EntityEntry<MediaConsumptionRecordEntity> seededEntry = _mockContext.Entry(record);
|
||||
Assert.Equal(EntityState.Unchanged, seededEntry.State);
|
||||
Assert.Equal(record.Id, seededEntry.Entity.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdForUserAsync_WhenEntitiesShouldBeTracked_ShouldReturnTheTrackedInstance()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
|
||||
_mockContext.MediaConsumptionRecords.Add(record);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaConsumptionRecordEntity?> result = await _sut.GetByIdForUserAsync(record.Id, userId, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Same(record, result.Value);
|
||||
Assert.Equal(EntityState.Unchanged, _mockContext.Entry(result.Value!).State);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateForUserAsync_WhenNoEditableValueChanged_ShouldReturnUpdatedWithoutBumpingTheVersion()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
DateTime startedOnUtc = new(2025, 1, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
DateTime lastActivityOnUtc = new(2025, 1, 1, 10, 30, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity storedRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.InProgress,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
includeEndedOnUtc: false,
|
||||
consumedDurationMilliseconds: 60_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 30_000,
|
||||
includeLastPositionLocation: false,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0,
|
||||
version: 3);
|
||||
_mockContext.MediaConsumptionRecords.Add(storedRecord);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
MediaConsumptionRecordEntity incoming = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.InProgress,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
includeEndedOnUtc: false,
|
||||
consumedDurationMilliseconds: 60_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 30_000,
|
||||
includeLastPositionLocation: false,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0,
|
||||
version: 3);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateForUserAsync(incoming, userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<MediaConsumptionRecordEntity> storedEntry = _mockContext.Entry(storedRecord);
|
||||
Assert.Equal(EntityState.Unchanged, storedEntry.State);
|
||||
Assert.Equal(3L, storedEntry.Entity.Version);
|
||||
Assert.DoesNotContain(_mockContext.ChangeTracker.Entries<MediaConsumptionRecordEntity>(), entry => entry.State == EntityState.Modified);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateForUserAsync_WhenAnEditableValueChanged_ShouldCopyTheValuesAndIncrementTheVersion()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
DateTime startedOnUtc = new(2025, 1, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
DateTime lastActivityOnUtc = new(2025, 1, 1, 10, 30, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity storedRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.InProgress,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
includeEndedOnUtc: false,
|
||||
consumedDurationMilliseconds: 60_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 30_000,
|
||||
includeLastPositionLocation: false,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0,
|
||||
version: 3);
|
||||
_mockContext.MediaConsumptionRecords.Add(storedRecord);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
DateTime endedOnUtc = new(2025, 1, 1, 11, 0, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity incoming = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: Guid.NewGuid(),
|
||||
libraryId: Guid.NewGuid(),
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Completed,
|
||||
startedOnUtc: new(2024, 12, 31, 9, 0, 0, DateTimeKind.Utc),
|
||||
lastActivityOnUtc: new(2025, 1, 1, 10, 55, 0, DateTimeKind.Utc),
|
||||
endedOnUtc: endedOnUtc,
|
||||
consumedDurationMilliseconds: 600_000,
|
||||
lastPositionKind: MediaPositionKind.Location,
|
||||
includeLastPositionTimeOffsetMilliseconds: false,
|
||||
lastPositionLocation: "chapter-12",
|
||||
lastProgressFraction: 1.0,
|
||||
consecutivePagesRead: 42,
|
||||
version: 3);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateForUserAsync(incoming, userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<MediaConsumptionRecordEntity> storedEntry = _mockContext.Entry(storedRecord);
|
||||
Assert.Equal(EntityState.Modified, storedEntry.State);
|
||||
MediaConsumptionRecordEntity updatedRecord = storedEntry.Entity;
|
||||
// The stored identity is never reassigned by an edit.
|
||||
Assert.Equal(recordId, updatedRecord.Id);
|
||||
Assert.Equal(userId, updatedRecord.UserId);
|
||||
Assert.Equal(libraryId, updatedRecord.LibraryId);
|
||||
Assert.Equal(MediaKind.Movie, updatedRecord.MediaKind);
|
||||
Assert.Equal(mediaItemId, updatedRecord.MediaItemId);
|
||||
Assert.Equal(startedOnUtc, updatedRecord.StartedOnUtc);
|
||||
// The editable values are copied from the incoming record.
|
||||
Assert.Equal(ConsumptionStatus.Completed, updatedRecord.Status);
|
||||
Assert.Equal(new DateTime(2025, 1, 1, 10, 55, 0, DateTimeKind.Utc), updatedRecord.LastActivityOnUtc);
|
||||
Assert.Equal(endedOnUtc, updatedRecord.EndedOnUtc);
|
||||
Assert.Equal(600_000L, updatedRecord.ConsumedDurationMilliseconds);
|
||||
Assert.Equal(MediaPositionKind.Location, updatedRecord.LastPositionKind);
|
||||
Assert.Null(updatedRecord.LastPositionTimeOffsetMilliseconds);
|
||||
Assert.Equal("chapter-12", updatedRecord.LastPositionLocation);
|
||||
Assert.Equal(1.0, updatedRecord.LastProgressFraction);
|
||||
Assert.Equal(42, updatedRecord.ConsecutivePagesRead);
|
||||
// The version is incremented by exactly one for a single edit.
|
||||
Assert.Equal(4L, updatedRecord.Version);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateForUserAsync_WhenOnlyIdentityValuesDiffer_ShouldReturnUpdatedWithoutBumpingTheVersion()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
DateTime startedOnUtc = new(2025, 1, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
DateTime lastActivityOnUtc = new(2025, 1, 1, 10, 30, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity storedRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.InProgress,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
includeEndedOnUtc: false,
|
||||
consumedDurationMilliseconds: 60_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 30_000,
|
||||
includeLastPositionLocation: false,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0,
|
||||
version: 3);
|
||||
_mockContext.MediaConsumptionRecords.Add(storedRecord);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
MediaConsumptionRecordEntity incoming = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: Guid.NewGuid(),
|
||||
libraryId: Guid.NewGuid(),
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.InProgress,
|
||||
startedOnUtc: new(2024, 12, 31, 9, 0, 0, DateTimeKind.Utc),
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
includeEndedOnUtc: false,
|
||||
consumedDurationMilliseconds: 60_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 30_000,
|
||||
includeLastPositionLocation: false,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0,
|
||||
version: 3);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateForUserAsync(incoming, userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<MediaConsumptionRecordEntity> storedEntry = _mockContext.Entry(storedRecord);
|
||||
Assert.Equal(EntityState.Unchanged, storedEntry.State);
|
||||
Assert.Equal(3L, storedEntry.Entity.Version);
|
||||
Assert.Equal(userId, storedEntry.Entity.UserId);
|
||||
Assert.Equal(libraryId, storedEntry.Entity.LibraryId);
|
||||
Assert.Equal(MediaKind.Movie, storedEntry.Entity.MediaKind);
|
||||
Assert.Equal(mediaItemId, storedEntry.Entity.MediaItemId);
|
||||
Assert.Equal(startedOnUtc, storedEntry.Entity.StartedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateForUserAsync_WhenRecordDoesNotExist_ShouldReturnConsumptionRecordNotFound()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionRecordEntity incoming = _mediaConsumptionRecordEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateForUserAsync(incoming, incoming.UserId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.MediaConsumption.ConsumptionRecordNotFound, result.FirstError);
|
||||
Assert.Empty(_mockContext.ChangeTracker.Entries<MediaConsumptionRecordEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateForUserAsync_WhenRecordBelongsToAnotherUser_ShouldReturnConsumptionRecordNotFoundAndNotModifyIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid ownerId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity storedRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: ownerId,
|
||||
status: ConsumptionStatus.InProgress,
|
||||
includeEndedOnUtc: false,
|
||||
lastProgressFraction: 0.5,
|
||||
version: 3);
|
||||
_mockContext.MediaConsumptionRecords.Add(storedRecord);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
MediaConsumptionRecordEntity incoming = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: storedRecord.Id,
|
||||
userId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Completed,
|
||||
lastProgressFraction: 1.0,
|
||||
version: 3);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateForUserAsync(incoming, Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.MediaConsumption.ConsumptionRecordNotFound, result.FirstError);
|
||||
EntityEntry<MediaConsumptionRecordEntity> storedEntry = _mockContext.Entry(storedRecord);
|
||||
Assert.Equal(EntityState.Unchanged, storedEntry.State);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, storedEntry.Entity.Status);
|
||||
Assert.Equal(0.5, storedEntry.Entity.LastProgressFraction);
|
||||
Assert.Equal(3L, storedEntry.Entity.Version);
|
||||
Assert.Equal(ownerId, storedEntry.Entity.UserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteForUserAsync_WhenRecordBelongsToTheUser_ShouldRemoveTheRecordAndReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
|
||||
_mockContext.MediaConsumptionRecords.Add(record);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteForUserAsync(record.Id, userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
|
||||
EntityEntry<MediaConsumptionRecordEntity>? deletedRecord = _mockContext.ChangeTracker.Entries<MediaConsumptionRecordEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Deleted && entry.Entity.Id == record.Id);
|
||||
Assert.NotNull(deletedRecord);
|
||||
|
||||
await _mockContext.SaveChangesAsync();
|
||||
Assert.Null(await _mockContext.MediaConsumptionRecords.FirstOrDefaultAsync(candidate => candidate.Id == record.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteForUserAsync_WhenRecordBelongsToAnotherUser_ShouldLeaveTheRecordUntouched()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(userId: Guid.NewGuid());
|
||||
_mockContext.MediaConsumptionRecords.Add(record);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteForUserAsync(record.Id, Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
Assert.DoesNotContain(_mockContext.ChangeTracker.Entries<MediaConsumptionRecordEntity>(), entry => entry.State == EntityState.Deleted);
|
||||
Assert.Equal(EntityState.Unchanged, _mockContext.Entry(record).State);
|
||||
|
||||
await _mockContext.SaveChangesAsync();
|
||||
Assert.NotNull(await _mockContext.MediaConsumptionRecords.FirstOrDefaultAsync(candidate => candidate.Id == record.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteForUserAsync_WhenRecordDoesNotExist_ShouldReturnDeletedWithoutChanges()
|
||||
{
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteForUserAsync(Guid.NewGuid(), Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
Assert.Empty(_mockContext.ChangeTracker.Entries<MediaConsumptionRecordEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAllByMediaItemIdForUserAsync_WhenRecordsMatchAllFourParts_ShouldRemoveOnlyTheMatchingRecords()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid otherUserId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid otherLibraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid otherMediaItemId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity matchingFirst = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId);
|
||||
MediaConsumptionRecordEntity matchingSecond = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId);
|
||||
MediaConsumptionRecordEntity otherUser = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: otherUserId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId);
|
||||
MediaConsumptionRecordEntity otherKind = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: mediaItemId);
|
||||
MediaConsumptionRecordEntity otherItem = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: otherMediaItemId);
|
||||
MediaConsumptionRecordEntity otherLibrary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId,
|
||||
libraryId: otherLibraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId);
|
||||
_mockContext.MediaConsumptionRecords.AddRange(matchingFirst, matchingSecond, otherUser, otherKind, otherItem, otherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteAllByMediaItemIdForUserAsync(userId, MediaKind.Movie, mediaItemId, libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
|
||||
List<Guid> deletedRecordIds = [.. _mockContext.ChangeTracker.Entries<MediaConsumptionRecordEntity>()
|
||||
.Where(entry => entry.State == EntityState.Deleted)
|
||||
.Select(entry => entry.Entity.Id)
|
||||
.OrderBy(id => id)];
|
||||
Assert.Equal(
|
||||
new[] { matchingFirst.Id, matchingSecond.Id }.OrderBy(id => id),
|
||||
deletedRecordIds);
|
||||
|
||||
await _mockContext.SaveChangesAsync();
|
||||
List<Guid> remainingRecordIds = await _mockContext.MediaConsumptionRecords
|
||||
.AsNoTracking()
|
||||
.Select(record => record.Id)
|
||||
.ToListAsync();
|
||||
Assert.Equal(
|
||||
new[] { otherUser.Id, otherKind.Id, otherItem.Id, otherLibrary.Id }.OrderBy(id => id),
|
||||
remainingRecordIds.OrderBy(id => id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAllByMediaItemIdForUserAsync_WhenNoRecordMatches_ShouldReturnDeletedWithoutChanges()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: Guid.NewGuid(),
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: Guid.NewGuid());
|
||||
_mockContext.MediaConsumptionRecords.Add(record);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteAllByMediaItemIdForUserAsync(Guid.NewGuid(), MediaKind.Movie, Guid.NewGuid(), Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
Assert.DoesNotContain(_mockContext.ChangeTracker.Entries<MediaConsumptionRecordEntity>(), entry => entry.State == EntityState.Deleted);
|
||||
|
||||
await _mockContext.SaveChangesAsync();
|
||||
Assert.NotNull(await _mockContext.MediaConsumptionRecords.FirstOrDefaultAsync(candidate => candidate.Id == record.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAllForUserAsync_WhenTheUserHasRecords_ShouldRemoveOnlyTheirRecords()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity firstRecord = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
|
||||
MediaConsumptionRecordEntity secondRecord = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
|
||||
MediaConsumptionRecordEntity otherUserRecord = _mediaConsumptionRecordEntityFixture.Create(userId: Guid.NewGuid());
|
||||
_mockContext.MediaConsumptionRecords.AddRange(firstRecord, secondRecord, otherUserRecord);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteAllForUserAsync(userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
|
||||
List<Guid> deletedRecordIds = [.. _mockContext.ChangeTracker.Entries<MediaConsumptionRecordEntity>()
|
||||
.Where(entry => entry.State == EntityState.Deleted)
|
||||
.Select(entry => entry.Entity.Id)
|
||||
.OrderBy(id => id)];
|
||||
Assert.Equal(
|
||||
new[] { firstRecord.Id, secondRecord.Id }.OrderBy(id => id),
|
||||
deletedRecordIds);
|
||||
|
||||
await _mockContext.SaveChangesAsync();
|
||||
List<Guid> remainingRecordIds = await _mockContext.MediaConsumptionRecords
|
||||
.AsNoTracking()
|
||||
.Select(record => record.Id)
|
||||
.ToListAsync();
|
||||
Assert.Equal([otherUserRecord.Id], remainingRecordIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAllForUserAsync_WhenTheUserHasNoRecords_ShouldReturnDeletedWithoutChanges()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionRecordEntity otherUserRecord = _mediaConsumptionRecordEntityFixture.Create(userId: Guid.NewGuid());
|
||||
_mockContext.MediaConsumptionRecords.Add(otherUserRecord);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteAllForUserAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
Assert.DoesNotContain(_mockContext.ChangeTracker.Entries<MediaConsumptionRecordEntity>(), entry => entry.State == EntityState.Deleted);
|
||||
|
||||
await _mockContext.SaveChangesAsync();
|
||||
Assert.NotNull(await _mockContext.MediaConsumptionRecords.FirstOrDefaultAsync(candidate => candidate.Id == otherUserRecord.Id));
|
||||
}
|
||||
}
|
||||
+523
@@ -0,0 +1,523 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.Repositories.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
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.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaResumePointRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaResumePointRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly MediaResumePointRepository _sut;
|
||||
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaResumePointRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public MediaResumePointRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new MediaResumePointRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAndMediaItemAsync_WhenResumePointMatchesUserKindAndItem_ShouldReturnTheResumePoint()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
MediaResumePointEntity resumePoint = _mediaResumePointEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId);
|
||||
_mockContext.MediaResumePoints.Add(resumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaResumePointEntity?> result = await _sut.GetForUserAndMediaItemAsync(userId, MediaKind.Movie, mediaItemId, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(resumePoint.Id, result.Value!.Id);
|
||||
Assert.Equal(userId, result.Value.UserId);
|
||||
Assert.Equal(MediaKind.Movie, result.Value.MediaKind);
|
||||
Assert.Equal(mediaItemId, result.Value.MediaItemId);
|
||||
Assert.Equal(resumePoint.LibraryId, result.Value.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAndMediaItemAsync_WhenTheResumePointBelongsToAnotherUser_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
MediaResumePointEntity resumePoint = _mediaResumePointEntityFixture.Create(
|
||||
userId: Guid.NewGuid(),
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId);
|
||||
_mockContext.MediaResumePoints.Add(resumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaResumePointEntity?> result = await _sut.GetForUserAndMediaItemAsync(Guid.NewGuid(), MediaKind.Movie, mediaItemId, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAndMediaItemAsync_WhenTheResumePointIsForAnotherMediaKind_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
MediaResumePointEntity resumePoint = _mediaResumePointEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: mediaItemId);
|
||||
_mockContext.MediaResumePoints.Add(resumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaResumePointEntity?> result = await _sut.GetForUserAndMediaItemAsync(userId, MediaKind.Movie, mediaItemId, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAndMediaItemAsync_WhenTheResumePointIsForAnotherMediaItem_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaResumePointEntity resumePoint = _mediaResumePointEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: Guid.NewGuid());
|
||||
_mockContext.MediaResumePoints.Add(resumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaResumePointEntity?> result = await _sut.GetForUserAndMediaItemAsync(userId, MediaKind.Movie, Guid.NewGuid(), cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAndMediaItemAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnTheResumePointAndLeaveTheTrackedRowUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
MediaResumePointEntity resumePoint = _mediaResumePointEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId);
|
||||
_mockContext.MediaResumePoints.Add(resumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaResumePointEntity?> result = await _sut.GetForUserAndMediaItemAsync(userId, MediaKind.Movie, mediaItemId, shouldTrackEntities: false, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(resumePoint.Id, result.Value!.Id);
|
||||
Assert.Equal(resumePoint.UserId, result.Value.UserId);
|
||||
// The in-memory medium behind the mocked context does not materialize a distinct instance for a no-tracking query, so the detached
|
||||
// identity of the returned resume point is asserted against the real SQLite provider in the integration tests.
|
||||
Assert.Equal(EntityState.Unchanged, _mockContext.Entry(resumePoint).State);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAndMediaItemAsync_WhenEntitiesShouldBeTracked_ShouldReturnTheTrackedInstance()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
MediaResumePointEntity resumePoint = _mediaResumePointEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId);
|
||||
_mockContext.MediaResumePoints.Add(resumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaResumePointEntity?> result = await _sut.GetForUserAndMediaItemAsync(userId, MediaKind.Movie, mediaItemId, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Same(resumePoint, result.Value);
|
||||
Assert.Equal(EntityState.Unchanged, _mockContext.Entry(result.Value!).State);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertForUserAsync_WhenResumePointDoesNotExist_ShouldAddItWithTheAuthoritativeUserId()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaResumePointEntity resumePoint = _mediaResumePointEntityFixture.Create(
|
||||
userId: Guid.NewGuid(),
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
libraryId: Guid.NewGuid(),
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 120_000,
|
||||
lastProgressFraction: 0.25,
|
||||
version: 2);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertForUserAsync(resumePoint, userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<MediaResumePointEntity>? addedResumePoint = _mockContext.ChangeTracker.Entries<MediaResumePointEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == resumePoint.Id);
|
||||
Assert.NotNull(addedResumePoint);
|
||||
Assert.Same(resumePoint, addedResumePoint.Entity);
|
||||
// The owner argument is authoritative for a new row, not the owner carried by the incoming entity.
|
||||
Assert.Equal(userId, addedResumePoint.Entity.UserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertForUserAsync_WhenTheBusinessKeyExists_ShouldUpdateTheStoredRowAndIncrementTheVersion()
|
||||
{
|
||||
// Arrange
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
DateTime lastConsumedOnUtc = new(2025, 1, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
DateTime createdOnUtc = new(2024, 12, 31, 9, 0, 0, DateTimeKind.Utc);
|
||||
Guid createdBy = Guid.NewGuid();
|
||||
Guid incomingLibraryId = Guid.NewGuid();
|
||||
MediaResumePointEntity storedResumePoint = _mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: Guid.NewGuid(),
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 60_000,
|
||||
includeLastPositionLocation: false,
|
||||
lastProgressFraction: 0.25,
|
||||
lastConsumedOnUtc: lastConsumedOnUtc,
|
||||
version: 3,
|
||||
createdOnUtc: createdOnUtc,
|
||||
createdBy: createdBy);
|
||||
_mockContext.MediaResumePoints.Add(storedResumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
// The tracker is cleared so that the business key is located through the persistence medium instead of the local cache.
|
||||
_mockContext.ChangeTracker.Clear();
|
||||
MediaResumePointEntity incoming = _mediaResumePointEntityFixture.Create(
|
||||
id: Guid.NewGuid(),
|
||||
userId: Guid.NewGuid(),
|
||||
libraryId: incomingLibraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.Location,
|
||||
includeLastPositionTimeOffsetMilliseconds: false,
|
||||
lastPositionLocation: "chapter-4",
|
||||
lastProgressFraction: 0.75,
|
||||
lastConsumedOnUtc: new(2025, 1, 2, 8, 0, 0, DateTimeKind.Utc),
|
||||
version: 3);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertForUserAsync(incoming, userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<MediaResumePointEntity> storedEntry = Assert.Single(_mockContext.ChangeTracker.Entries<MediaResumePointEntity>());
|
||||
Assert.Equal(EntityState.Modified, storedEntry.State);
|
||||
MediaResumePointEntity updatedResumePoint = storedEntry.Entity;
|
||||
// The business key and the creation audit are never reassigned by an upsert.
|
||||
Assert.Equal(resumePointId, updatedResumePoint.Id);
|
||||
Assert.Equal(userId, updatedResumePoint.UserId);
|
||||
Assert.Equal(MediaKind.Movie, updatedResumePoint.MediaKind);
|
||||
Assert.Equal(mediaItemId, updatedResumePoint.MediaItemId);
|
||||
Assert.Equal(createdOnUtc, updatedResumePoint.CreatedOnUtc);
|
||||
Assert.Equal(createdBy, updatedResumePoint.CreatedBy);
|
||||
// The editable values are copied from the incoming resume point.
|
||||
Assert.Equal(MediaPositionKind.Location, updatedResumePoint.LastPositionKind);
|
||||
Assert.Null(updatedResumePoint.LastPositionTimeOffsetMilliseconds);
|
||||
Assert.Equal("chapter-4", updatedResumePoint.LastPositionLocation);
|
||||
Assert.Equal(0.75, updatedResumePoint.LastProgressFraction);
|
||||
Assert.Equal(new DateTime(2025, 1, 2, 8, 0, 0, DateTimeKind.Utc), updatedResumePoint.LastConsumedOnUtc);
|
||||
Assert.Equal(incomingLibraryId, updatedResumePoint.LibraryId);
|
||||
// The version is incremented by exactly one for a single save.
|
||||
Assert.Equal(4L, updatedResumePoint.Version);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertForUserAsync_WhenNoEditableValueChanged_ShouldReturnUpdatedWithoutBumpingTheVersion()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
MediaResumePointEntity storedResumePoint = _mediaResumePointEntityFixture.Create(
|
||||
userId: userId,
|
||||
libraryId: Guid.NewGuid(),
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 90_000,
|
||||
includeLastPositionLocation: false,
|
||||
lastProgressFraction: 0.4,
|
||||
lastConsumedOnUtc: new(2025, 1, 1, 10, 0, 0, DateTimeKind.Utc),
|
||||
version: 3);
|
||||
_mockContext.MediaResumePoints.Add(storedResumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
// A separate instance carrying exactly the stored editable values is the shape of a save that changes nothing.
|
||||
MediaResumePointEntity incoming = _mediaResumePointEntityFixture.Create(
|
||||
id: storedResumePoint.Id,
|
||||
userId: userId,
|
||||
libraryId: storedResumePoint.LibraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 90_000,
|
||||
includeLastPositionLocation: false,
|
||||
lastProgressFraction: 0.4,
|
||||
lastConsumedOnUtc: new(2025, 1, 1, 10, 0, 0, DateTimeKind.Utc),
|
||||
version: 3);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertForUserAsync(incoming, userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<MediaResumePointEntity> storedEntry = _mockContext.Entry(storedResumePoint);
|
||||
Assert.Equal(EntityState.Unchanged, storedEntry.State);
|
||||
Assert.Equal(3L, storedEntry.Entity.Version);
|
||||
Assert.DoesNotContain(_mockContext.ChangeTracker.Entries<MediaResumePointEntity>(), entry => entry.State == EntityState.Modified);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertForUserAsync_WhenAnotherUserHasTheSameMediaItem_ShouldInsertASecondRow()
|
||||
{
|
||||
// Arrange
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
MediaResumePointEntity otherUserResumePoint = _mediaResumePointEntityFixture.Create(
|
||||
userId: Guid.NewGuid(),
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId,
|
||||
lastProgressFraction: 0.3);
|
||||
_mockContext.MediaResumePoints.Add(otherUserResumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaResumePointEntity incoming = _mediaResumePointEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId,
|
||||
lastProgressFraction: 0.6);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertForUserAsync(incoming, userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
// The business key includes the user, so another user owning the same item does not turn the insert into an update.
|
||||
Assert.Equal(2, _mockContext.ChangeTracker.Entries<MediaResumePointEntity>().Count());
|
||||
Assert.Contains(_mockContext.ChangeTracker.Entries<MediaResumePointEntity>(), entry => entry.State == EntityState.Added && entry.Entity.UserId == userId);
|
||||
Assert.Equal(EntityState.Unchanged, _mockContext.Entry(otherUserResumePoint).State);
|
||||
Assert.Equal(0.3, otherUserResumePoint.LastProgressFraction);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertForUserAsync_WhenTheResumePointIsAlreadyTracked_ShouldUpdateThatInstanceInsteadOfAddingADuplicate()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
MediaResumePointEntity trackedResumePoint = _mediaResumePointEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId,
|
||||
lastProgressFraction: 0.3,
|
||||
version: 5);
|
||||
_mockContext.MediaResumePoints.Add(trackedResumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
MediaResumePointEntity incoming = _mediaResumePointEntityFixture.Create(
|
||||
id: Guid.NewGuid(),
|
||||
userId: userId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId,
|
||||
lastProgressFraction: 0.9,
|
||||
version: 5);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertForUserAsync(incoming, userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
EntityEntry<MediaResumePointEntity> singleEntry = Assert.Single(_mockContext.ChangeTracker.Entries<MediaResumePointEntity>());
|
||||
Assert.Same(trackedResumePoint, singleEntry.Entity);
|
||||
Assert.Equal(EntityState.Modified, singleEntry.State);
|
||||
Assert.Equal(0.9, trackedResumePoint.LastProgressFraction);
|
||||
Assert.Equal(6L, trackedResumePoint.Version);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteForUserAndMediaItemAsync_WhenTheResumePointMatches_ShouldRemoveItAndReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
MediaResumePointEntity resumePoint = _mediaResumePointEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId);
|
||||
_mockContext.MediaResumePoints.Add(resumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteForUserAndMediaItemAsync(userId, MediaKind.Movie, mediaItemId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
|
||||
EntityEntry<MediaResumePointEntity>? deletedResumePoint = _mockContext.ChangeTracker.Entries<MediaResumePointEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Deleted && entry.Entity.Id == resumePoint.Id);
|
||||
Assert.NotNull(deletedResumePoint);
|
||||
|
||||
await _mockContext.SaveChangesAsync();
|
||||
Assert.Null(await _mockContext.MediaResumePoints.FirstOrDefaultAsync(candidate => candidate.Id == resumePoint.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteForUserAndMediaItemAsync_WhenTheResumePointBelongsToAnotherUser_ShouldLeaveItUntouched()
|
||||
{
|
||||
// Arrange
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
MediaResumePointEntity resumePoint = _mediaResumePointEntityFixture.Create(
|
||||
userId: Guid.NewGuid(),
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: mediaItemId);
|
||||
_mockContext.MediaResumePoints.Add(resumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteForUserAndMediaItemAsync(Guid.NewGuid(), MediaKind.Movie, mediaItemId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
Assert.DoesNotContain(_mockContext.ChangeTracker.Entries<MediaResumePointEntity>(), entry => entry.State == EntityState.Deleted);
|
||||
Assert.Equal(EntityState.Unchanged, _mockContext.Entry(resumePoint).State);
|
||||
|
||||
await _mockContext.SaveChangesAsync();
|
||||
Assert.NotNull(await _mockContext.MediaResumePoints.FirstOrDefaultAsync(candidate => candidate.Id == resumePoint.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteForUserAndMediaItemAsync_WhenTheResumePointDoesNotExist_ShouldReturnDeletedWithoutChanges()
|
||||
{
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteForUserAndMediaItemAsync(Guid.NewGuid(), MediaKind.Movie, Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
Assert.Empty(_mockContext.ChangeTracker.Entries<MediaResumePointEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAllForUserAsync_WhenTheUserHasResumePoints_ShouldRemoveOnlyTheirResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
MediaResumePointEntity firstResumePoint = _mediaResumePointEntityFixture.Create(userId: userId, libraryId: libraryId);
|
||||
MediaResumePointEntity secondResumePoint = _mediaResumePointEntityFixture.Create(userId: userId, libraryId: Guid.NewGuid());
|
||||
MediaResumePointEntity otherUserResumePoint = _mediaResumePointEntityFixture.Create(userId: Guid.NewGuid(), libraryId: libraryId);
|
||||
_mockContext.MediaResumePoints.AddRange(firstResumePoint, secondResumePoint, otherUserResumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteAllForUserAsync(userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
|
||||
List<Guid> deletedResumePointIds = [.. _mockContext.ChangeTracker.Entries<MediaResumePointEntity>()
|
||||
.Where(entry => entry.State == EntityState.Deleted)
|
||||
.Select(entry => entry.Entity.Id)
|
||||
.OrderBy(id => id)];
|
||||
Assert.Equal(
|
||||
new[] { firstResumePoint.Id, secondResumePoint.Id }.OrderBy(id => id),
|
||||
deletedResumePointIds);
|
||||
|
||||
await _mockContext.SaveChangesAsync();
|
||||
List<Guid> remainingResumePointIds = await _mockContext.MediaResumePoints
|
||||
.AsNoTracking()
|
||||
.Select(resumePoint => resumePoint.Id)
|
||||
.ToListAsync();
|
||||
Assert.Equal([otherUserResumePoint.Id], remainingResumePointIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAllForUserInLibraryAsync_WhenTheUserHasResumePointsInTheLibrary_ShouldRemoveOnlyThoseResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
MediaResumePointEntity matchingResumePoint = _mediaResumePointEntityFixture.Create(userId: userId, libraryId: libraryId);
|
||||
MediaResumePointEntity otherLibraryResumePoint = _mediaResumePointEntityFixture.Create(userId: userId, libraryId: Guid.NewGuid());
|
||||
MediaResumePointEntity otherUserResumePoint = _mediaResumePointEntityFixture.Create(userId: Guid.NewGuid(), libraryId: libraryId);
|
||||
_mockContext.MediaResumePoints.AddRange(matchingResumePoint, otherLibraryResumePoint, otherUserResumePoint);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteAllForUserInLibraryAsync(userId, libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
|
||||
List<Guid> deletedResumePointIds = [.. _mockContext.ChangeTracker.Entries<MediaResumePointEntity>()
|
||||
.Where(entry => entry.State == EntityState.Deleted)
|
||||
.Select(entry => entry.Entity.Id)];
|
||||
Assert.Equal([matchingResumePoint.Id], deletedResumePointIds);
|
||||
|
||||
await _mockContext.SaveChangesAsync();
|
||||
List<Guid> remainingResumePointIds = await _mockContext.MediaResumePoints
|
||||
.AsNoTracking()
|
||||
.Select(resumePoint => resumePoint.Id)
|
||||
.ToListAsync();
|
||||
Assert.Equal(
|
||||
new[] { otherLibraryResumePoint.Id, otherUserResumePoint.Id }.OrderBy(id => id),
|
||||
remainingResumePointIds.OrderBy(id => id));
|
||||
}
|
||||
}
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.DataAccess.Core.Repositories.MediaContributors;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
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.MediaContributors;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaContributorRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly MediaContributorRepository _sut;
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaContributorRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public MediaContributorRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new MediaContributorRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FindOrCreateByDisplayNameAsync_WhenContributorExists_ShouldReturnTheExistingContributor()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Stephen King");
|
||||
_mockContext.MediaContributors.Add(existingContributor);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaContributorEntity> result = await _sut.FindOrCreateByDisplayNameAsync("stephen king", null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
// The comparison is case-insensitive, so the existing contributor is returned and no new one is created.
|
||||
Assert.Equal(existingContributor.Id, result.Value.Id);
|
||||
Assert.Equal("Stephen King", result.Value.DisplayName);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FindOrCreateByDisplayNameAsync_WhenContributorDoesNotExist_ShouldCreateAndAddANewContributor()
|
||||
{
|
||||
// Arrange
|
||||
string displayName = "Frank Herbert";
|
||||
|
||||
// Act
|
||||
Result<MediaContributorEntity> result = await _sut.FindOrCreateByDisplayNameAsync(displayName, "Franklin Patrick Herbert", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(displayName, result.Value.DisplayName);
|
||||
Assert.Equal("Franklin Patrick Herbert", result.Value.LegalName);
|
||||
|
||||
EntityEntry<MediaContributorEntity>? addedContributor = _mockContext.ChangeTracker.Entries<MediaContributorEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == result.Value.Id);
|
||||
Assert.NotNull(addedContributor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FindOrCreateByDisplayNameAsync_WhenContributorWithSameNameExistsInDifferentCase_ShouldNotCreateADuplicate()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
|
||||
_mockContext.MediaContributors.Add(existingContributor);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaContributorEntity> result = await _sut.FindOrCreateByDisplayNameAsync("FRANK HERBERT", "Franklin Patrick Herbert", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(existingContributor.Id, result.Value.Id);
|
||||
Assert.Equal(existingContributor.DisplayName, result.Value.DisplayName);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FindOrCreateByDisplayNameAsync_WhenExistingNameStartsWithNonAsciiUppercase_ShouldReturnTheExistingContributor()
|
||||
{
|
||||
// Arrange
|
||||
// The storage medium folds only ASCII case, so a name starting with a non-ASCII uppercase letter would previously not be found by the lookup
|
||||
// and would be inserted again, violating the unique index on the display name.
|
||||
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Лев Ошанин");
|
||||
_mockContext.MediaContributors.Add(existingContributor);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaContributorEntity> result = await _sut.FindOrCreateByDisplayNameAsync("Лев Ошанин", null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(existingContributor.Id, result.Value.Id);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FindOrCreateByDisplayNameAsync_WhenContributorWasAddedButNotSaved_ShouldReturnTheTrackedContributor()
|
||||
{
|
||||
// Arrange
|
||||
Result<MediaContributorEntity> firstResult = await _sut.FindOrCreateByDisplayNameAsync("Bob Ludwig", null, CancellationToken.None);
|
||||
Assert.False(firstResult.IsFailure);
|
||||
|
||||
// Act
|
||||
Result<MediaContributorEntity> secondResult = await _sut.FindOrCreateByDisplayNameAsync("BOB LUDWIG", null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(secondResult.IsFailure);
|
||||
// The contributor added earlier in the same unit of work is tracked, so it is returned instead of a duplicate being added.
|
||||
Assert.Equal(firstResult.Value.Id, secondResult.Value.Id);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>(), entityEntry => entityEntry.State == EntityState.Added);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenCalled_ShouldReturnOnlyTheContributorsWithTheProvidedIds()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create();
|
||||
MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create();
|
||||
MediaContributorEntity thirdContributor = _mediaContributorEntityFixture.Create();
|
||||
_mockContext.MediaContributors.AddRange(firstContributor, secondContributor, thirdContributor);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaContributorEntity>> result = await _sut.GetByIdsAsync([firstContributor.Id, thirdContributor.Id], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, contributor => contributor.Id == firstContributor.Id);
|
||||
Assert.Contains(result.Value, contributor => contributor.Id == thirdContributor.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenCalled_ShouldAddContributorToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(contributor, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<MediaContributorEntity>? addedContributor = _mockContext.ChangeTracker.Entries<MediaContributorEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == contributor.Id);
|
||||
Assert.NotNull(addedContributor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenContributorWithSameIdAlreadyExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create();
|
||||
_mockContext.MediaContributors.Add(existingContributor);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(id: existingContributor.Id);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(contributor, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.MediaContributor.MediaContributorAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenIdsIsEmpty_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
|
||||
_mockContext.MediaContributors.Add(contributor);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaContributorEntity>> result = await _sut.GetByIdsAsync([], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenAnIdDoesNotExist_ShouldIgnoreIt()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
|
||||
_mockContext.MediaContributors.Add(contributor);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaContributorEntity>> result = await _sut.GetByIdsAsync([contributor.Id, Guid.NewGuid()], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
MediaContributorEntity returnedContributor = Assert.Single(result.Value);
|
||||
Assert.Equal(contributor.Id, returnedContributor.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenMoreThanFiveHundredIdsAreRequested_ShouldReturnEveryContributor()
|
||||
{
|
||||
// Arrange
|
||||
const int CONTRIBUTOR_COUNT = 501;
|
||||
List<MediaContributorEntity> contributors = _mediaContributorEntityFixture.CreateMany(CONTRIBUTOR_COUNT);
|
||||
_mockContext.MediaContributors.AddRange(contributors);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
// The lookup is chunked in batches of 500, so the 501st Id proves the second chunk is queried as well.
|
||||
Result<IReadOnlyList<MediaContributorEntity>> result = await _sut.GetByIdsAsync(
|
||||
[.. contributors.Select(contributor => contributor.Id)], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(CONTRIBUTOR_COUNT, result.Value.Count);
|
||||
Assert.Equal(
|
||||
contributors.Select(contributor => contributor.Id).OrderBy(id => id),
|
||||
result.Value.Select(contributor => contributor.Id).OrderBy(id => id));
|
||||
}
|
||||
}
|
||||
+1468
File diff suppressed because it is too large.
Load diff
+1907
File diff suppressed because it is too large.
Load diff
+152
@@ -0,0 +1,152 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicArtworkRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtworkRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly MusicArtworkRepository _sut;
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtworkRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public MusicArtworkRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new MusicArtworkRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByOwnersAsync_WhenCalled_ShouldReturnOnlyTheArtworkOfTheRequestedOwnerTypeAndOwnerIds()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstOwnerId = Guid.NewGuid();
|
||||
Guid secondOwnerId = Guid.NewGuid();
|
||||
MusicArtworkEntity firstOwnerCover = _musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album, ownerId: firstOwnerId, artworkType: ArtworkType.Cover, ordinal: 0);
|
||||
MusicArtworkEntity firstOwnerFront = _musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album, ownerId: firstOwnerId, artworkType: ArtworkType.Front, ordinal: 1);
|
||||
MusicArtworkEntity secondOwnerCover = _musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album, ownerId: secondOwnerId, artworkType: ArtworkType.Cover, ordinal: 0);
|
||||
MusicArtworkEntity artworkOfAnotherOwner = _musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album, ownerId: Guid.NewGuid(), artworkType: ArtworkType.Cover, ordinal: 0);
|
||||
MusicArtworkEntity artworkOfAnotherOwnerType = _musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Artist, ownerId: firstOwnerId, artworkType: ArtworkType.Cover, ordinal: 0);
|
||||
_mockContext.MusicArtwork.AddRange(
|
||||
firstOwnerCover, firstOwnerFront, secondOwnerCover, artworkOfAnotherOwner, artworkOfAnotherOwnerType);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MusicArtworkEntity>> result = await _sut.GetByOwnersAsync(MusicArtworkOwnerType.Album, [firstOwnerId, secondOwnerId], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count);
|
||||
Assert.Contains(result.Value, artwork => artwork.Id == firstOwnerCover.Id);
|
||||
Assert.Contains(result.Value, artwork => artwork.Id == firstOwnerFront.Id);
|
||||
Assert.Contains(result.Value, artwork => artwork.Id == secondOwnerCover.Id);
|
||||
Assert.DoesNotContain(result.Value, artwork => artwork.Id == artworkOfAnotherOwner.Id);
|
||||
Assert.DoesNotContain(result.Value, artwork => artwork.Id == artworkOfAnotherOwnerType.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByOwnersAsync_WhenAnOwnerIdDoesNotExist_ShouldIgnoreIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid ownerId = Guid.NewGuid();
|
||||
MusicArtworkEntity artwork = _musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Track, ownerId: ownerId, artworkType: ArtworkType.Cover, ordinal: 0);
|
||||
_mockContext.MusicArtwork.Add(artwork);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MusicArtworkEntity>> result = await _sut.GetByOwnersAsync(MusicArtworkOwnerType.Track, [ownerId, Guid.NewGuid()], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
MusicArtworkEntity returnedArtwork = Assert.Single(result.Value);
|
||||
Assert.Equal(artwork.Id, returnedArtwork.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByOwnersAsync_WhenOwnerIdsIsEmpty_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
MusicArtworkEntity artwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album);
|
||||
_mockContext.MusicArtwork.Add(artwork);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MusicArtworkEntity>> result = await _sut.GetByOwnersAsync(MusicArtworkOwnerType.Album, [], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByOwnersAsync_WhenCalled_ShouldOrderTheArtworkByTypeThenOrdinal()
|
||||
{
|
||||
// Arrange
|
||||
Guid ownerId = Guid.NewGuid();
|
||||
MusicArtworkEntity frontSecond = _musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album, ownerId: ownerId, artworkType: ArtworkType.Front, ordinal: 1);
|
||||
MusicArtworkEntity frontFirst = _musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album, ownerId: ownerId, artworkType: ArtworkType.Front, ordinal: 0);
|
||||
MusicArtworkEntity cover = _musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album, ownerId: ownerId, artworkType: ArtworkType.Cover, ordinal: 0);
|
||||
_mockContext.MusicArtwork.AddRange(frontSecond, frontFirst, cover);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MusicArtworkEntity>> result = await _sut.GetByOwnersAsync(MusicArtworkOwnerType.Album, [ownerId], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal([cover.Id, frontFirst.Id, frontSecond.Id], result.Value.Select(artwork => artwork.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByOwnersAsync_WhenMoreThanFiveHundredOwnerIdsAreRequested_ShouldReturnTheArtworkOfEveryOwner()
|
||||
{
|
||||
// Arrange
|
||||
const int OWNER_COUNT = 501;
|
||||
List<Guid> ownerIds = [.. Enumerable.Range(0, OWNER_COUNT).Select(_ => Guid.NewGuid())];
|
||||
List<MusicArtworkEntity> artwork = [.. ownerIds.Select(ownerId => _musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album, ownerId: ownerId, artworkType: ArtworkType.Cover, ordinal: 0))];
|
||||
_mockContext.MusicArtwork.AddRange(artwork);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
// The lookup is chunked in batches of 500, so the 501st owner proves the last chunk is queried as well.
|
||||
Result<IReadOnlyList<MusicArtworkEntity>> result = await _sut.GetByOwnersAsync(MusicArtworkOwnerType.Album, ownerIds, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(OWNER_COUNT, result.Value.Count);
|
||||
Assert.Equal(
|
||||
artwork.Select(candidate => candidate.Id).OrderBy(id => id),
|
||||
result.Value.Select(candidate => candidate.Id).OrderBy(id => id));
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.MusicLibrary.Specifications;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary.Specifications;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ArtistSearchSpecification"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ArtistSearchSpecificationTests
|
||||
{
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenNameContainsSearchTerm_ShouldMatchArtist()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(name: "Queens of the Stone Age", includeAlbums: false, includeContributors: false);
|
||||
ArtistSearchSpecification specification = new("Stone");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(artist);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenNameDoesNotContainSearchTerm_ShouldNotMatchArtist()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(name: "Radiohead", includeAlbums: false, includeContributors: false);
|
||||
ArtistSearchSpecification specification = new("Queen");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(artist);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenNameMatchesInDifferentCase_ShouldMatchCaseInsensitively()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(name: "Queens of the Stone Age", includeAlbums: false, includeContributors: false);
|
||||
ArtistSearchSpecification specification = new("QUEENS");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(artist);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenSearchTermIsEmpty_ShouldMatchEveryArtist()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(name: "Radiohead", includeAlbums: false, includeContributors: false);
|
||||
ArtistSearchSpecification specification = new(string.Empty);
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(artist);
|
||||
|
||||
// Assert
|
||||
// The repository guards blank terms with IsNullOrWhiteSpace before building the specification, so an empty term is documented as matching every artist rather than being treated as a literal.
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenSearchTermIsWhitespace_ShouldNotMatchAnArtistWithoutThatWhitespace()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(name: "Radiohead", includeAlbums: false, includeContributors: false);
|
||||
ArtistSearchSpecification specification = new(" ");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(artist);
|
||||
|
||||
// Assert
|
||||
// A whitespace-only term is not silently ignored, it is matched literally.
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenApplied_ShouldFilterOutNonMatchingArtists()
|
||||
{
|
||||
// Arrange
|
||||
List<ArtistEntity> artists =
|
||||
[
|
||||
_artistEntityFixture.Create(name: "Queens of the Stone Age", includeAlbums: false, includeContributors: false),
|
||||
_artistEntityFixture.Create(name: "Radiohead", includeAlbums: false, includeContributors: false),
|
||||
_artistEntityFixture.Create(name: "Stone Temple Pilots", includeAlbums: false, includeContributors: false)
|
||||
];
|
||||
ArtistSearchSpecification specification = new("stone");
|
||||
|
||||
// Act
|
||||
IEnumerable<ArtistEntity> matchingArtists = artists.AsQueryable().Where(specification.ToExpression());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, matchingArtists.Count());
|
||||
Assert.DoesNotContain(matchingArtists, artist => artist.Name == "Radiohead");
|
||||
}
|
||||
}
|
||||
+1830
File diff suppressed because it is too large.
Load diff
+199
@@ -0,0 +1,199 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.DataAccess.Core.Repositories.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ArtworkProviderConfigurationRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ArtworkProviderConfigurationRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly ArtworkProviderConfigurationRepository _sut;
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ArtworkProviderConfigurationRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public ArtworkProviderConfigurationRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new ArtworkProviderConfigurationRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByLibraryIdAsync_WhenCalled_ShouldReturnOnlyConfigurationsOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryArtworkProviderConfigurationEntity configurationOfLibrary = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1);
|
||||
LibraryArtworkProviderConfigurationEntity configurationOfAnotherLibrary = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
_mockContext.LibraryArtworkProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<System.Collections.Generic.IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryArtworkProviderConfigurationEntity retrievedConfiguration = Assert.Single(result.Value);
|
||||
Assert.Equal(configurationOfLibrary.PluginId, retrievedConfiguration.PluginId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByLibraryIdAsync_WhenLibraryHasNoConfigurations_ShouldReturnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<System.Collections.Generic.IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationExists_ShouldReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
LibraryArtworkProviderConfigurationEntity configuration = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
_mockContext.LibraryArtworkProviderConfigurations.Add(configuration);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<LibraryArtworkProviderConfigurationEntity?> result = await _sut.GetByLibraryAndPluginIdAsync(configuration.LibraryId, configuration.PluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(configuration.Id, result.Value!.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<LibraryArtworkProviderConfigurationEntity?> result = await _sut.GetByLibraryAndPluginIdAsync(libraryId, pluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertAsync_WhenConfigurationDoesNotExist_ShouldInsertIt()
|
||||
{
|
||||
// Arrange
|
||||
LibraryArtworkProviderConfigurationEntity configuration = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertAsync(configuration, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(_mockContext.LibraryArtworkProviderConfigurations);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertAsync_WhenConfigurationExists_ShouldUpdateIt()
|
||||
{
|
||||
// Arrange
|
||||
LibraryArtworkProviderConfigurationEntity configuration = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
_mockContext.LibraryArtworkProviderConfigurations.Add(configuration);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryArtworkProviderConfigurationEntity updatedConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(configuration.LibraryId, configuration.PluginId, 5);
|
||||
updatedConfiguration.IsEnabled = true;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertAsync(updatedConfiguration, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryArtworkProviderConfigurationEntity retrievedConfiguration = _mockContext.LibraryArtworkProviderConfigurations.Single();
|
||||
Assert.Equal(5, retrievedConfiguration.Rank);
|
||||
Assert.True(retrievedConfiguration.IsEnabled);
|
||||
Assert.Equal(configuration.Id, retrievedConfiguration.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldRemoveOnlyConfigurationsOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryArtworkProviderConfigurationEntity configurationOfLibrary = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1);
|
||||
LibraryArtworkProviderConfigurationEntity configurationOfAnotherLibrary = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
_mockContext.LibraryArtworkProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryArtworkProviderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryArtworkProviderConfigurations);
|
||||
Assert.Equal(configurationOfAnotherLibrary.Id, remainingConfiguration.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByPluginIdAsync_WhenCalled_ShouldRemoveConfigurationsOfThePlugin()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
LibraryArtworkProviderConfigurationEntity configurationOfPlugin = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), pluginId, 1);
|
||||
LibraryArtworkProviderConfigurationEntity configurationOfAnotherPlugin = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
_mockContext.LibraryArtworkProviderConfigurations.AddRange(configurationOfPlugin, configurationOfAnotherPlugin);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByPluginIdAsync(pluginId, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryArtworkProviderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryArtworkProviderConfigurations);
|
||||
Assert.Equal(configurationOfAnotherPlugin.Id, remainingConfiguration.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByLibraryIdAndPluginIdsAsync_WhenCalled_ShouldRemoveOnlyTheConfigurationsOfTheProvidedPlugins()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid removedPluginId = Guid.NewGuid();
|
||||
Guid keptPluginId = Guid.NewGuid();
|
||||
LibraryArtworkProviderConfigurationEntity removedConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, removedPluginId, 1);
|
||||
LibraryArtworkProviderConfigurationEntity keptConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, keptPluginId, 2);
|
||||
_mockContext.LibraryArtworkProviderConfigurations.AddRange(removedConfiguration, keptConfiguration);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByLibraryIdAndPluginIdsAsync(libraryId, [removedPluginId], CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryArtworkProviderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryArtworkProviderConfigurations);
|
||||
Assert.Equal(keptConfiguration.Id, remainingConfiguration.Id);
|
||||
}
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.DataAccess.Core.Repositories.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
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.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryBookReaderConfigurationRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryBookReaderConfigurationRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly LibraryBookReaderConfigurationRepository _sut;
|
||||
private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryBookReaderConfigurationRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryBookReaderConfigurationRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new LibraryBookReaderConfigurationRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByLibraryIdAsync_WhenCalled_ShouldReturnOnlyConfigurationsOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryBookReaderConfigurationEntity configurationOfLibrary = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId);
|
||||
LibraryBookReaderConfigurationEntity configurationOfAnotherLibrary = _libraryBookReaderConfigurationEntityFixture.Create();
|
||||
_mockContext.LibraryBookReaderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryBookReaderConfigurationEntity retrievedConfiguration = Assert.Single(result.Value);
|
||||
Assert.Equal(configurationOfLibrary.PluginId, retrievedConfiguration.PluginId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationExists_ShouldReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
LibraryBookReaderConfigurationEntity configuration = _libraryBookReaderConfigurationEntityFixture.Create();
|
||||
_mockContext.LibraryBookReaderConfigurations.Add(configuration);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<LibraryBookReaderConfigurationEntity?> result = await _sut.GetByLibraryAndPluginIdAsync(configuration.LibraryId, configuration.PluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(configuration.Id, result.Value!.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<LibraryBookReaderConfigurationEntity?> result = await _sut.GetByLibraryAndPluginIdAsync(Guid.NewGuid(), Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertAsync_WhenConfigurationDoesNotExist_ShouldInsertIt()
|
||||
{
|
||||
// Arrange
|
||||
LibraryBookReaderConfigurationEntity configuration = _libraryBookReaderConfigurationEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertAsync(configuration, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(_mockContext.LibraryBookReaderConfigurations);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertAsync_WhenConfigurationExists_ShouldUpdateIt()
|
||||
{
|
||||
// Arrange
|
||||
LibraryBookReaderConfigurationEntity configuration = _libraryBookReaderConfigurationEntityFixture.Create(isEnabled: false);
|
||||
_mockContext.LibraryBookReaderConfigurations.Add(configuration);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryBookReaderConfigurationEntity updatedConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: configuration.LibraryId, pluginId: configuration.PluginId, isEnabled: true);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertAsync(updatedConfiguration, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryBookReaderConfigurationEntity retrievedConfiguration = _mockContext.LibraryBookReaderConfigurations.Single();
|
||||
Assert.True(retrievedConfiguration.IsEnabled);
|
||||
Assert.Equal(configuration.Id, retrievedConfiguration.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldRemoveOnlyConfigurationsOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryBookReaderConfigurationEntity configurationOfLibrary = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId);
|
||||
LibraryBookReaderConfigurationEntity configurationOfAnotherLibrary = _libraryBookReaderConfigurationEntityFixture.Create();
|
||||
_mockContext.LibraryBookReaderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryBookReaderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryBookReaderConfigurations);
|
||||
Assert.Equal(configurationOfAnotherLibrary.Id, remainingConfiguration.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByPluginIdAsync_WhenCalled_ShouldRemoveConfigurationsOfThePlugin()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
LibraryBookReaderConfigurationEntity configurationOfPlugin = _libraryBookReaderConfigurationEntityFixture.Create(pluginId: pluginId);
|
||||
LibraryBookReaderConfigurationEntity configurationOfAnotherPlugin = _libraryBookReaderConfigurationEntityFixture.Create();
|
||||
_mockContext.LibraryBookReaderConfigurations.AddRange(configurationOfPlugin, configurationOfAnotherPlugin);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByPluginIdAsync(pluginId, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryBookReaderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryBookReaderConfigurations);
|
||||
Assert.Equal(configurationOfAnotherPlugin.Id, remainingConfiguration.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByLibraryIdAndPluginIdsAsync_WhenCalled_ShouldRemoveOnlyTheConfigurationsOfTheProvidedPlugins()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid removedPluginId = Guid.NewGuid();
|
||||
Guid keptPluginId = Guid.NewGuid();
|
||||
LibraryBookReaderConfigurationEntity removedConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: removedPluginId);
|
||||
LibraryBookReaderConfigurationEntity keptConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: keptPluginId);
|
||||
_mockContext.LibraryBookReaderConfigurations.AddRange(removedConfiguration, keptConfiguration);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByLibraryIdAndPluginIdsAsync(libraryId, [removedPluginId], CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryBookReaderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryBookReaderConfigurations);
|
||||
Assert.Equal(keptConfiguration.Id, remainingConfiguration.Id);
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.DataAccess.Core.Repositories.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryMetadataProviderConfigurationRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryMetadataProviderConfigurationRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly LibraryMetadataProviderConfigurationRepository _sut;
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryMetadataProviderConfigurationRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryMetadataProviderConfigurationRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new LibraryMetadataProviderConfigurationRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByLibraryIdAsync_WhenCalled_ShouldReturnOnlyConfigurationsOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryMetadataProviderConfigurationEntity configurationOfLibrary = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1);
|
||||
LibraryMetadataProviderConfigurationEntity configurationOfAnotherLibrary = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
_mockContext.LibraryMetadataProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<System.Collections.Generic.IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryMetadataProviderConfigurationEntity retrievedConfiguration = Assert.Single(result.Value);
|
||||
Assert.Equal(configurationOfLibrary.PluginId, retrievedConfiguration.PluginId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationExists_ShouldReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
LibraryMetadataProviderConfigurationEntity configuration = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
_mockContext.LibraryMetadataProviderConfigurations.Add(configuration);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<LibraryMetadataProviderConfigurationEntity?> result = await _sut.GetByLibraryAndPluginIdAsync(configuration.LibraryId, configuration.PluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(configuration.Id, result.Value!.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertAsync_WhenConfigurationDoesNotExist_ShouldInsertIt()
|
||||
{
|
||||
// Arrange
|
||||
LibraryMetadataProviderConfigurationEntity configuration = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertAsync(configuration, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(_mockContext.LibraryMetadataProviderConfigurations);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertAsync_WhenConfigurationExists_ShouldUpdateIt()
|
||||
{
|
||||
// Arrange
|
||||
LibraryMetadataProviderConfigurationEntity configuration = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
_mockContext.LibraryMetadataProviderConfigurations.Add(configuration);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryMetadataProviderConfigurationEntity updatedConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(configuration.LibraryId, configuration.PluginId, 5);
|
||||
updatedConfiguration.IsEnabled = true;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertAsync(updatedConfiguration, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryMetadataProviderConfigurationEntity retrievedConfiguration = _mockContext.LibraryMetadataProviderConfigurations.Single();
|
||||
Assert.Equal(5, retrievedConfiguration.Rank);
|
||||
Assert.True(retrievedConfiguration.IsEnabled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldRemoveOnlyConfigurationsOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryMetadataProviderConfigurationEntity configurationOfLibrary = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1);
|
||||
LibraryMetadataProviderConfigurationEntity configurationOfAnotherLibrary = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
_mockContext.LibraryMetadataProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryMetadataProviderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryMetadataProviderConfigurations);
|
||||
Assert.Equal(configurationOfAnotherLibrary.Id, remainingConfiguration.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByPluginIdAsync_WhenCalled_ShouldRemoveConfigurationsOfThePlugin()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
LibraryMetadataProviderConfigurationEntity configurationOfPlugin = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), pluginId, 1);
|
||||
LibraryMetadataProviderConfigurationEntity configurationOfAnotherPlugin = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
_mockContext.LibraryMetadataProviderConfigurations.AddRange(configurationOfPlugin, configurationOfAnotherPlugin);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByPluginIdAsync(pluginId, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryMetadataProviderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryMetadataProviderConfigurations);
|
||||
Assert.Equal(configurationOfAnotherPlugin.Id, remainingConfiguration.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByLibraryIdAndPluginIdsAsync_WhenCalled_ShouldRemoveOnlyTheConfigurationsOfTheProvidedPlugins()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid removedPluginId = Guid.NewGuid();
|
||||
Guid keptPluginId = Guid.NewGuid();
|
||||
LibraryMetadataProviderConfigurationEntity removedConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, removedPluginId, 1);
|
||||
LibraryMetadataProviderConfigurationEntity keptConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, keptPluginId, 2);
|
||||
_mockContext.LibraryMetadataProviderConfigurations.AddRange(removedConfiguration, keptConfiguration);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByLibraryIdAndPluginIdsAsync(libraryId, [removedPluginId], CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryMetadataProviderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryMetadataProviderConfigurations);
|
||||
Assert.Equal(keptConfiguration.Id, remainingConfiguration.Id);
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.DataAccess.Core.Repositories.Plugins;
|
||||
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.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PluginRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly PluginRepository _sut;
|
||||
private readonly PluginEntityFixture _pluginEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PluginRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public PluginRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new PluginRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenPluginExists_ShouldReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
PluginEntity plugin = _pluginEntityFixture.Create();
|
||||
_mockContext.Plugins.Add(plugin);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PluginEntity?> result = await _sut.GetByIdAsync(plugin.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(plugin.Id, result.Value!.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertAsync_WhenPluginDoesNotExist_ShouldInsertIt()
|
||||
{
|
||||
// Arrange
|
||||
PluginEntity plugin = _pluginEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertAsync(plugin, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(_mockContext.Plugins);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertAsync_WhenPluginExists_ShouldUpdateDetectionFieldsAndPreserveSettings()
|
||||
{
|
||||
// Arrange
|
||||
PluginEntity plugin = _pluginEntityFixture.Create();
|
||||
plugin.SettingsJson = """{"preferredLanguage":"en"}""";
|
||||
_mockContext.Plugins.Add(plugin);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PluginEntity updatedPlugin = _pluginEntityFixture.Create(plugin.Id);
|
||||
updatedPlugin.Name = "Updated Name";
|
||||
updatedPlugin.SettingsJson = null; // The stored settings must be preserved.
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertAsync(updatedPlugin, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
PluginEntity retrievedPlugin = _mockContext.Plugins.Single();
|
||||
Assert.Equal("Updated Name", retrievedPlugin.Name);
|
||||
Assert.Equal("""{"preferredLanguage":"en"}""", retrievedPlugin.SettingsJson);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSettingsAsync_WhenPluginExists_ShouldUpdateItsSettings()
|
||||
{
|
||||
// Arrange
|
||||
PluginEntity plugin = _pluginEntityFixture.Create();
|
||||
_mockContext.Plugins.Add(plugin);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateSettingsAsync(plugin.Id, """{"preferredLanguage":"fr"}""", CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("""{"preferredLanguage":"fr"}""", _mockContext.Plugins.Single().SettingsJson);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSettingsAsync_WhenPluginDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateSettingsAsync(Guid.NewGuid(), null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.PluginNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenPluginsExist_ShouldReturnAllPlugins()
|
||||
{
|
||||
// Arrange
|
||||
List<PluginEntity> plugins = _pluginEntityFixture.CreateMany(2);
|
||||
|
||||
_mockContext.Plugins.AddRange(plugins);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<PluginEntity>> result = await _sut.GetAllAsync<BaseFilterDto>(cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(2, result.Value.Data.Count);
|
||||
Assert.Contains(result.Value.Data, plugin => plugin.Id == plugins[0].Id);
|
||||
Assert.Contains(result.Value.Data, plugin => plugin.Id == plugins[1].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenNoPluginsExist_ShouldReturnEmptyList()
|
||||
{
|
||||
// Act
|
||||
Result<PaginatedResultDto<PluginEntity>> result = await _sut.GetAllAsync<BaseFilterDto>(cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value.Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenPluginExists_ShouldRemovePluginAndReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
PluginEntity existingPlugin = _pluginEntityFixture.Create();
|
||||
_mockContext.Plugins.Add(existingPlugin);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(existingPlugin.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
|
||||
EntityEntry<PluginEntity>? deletedEntry = _mockContext.ChangeTracker.Entries<PluginEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.Entity.Id == existingPlugin.Id);
|
||||
Assert.NotNull(deletedEntry);
|
||||
Assert.Equal(EntityState.Deleted, deletedEntry!.State);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenPluginDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(nonExistentId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.PluginNotFound, result.FirstError);
|
||||
}
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.DataAccess.Core.Repositories.Scheduling;
|
||||
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.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobExecutionRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobExecutionRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly ScheduledJobExecutionRepository _sut;
|
||||
private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScheduledJobExecutionRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public ScheduledJobExecutionRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new ScheduledJobExecutionRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenExecutionExists_ShouldReturnExecution()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create();
|
||||
_mockContext.ScheduledJobExecutions.Add(execution);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<ScheduledJobExecutionEntity?> result = await _sut.GetByIdAsync(execution.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(execution.Id, result.Value!.Id);
|
||||
Assert.Equal(execution.ScheduledJobId, result.Value.ScheduledJobId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenExecutionDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<ScheduledJobExecutionEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenExecutionDoesNotExist_ShouldAddExecutionToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(execution, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
EntityEntry<ScheduledJobExecutionEntity>? addedExecution = _mockContext.ChangeTracker.Entries<ScheduledJobExecutionEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == execution.Id);
|
||||
Assert.NotNull(addedExecution);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenExecutionAlreadyExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create();
|
||||
_mockContext.ScheduledJobExecutions.Add(execution);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(execution, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.ScheduledJobExecutionAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenExecutionExists_ShouldUpdateItsPropertiesAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
DateTime completedOnUtc = DateTime.UtcNow;
|
||||
ScheduledJobExecutionEntity existingExecution = _scheduledJobExecutionEntityFixture.Create(completedOnUtc: null);
|
||||
_mockContext.ScheduledJobExecutions.Add(existingExecution);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
ScheduledJobExecutionEntity updatedExecution = _scheduledJobExecutionEntityFixture.Create(
|
||||
id: existingExecution.Id,
|
||||
scheduledJobId: existingExecution.ScheduledJobId,
|
||||
isCycleRun: existingExecution.IsCycleRun,
|
||||
startedOnUtc: existingExecution.StartedOnUtc,
|
||||
completedOnUtc: completedOnUtc);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedExecution, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
ScheduledJobExecutionEntity? modifiedExecution = await _mockContext.ScheduledJobExecutions.FirstOrDefaultAsync(execution => execution.Id == existingExecution.Id);
|
||||
Assert.NotNull(modifiedExecution);
|
||||
Assert.Equal(completedOnUtc, modifiedExecution!.CompletedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenExecutionDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(execution, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.ScheduledJobExecutionNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetOpenByScheduledJobIdAsync_WhenAnOpenExecutionExists_ShouldReturnTheMostRecentOne()
|
||||
{
|
||||
// Arrange
|
||||
Guid scheduledJobId = Guid.NewGuid();
|
||||
DateTime mostRecentStart = DateTime.UtcNow.AddMinutes(-1);
|
||||
ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId, startedOnUtc: mostRecentStart, completedOnUtc: null);
|
||||
ScheduledJobExecutionEntity olderOpenExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId, startedOnUtc: mostRecentStart.AddMinutes(-10), completedOnUtc: null);
|
||||
ScheduledJobExecutionEntity closedExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId, startedOnUtc: mostRecentStart.AddMinutes(-5), completedOnUtc: DateTime.UtcNow);
|
||||
_mockContext.ScheduledJobExecutions.AddRange(openExecution, olderOpenExecution, closedExecution);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<ScheduledJobExecutionEntity?> result = await _sut.GetOpenByScheduledJobIdAsync(scheduledJobId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(openExecution.Id, result.Value!.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetOpenByScheduledJobIdAsync_WhenNoOpenExecutionExists_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
Guid scheduledJobId = Guid.NewGuid();
|
||||
ScheduledJobExecutionEntity closedExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId, completedOnUtc: DateTime.UtcNow);
|
||||
_mockContext.ScheduledJobExecutions.Add(closedExecution);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<ScheduledJobExecutionEntity?> result = await _sut.GetOpenByScheduledJobIdAsync(scheduledJobId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByTimeRangeAsync_WhenExecutionsStartedInTheRange_ShouldReturnThemOrderedByStartTime()
|
||||
{
|
||||
// Arrange
|
||||
DateTime fromUtc = DateTime.UtcNow.AddHours(-2);
|
||||
DateTime toUtc = DateTime.UtcNow;
|
||||
ScheduledJobExecutionEntity inRange1 = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: fromUtc.AddMinutes(1));
|
||||
ScheduledJobExecutionEntity inRange2 = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: fromUtc.AddMinutes(30));
|
||||
ScheduledJobExecutionEntity beforeRange = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: fromUtc.AddMinutes(-10));
|
||||
ScheduledJobExecutionEntity afterRange = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: toUtc.AddMinutes(10));
|
||||
_mockContext.ScheduledJobExecutions.AddRange(inRange1, inRange2, beforeRange, afterRange);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<ScheduledJobExecutionEntity>> result = await _sut.GetByTimeRangeAsync(fromUtc, toUtc, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
List<ScheduledJobExecutionEntity> executions = [.. result.Value];
|
||||
Assert.Equal(2, executions.Count);
|
||||
Assert.Equal(inRange1.Id, executions[0].Id);
|
||||
Assert.Equal(inRange2.Id, executions[1].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByScheduledJobIdAsync_WhenExecutionsExist_ShouldRemoveThemAllAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
Guid scheduledJobId = Guid.NewGuid();
|
||||
ScheduledJobExecutionEntity execution1 = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId);
|
||||
ScheduledJobExecutionEntity execution2 = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId);
|
||||
ScheduledJobExecutionEntity otherExecution = _scheduledJobExecutionEntityFixture.Create();
|
||||
_mockContext.ScheduledJobExecutions.AddRange(execution1, execution2, otherExecution);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.DeleteByScheduledJobIdAsync(scheduledJobId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.Equal(2, _mockContext.ChangeTracker.Entries<ScheduledJobExecutionEntity>().Count(entry => entry.State == EntityState.Deleted));
|
||||
Assert.Contains(_mockContext.ChangeTracker.Entries<ScheduledJobExecutionEntity>(), entry => entry.State == EntityState.Deleted && entry.Entity.Id == execution1.Id);
|
||||
Assert.Contains(_mockContext.ChangeTracker.Entries<ScheduledJobExecutionEntity>(), entry => entry.State == EntityState.Deleted && entry.Entity.Id == execution2.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByScheduledJobIdAsync_WhenNoExecutionsExist_ShouldReturnSuccess()
|
||||
{
|
||||
// Act
|
||||
Result<Success> result = await _sut.DeleteByScheduledJobIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
}
|
||||
}
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.DataAccess.Core.Repositories.Scheduling;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
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.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly ScheduledJobRepository _sut;
|
||||
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScheduledJobRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public ScheduledJobRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new ScheduledJobRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenScheduledJobExists_ShouldReturnScheduledJob()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create();
|
||||
_mockContext.ScheduledJobs.Add(scheduledJob);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<ScheduledJobEntity?> result = await _sut.GetByIdAsync(scheduledJob.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(scheduledJob.Id, result.Value!.Id);
|
||||
Assert.Equal(scheduledJob.Name, result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenScheduledJobDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<ScheduledJobEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdWithoutTrackingAsync_WhenScheduledJobExists_ShouldReturnScheduledJob()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create();
|
||||
_mockContext.ScheduledJobs.Add(scheduledJob);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<ScheduledJobEntity?> result = await _sut.GetByIdWithoutTrackingAsync(scheduledJob.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(scheduledJob.Id, result.Value!.Id);
|
||||
Assert.Equal(scheduledJob.Name, result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdWithoutTrackingAsync_WhenScheduledJobDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<ScheduledJobEntity?> result = await _sut.GetByIdWithoutTrackingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenScheduledJobsExist_ShouldReturnAllScheduledJobs()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create();
|
||||
ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create();
|
||||
_mockContext.ScheduledJobs.AddRange(scheduledJob1, scheduledJob2);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<ScheduledJobEntity>> result = await _sut.GetAllAsync<BaseFilterDto>(cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Data.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetActiveOrRunningAsync_WhenScheduledJobsAreActiveOrRunning_ShouldReturnOnlyThem()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active);
|
||||
ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running);
|
||||
ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added);
|
||||
ScheduledJobEntity completedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Completed);
|
||||
_mockContext.ScheduledJobs.AddRange(activeJob, runningJob, addedJob, completedJob);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<ScheduledJobEntity>> result = await _sut.GetActiveOrRunningAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
List<ScheduledJobEntity> scheduledJobs = result.Value.ToList();
|
||||
Assert.Equal(2, scheduledJobs.Count);
|
||||
Assert.Contains(scheduledJobs, scheduledJob => scheduledJob.Id == activeJob.Id);
|
||||
Assert.Contains(scheduledJobs, scheduledJob => scheduledJob.Id == runningJob.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenScheduledJobDoesNotExist_ShouldAddScheduledJobToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(scheduledJob, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
EntityEntry<ScheduledJobEntity>? addedScheduledJob = _mockContext.ChangeTracker.Entries<ScheduledJobEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == scheduledJob.Id);
|
||||
Assert.NotNull(addedScheduledJob);
|
||||
Assert.Equal(scheduledJob.Name, addedScheduledJob!.Entity.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenScheduledJobAlreadyExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create();
|
||||
_mockContext.ScheduledJobs.Add(scheduledJob);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(scheduledJob, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.ScheduledJobAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenScheduledJobExists_ShouldUpdateItsPropertiesAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobEntity existingScheduledJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added);
|
||||
_mockContext.ScheduledJobs.Add(existingScheduledJob);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
ScheduledJobEntity updatedScheduledJob = _scheduledJobEntityFixture.Create(
|
||||
id: existingScheduledJob.Id,
|
||||
name: "Updated name",
|
||||
status: ScheduledJobStatus.Active);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedScheduledJob, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
ScheduledJobEntity? modifiedScheduledJob = await _mockContext.ScheduledJobs.FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == existingScheduledJob.Id);
|
||||
Assert.NotNull(modifiedScheduledJob);
|
||||
Assert.Equal("Updated name", modifiedScheduledJob!.Name);
|
||||
Assert.Equal(ScheduledJobStatus.Active, modifiedScheduledJob.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenScheduledJobDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(scheduledJob, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenScheduledJobExists_ShouldRemoveItAndReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create();
|
||||
_mockContext.ScheduledJobs.Add(scheduledJob);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(scheduledJob.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
EntityEntry<ScheduledJobEntity>? deletedScheduledJob = _mockContext.ChangeTracker.Entries<ScheduledJobEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Deleted && entry.Entity.Id == scheduledJob.Id);
|
||||
Assert.NotNull(deletedScheduledJob);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenScheduledJobDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, result.FirstError);
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.DataAccess.Core.Repositories.Scheduling;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SchedulerDisplayPreferencesRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SchedulerDisplayPreferencesRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly SchedulerDisplayPreferencesRepository _sut;
|
||||
private readonly SchedulerDisplayPreferencesEntityFixture _schedulerDisplayPreferencesEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SchedulerDisplayPreferencesRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public SchedulerDisplayPreferencesRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new SchedulerDisplayPreferencesRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByUserIdAsync_WhenDisplayPreferencesExist_ShouldReturnThem()
|
||||
{
|
||||
// Arrange
|
||||
SchedulerDisplayPreferencesEntity displayPreferences = _schedulerDisplayPreferencesEntityFixture.Create();
|
||||
_mockContext.SchedulerDisplayPreferences.Add(displayPreferences);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<SchedulerDisplayPreferencesEntity?> result = await _sut.GetByUserIdAsync(displayPreferences.UserId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(displayPreferences.Id, result.Value!.Id);
|
||||
Assert.Equal(displayPreferences.UserId, result.Value.UserId);
|
||||
Assert.Equal(displayPreferences.DisplayTimeSpan, result.Value.DisplayTimeSpan);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByUserIdAsync_WhenDisplayPreferencesDoNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<SchedulerDisplayPreferencesEntity?> result = await _sut.GetByUserIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertAsync_WhenDisplayPreferencesDoNotExist_ShouldAddThemToContextAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
SchedulerDisplayPreferencesEntity displayPreferences = _schedulerDisplayPreferencesEntityFixture.Create(
|
||||
displayTimeSpan: 30,
|
||||
displayTimeUnit: SchedulerDisplayTimeUnit.Minutes);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertAsync(displayPreferences, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
EntityEntry<SchedulerDisplayPreferencesEntity>? addedPreferences = _mockContext.ChangeTracker.Entries<SchedulerDisplayPreferencesEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.UserId == displayPreferences.UserId);
|
||||
Assert.NotNull(addedPreferences);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertAsync_WhenDisplayPreferencesAlreadyExist_ShouldUpdateTheMutableFieldsAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
SchedulerDisplayPreferencesEntity existingPreferences = _schedulerDisplayPreferencesEntityFixture.Create(
|
||||
userId: userId,
|
||||
jobTypeFilter: ScheduledTaskType.ScanMediaLibraries,
|
||||
displayTimeSpan: 10,
|
||||
displayTimeUnit: SchedulerDisplayTimeUnit.Hours);
|
||||
_mockContext.SchedulerDisplayPreferences.Add(existingPreferences);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
SchedulerDisplayPreferencesEntity updatedPreferences = _schedulerDisplayPreferencesEntityFixture.Create(
|
||||
userId: userId,
|
||||
jobTypeFilter: ScheduledTaskType.CleanTemporaryFiles,
|
||||
displayTimeSpan: 60,
|
||||
displayTimeUnit: SchedulerDisplayTimeUnit.Days);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertAsync(updatedPreferences, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
SchedulerDisplayPreferencesEntity? modifiedPreferences = await _mockContext.SchedulerDisplayPreferences
|
||||
.FirstOrDefaultAsync(preferences => preferences.UserId == userId);
|
||||
Assert.NotNull(modifiedPreferences);
|
||||
// The Id and the ownership of the existing preferences are preserved.
|
||||
Assert.Equal(existingPreferences.Id, modifiedPreferences!.Id);
|
||||
Assert.Equal(ScheduledTaskType.CleanTemporaryFiles, modifiedPreferences.JobTypeFilter);
|
||||
Assert.Equal(60, modifiedPreferences.DisplayTimeSpan);
|
||||
Assert.Equal(SchedulerDisplayTimeUnit.Days, modifiedPreferences.DisplayTimeUnit);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<SchedulerDisplayPreferencesEntity>());
|
||||
}
|
||||
}
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.DataAccess.Core.Repositories.Themes;
|
||||
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.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThemeRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly ThemeRepository _sut;
|
||||
private readonly ThemeEntityFixture _themeEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public ThemeRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new ThemeRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenThemeDoesNotExist_ShouldAddThemeToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity theme = _themeEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(theme, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<ThemeEntity>? addedTheme = _mockContext.ChangeTracker.Entries<ThemeEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == theme.Id);
|
||||
Assert.NotNull(addedTheme);
|
||||
Assert.Equal(theme.ThemeId, addedTheme.Entity.ThemeId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenThemeAlreadyExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity theme = _themeEntityFixture.Create();
|
||||
_mockContext.Themes.Add(theme);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(theme, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<ThemeEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenCalled_ShouldReturnAllThemes()
|
||||
{
|
||||
// Arrange
|
||||
List<ThemeEntity> themes = _themeEntityFixture.CreateMany();
|
||||
_mockContext.Themes.AddRange(themes);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<ThemeEntity>> result = await _sut.GetAllAsync<BaseFilterDto>(cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(3, result.Value.Data.Count);
|
||||
Assert.Equal(themes, result.Value.Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenNoThemesExist_ShouldReturnEmptyList()
|
||||
{
|
||||
// Act
|
||||
Result<PaginatedResultDto<ThemeEntity>> result = await _sut.GetAllAsync<BaseFilterDto>(cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value.Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByThemeIdAsync_WhenThemeExists_ShouldReturnTheme()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity theme = _themeEntityFixture.Create(themeId: "my-theme");
|
||||
_mockContext.Themes.Add(theme);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<ThemeEntity?> result = await _sut.GetByThemeIdAsync(theme.ThemeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(theme, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByThemeIdAsync_WhenThemeDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<ThemeEntity?> result = await _sut.GetByThemeIdAsync("nonexistent-theme", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenThemeExists_ShouldUpdateThemeAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity existingTheme = _themeEntityFixture.Create(name: "Existing Theme");
|
||||
_mockContext.Themes.Add(existingTheme);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
ThemeEntity updatedTheme = _themeEntityFixture.Create(id: existingTheme.Id, themeId: existingTheme.ThemeId, name: "Updated Theme", includeIsCurrent: true, isCurrent: true);
|
||||
updatedTheme.CreatedOnUtc = existingTheme.CreatedOnUtc;
|
||||
updatedTheme.CreatedBy = existingTheme.CreatedBy;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedTheme, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
ThemeEntity? modifiedTheme = await _mockContext.Themes.FirstOrDefaultAsync(theme => theme.Id == existingTheme.Id);
|
||||
Assert.NotNull(modifiedTheme);
|
||||
Assert.Equal("Updated Theme", modifiedTheme.Name);
|
||||
Assert.True(modifiedTheme.IsCurrent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenThemeDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity theme = _themeEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(theme, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenThemeExists_ShouldRemoveThemeFromContextAndReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity theme = _themeEntityFixture.Create();
|
||||
_mockContext.Themes.Add(theme);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(theme.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
|
||||
EntityEntry<ThemeEntity>? deletedTheme = _mockContext.ChangeTracker.Entries<ThemeEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Deleted && entry.Entity.Id == theme.Id);
|
||||
Assert.NotNull(deletedTheme);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenThemeDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetCurrentAsync_WhenCurrentThemeExists_ShouldReturnCurrentTheme()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity currentTheme = _themeEntityFixture.Create(includeIsCurrent: true, isCurrent: true);
|
||||
ThemeEntity nonCurrentTheme = _themeEntityFixture.Create(includeIsCurrent: true, isCurrent: false);
|
||||
_mockContext.Themes.AddRange(currentTheme, nonCurrentTheme);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<ThemeEntity?> result = await _sut.GetCurrentAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(currentTheme, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetCurrentAsync_WhenNoCurrentThemeExists_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity nonCurrentTheme = _themeEntityFixture.Create(includeIsCurrent: true, isCurrent: false);
|
||||
_mockContext.Themes.Add(nonCurrentTheme);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<ThemeEntity?> result = await _sut.GetCurrentAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
}
|
||||
+479
@@ -0,0 +1,479 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.Repositories.Users;
|
||||
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.Users;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UserRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly UserRepository _sut;
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly UserRoleEntityFixture _userRoleEntityFixture = new();
|
||||
private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public UserRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new UserRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenUserDoesNotExist_ShouldAddUserToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity userModel = _userEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(userModel, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<UserEntity>? addedUser = _mockContext.ChangeTracker.Entries<UserEntity>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == userModel.Id);
|
||||
Assert.NotNull(addedUser);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenUserAlreadyExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity userModel = _userEntityFixture.Create();
|
||||
|
||||
_mockContext.Users.Add(userModel);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(userModel, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Users.UserAlreadyExists, result.FirstError);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<UserEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenCalled_ShouldReturnAllUsers()
|
||||
{
|
||||
// Arrange
|
||||
List<UserEntity> users = _userEntityFixture.CreateMany();
|
||||
_mockContext.Users.AddRange(users);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<UserEntity>> result = await _sut.GetAllAsync<BaseFilterDto>(cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(3, result.Value.Data.Count);
|
||||
Assert.Equal(users, result.Value.Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenNoUsersExist_ShouldReturnEmptyList()
|
||||
{
|
||||
// Act
|
||||
Result<PaginatedResultDto<UserEntity>> result = await _sut.GetAllAsync<BaseFilterDto>(cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value.Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByUsernameAsync_WhenUserExists_ShouldReturnUser()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity userModel = _userEntityFixture.Create();
|
||||
_mockContext.Users.Add(userModel);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<UserEntity?> result = await _sut.GetByUsernameAsync(userModel.Username, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(userModel, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByUsernameAsync_WhenUserDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<UserEntity?> result = await _sut.GetByUsernameAsync("nonexistent", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenUserExists_ShouldUpdateUserAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity existingUser = _userEntityFixture.Create();
|
||||
_mockContext.Users.Add(existingUser);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Create updated user with same Id but different properties.
|
||||
UserEntity updatedUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: "NewPassword123");
|
||||
updatedUser.TempPassword = "TempPass456";
|
||||
updatedUser.TotpSecret = "NewSecret";
|
||||
updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc;
|
||||
updatedUser.UpdatedOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedUser, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
UserEntity? modifiedUser = await _mockContext.Users.FirstOrDefaultAsync(u => u.Username == existingUser.Username);
|
||||
Assert.NotNull(modifiedUser);
|
||||
Assert.Equal(updatedUser.Password, modifiedUser.Password);
|
||||
Assert.Equal(updatedUser.TempPassword, modifiedUser.TempPassword);
|
||||
Assert.Equal(updatedUser.TotpSecret, modifiedUser.TotpSecret);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenUserDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity userModel = _userEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(userModel, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Users.UserDoesNotExist, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenIncomingEntityCarriesADifferentId_ShouldPreserveTheStoredIdentity()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity existingUser = _userEntityFixture.Create();
|
||||
_mockContext.Users.Add(existingUser);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
Guid mismatchedId = Guid.NewGuid();
|
||||
UserEntity updatedUser = _userEntityFixture.Create(id: mismatchedId, username: existingUser.Username, password: "NewPassword123");
|
||||
updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc;
|
||||
updatedUser.CreatedBy = existingUser.CreatedBy;
|
||||
updatedUser.UpdatedOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedUser, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
// The repository locates the row by username, so the stored identity must survive an incoming key that does not match it.
|
||||
EntityEntry<UserEntity> trackedUser = _mockContext.ChangeTracker.Entries<UserEntity>()
|
||||
.Single(entry => entry.Entity.Username == existingUser.Username);
|
||||
Assert.Equal(existingUser.Id, trackedUser.Entity.Id);
|
||||
Assert.NotEqual(mismatchedId, trackedUser.Entity.Id);
|
||||
Assert.Equal("NewPassword123", trackedUser.Entity.Password);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenUserExists_ShouldReturnUserWithAllRelations()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity userModel = _userEntityFixture.Create();
|
||||
_mockContext.Users.Add(userModel);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<UserEntity?> result = await _sut.GetByIdAsync(userModel.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(userModel.Id, result.Value.Id);
|
||||
Assert.Equal(userModel.Username, result.Value.Username);
|
||||
Assert.Equal(userModel.Password, result.Value.Password);
|
||||
Assert.Equal(userModel.Libraries, result.Value.Libraries);
|
||||
Assert.Equal(userModel.UserPermissions, result.Value.UserPermissions);
|
||||
Assert.Equal(userModel.UserRole, result.Value.UserRole);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenUserDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<UserEntity?> result = await _sut.GetByIdAsync(nonExistentId, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenUserExistsWithPermissions_ShouldUpdatePermissionsAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity existingUser = _userEntityFixture.Create();
|
||||
PermissionEntity oldPermission = _permissionEntityFixture.Create();
|
||||
PermissionEntity newPermission = _permissionEntityFixture.Create();
|
||||
|
||||
_mockContext.Users.Add(existingUser);
|
||||
_mockContext.Permissions.Add(oldPermission);
|
||||
_mockContext.Permissions.Add(newPermission);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
UserPermissionEntity newUserPermission = _userPermissionEntityFixture.Create(existingUser, newPermission);
|
||||
newUserPermission.CreatedOnUtc = DateTime.UtcNow;
|
||||
|
||||
UserEntity updatedUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: "NewPassword", userPermissions: [newUserPermission], includeUserPermissions: true);
|
||||
updatedUser.CreatedBy = existingUser.CreatedBy;
|
||||
updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc;
|
||||
updatedUser.UpdatedOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedUser, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
UserEntity? modifiedUser = await _mockContext.Users
|
||||
.Include(u => u.UserPermissions)
|
||||
.ThenInclude(up => up.Permission)
|
||||
.FirstOrDefaultAsync(u => u.Username == existingUser.Username);
|
||||
Assert.NotNull(modifiedUser);
|
||||
Assert.Single(modifiedUser.UserPermissions);
|
||||
Assert.Equal(newPermission.PermissionName, modifiedUser.UserPermissions.First().Permission.PermissionName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenThePermissionsAreReplaced_ShouldRemoveTheOldAndAddTheNew()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity existingUser = _userEntityFixture.Create();
|
||||
PermissionEntity oldPermission = _permissionEntityFixture.Create();
|
||||
PermissionEntity newPermission = _permissionEntityFixture.Create();
|
||||
|
||||
UserEntity userWithPermissions = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: existingUser.Password, userPermissions: [_userPermissionEntityFixture.Create(existingUser, oldPermission)], includeUserPermissions: true);
|
||||
userWithPermissions.CreatedOnUtc = existingUser.CreatedOnUtc;
|
||||
userWithPermissions.CreatedBy = existingUser.CreatedBy;
|
||||
userWithPermissions.UpdatedOnUtc = existingUser.UpdatedOnUtc;
|
||||
userWithPermissions.UpdatedBy = existingUser.UpdatedBy;
|
||||
|
||||
_mockContext.Users.Add(userWithPermissions);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
UserEntity updatedUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: existingUser.Password, userPermissions: [_userPermissionEntityFixture.Create(existingUser, newPermission)], includeUserPermissions: true);
|
||||
updatedUser.CreatedBy = existingUser.CreatedBy;
|
||||
updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc;
|
||||
updatedUser.UpdatedOnUtc = DateTime.UtcNow;
|
||||
updatedUser.UpdatedBy = existingUser.Id;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedUser, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<UserPermissionEntity>? removedPermission = _mockContext.ChangeTracker
|
||||
.Entries<UserPermissionEntity>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Deleted);
|
||||
Assert.NotNull(removedPermission);
|
||||
Assert.Equal(oldPermission.Id, removedPermission.Entity.PermissionId);
|
||||
|
||||
EntityEntry<UserPermissionEntity>? addedPermission = _mockContext.ChangeTracker
|
||||
.Entries<UserPermissionEntity>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Added);
|
||||
Assert.NotNull(addedPermission);
|
||||
Assert.Equal(newPermission.Id, addedPermission.Entity.PermissionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAPermissionIsStillPresent_ShouldKeepItsIdentityAndAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity existingUser = _userEntityFixture.Create();
|
||||
PermissionEntity keptPermission = _permissionEntityFixture.Create();
|
||||
PermissionEntity removedPermission = _permissionEntityFixture.Create();
|
||||
|
||||
DateTime keptCreatedOnUtc = new(2020, 5, 6, 7, 8, 9, DateTimeKind.Utc);
|
||||
UserPermissionEntity keptUserPermission = _userPermissionEntityFixture.Create(existingUser, keptPermission);
|
||||
keptUserPermission.CreatedOnUtc = keptCreatedOnUtc;
|
||||
UserPermissionEntity removedUserPermission = _userPermissionEntityFixture.Create(existingUser, removedPermission);
|
||||
|
||||
UserEntity userWithPermissions = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: existingUser.Password, userPermissions: [keptUserPermission, removedUserPermission], includeUserPermissions: true);
|
||||
userWithPermissions.CreatedOnUtc = existingUser.CreatedOnUtc;
|
||||
userWithPermissions.CreatedBy = existingUser.CreatedBy;
|
||||
|
||||
_mockContext.Users.Add(userWithPermissions);
|
||||
_mockContext.Permissions.Add(keptPermission);
|
||||
_mockContext.Permissions.Add(removedPermission);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
UserPermissionEntity incomingKeptPermission = _userPermissionEntityFixture.Create(userWithPermissions, keptPermission);
|
||||
UserEntity updatedUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: "NewPassword", userPermissions: [incomingKeptPermission], includeUserPermissions: true);
|
||||
updatedUser.CreatedBy = existingUser.CreatedBy;
|
||||
updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc;
|
||||
updatedUser.UpdatedOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedUser, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
UserEntity? modifiedUser = await _mockContext.Users
|
||||
.Include(u => u.UserPermissions)
|
||||
.FirstOrDefaultAsync(u => u.Username == existingUser.Username);
|
||||
Assert.NotNull(modifiedUser);
|
||||
UserPermissionEntity retainedPermission = Assert.Single(modifiedUser.UserPermissions);
|
||||
Assert.Equal(keptUserPermission.Id, retainedPermission.Id);
|
||||
Assert.Equal(keptPermission.Id, retainedPermission.PermissionId);
|
||||
Assert.Equal(keptCreatedOnUtc, retainedPermission.CreatedOnUtc);
|
||||
|
||||
EntityEntry<UserPermissionEntity>? removedEntry = _mockContext.ChangeTracker
|
||||
.Entries<UserPermissionEntity>()
|
||||
.FirstOrDefault(e => e.Entity.PermissionId == removedPermission.Id);
|
||||
Assert.NotNull(removedEntry);
|
||||
Assert.Equal(EntityState.Deleted, removedEntry.State);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenUserRoleChanges_ShouldRemoveOldRoleAndAddNew()
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity oldRole = _roleEntityFixture.Create(roleName: "OldRole");
|
||||
oldRole.CreatedOnUtc = DateTime.UtcNow;
|
||||
oldRole.CreatedBy = Guid.NewGuid();
|
||||
|
||||
RoleEntity newRole = _roleEntityFixture.Create(roleName: "NewRole");
|
||||
newRole.CreatedOnUtc = DateTime.UtcNow;
|
||||
newRole.CreatedBy = Guid.NewGuid();
|
||||
|
||||
UserEntity existingUser = _userEntityFixture.Create(username: "TestUser", password: "TestPass");
|
||||
existingUser.CreatedOnUtc = DateTime.UtcNow;
|
||||
existingUser.CreatedBy = Guid.NewGuid();
|
||||
|
||||
UserRoleEntity oldUserRole = _userRoleEntityFixture.Create(userId: existingUser.Id, user: existingUser, roleId: oldRole.Id, role: oldRole);
|
||||
oldUserRole.CreatedOnUtc = DateTime.UtcNow;
|
||||
oldUserRole.CreatedBy = Guid.NewGuid();
|
||||
|
||||
DateTime originalCreatedOnUtc = existingUser.CreatedOnUtc;
|
||||
Guid originalCreatedBy = existingUser.CreatedBy;
|
||||
existingUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: existingUser.Password, userRole: oldUserRole, includeUserRole: true);
|
||||
existingUser.CreatedOnUtc = originalCreatedOnUtc;
|
||||
existingUser.CreatedBy = originalCreatedBy;
|
||||
|
||||
_mockContext.Users.Add(existingUser);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
UserRoleEntity newUserRole = _userRoleEntityFixture.Create(userId: existingUser.Id, user: existingUser, roleId: newRole.Id, role: newRole);
|
||||
newUserRole.CreatedOnUtc = DateTime.UtcNow;
|
||||
newUserRole.CreatedBy = existingUser.Id;
|
||||
|
||||
UserEntity updatedUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: existingUser.Password, userRole: newUserRole, includeUserRole: true);
|
||||
updatedUser.CreatedBy = existingUser.CreatedBy;
|
||||
updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc;
|
||||
updatedUser.UpdatedOnUtc = DateTime.UtcNow;
|
||||
updatedUser.UpdatedBy = existingUser.Id;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedUser, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<UserRoleEntity>? removedRole = _mockContext.ChangeTracker
|
||||
.Entries<UserRoleEntity>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Deleted);
|
||||
Assert.NotNull(removedRole);
|
||||
Assert.Equal(oldRole.Id, removedRole.Entity.RoleId);
|
||||
|
||||
EntityEntry<UserRoleEntity>? addedRole = _mockContext.ChangeTracker
|
||||
.Entries<UserRoleEntity>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Added);
|
||||
Assert.NotNull(addedRole);
|
||||
Assert.Equal(existingUser.Id, addedRole.Entity.UserId);
|
||||
Assert.Equal(newRole.Id, addedRole.Entity.RoleId);
|
||||
Assert.Equal(newRole, addedRole.Entity.Role);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenRemovingUserRole_ShouldRemoveRoleAndNotAddNew()
|
||||
{
|
||||
// Arrange
|
||||
UserRoleEntity oldUserRole = _userRoleEntityFixture.Create();
|
||||
|
||||
UserEntity existingUser = _userEntityFixture.Create(username: "TestUser", password: "TestPass", userRole: oldUserRole, includeUserRole: true);
|
||||
existingUser.CreatedOnUtc = DateTime.UtcNow;
|
||||
existingUser.CreatedBy = Guid.NewGuid();
|
||||
|
||||
_mockContext.Users.Add(existingUser);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
UserEntity updatedUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: existingUser.Password);
|
||||
updatedUser.CreatedBy = existingUser.CreatedBy;
|
||||
updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc;
|
||||
updatedUser.UpdatedOnUtc = DateTime.UtcNow;
|
||||
updatedUser.UpdatedBy = existingUser.Id;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedUser, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
EntityEntry<UserRoleEntity>? removedRole = _mockContext.ChangeTracker
|
||||
.Entries<UserRoleEntity>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Deleted);
|
||||
Assert.NotNull(removedRole);
|
||||
Assert.Equal(oldUserRole, removedRole.Entity);
|
||||
|
||||
EntityEntry<UserRoleEntity>? addedRole = _mockContext.ChangeTracker
|
||||
.Entries<UserRoleEntity>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Added);
|
||||
Assert.Null(addedRole);
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.Repositories.Users;
|
||||
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.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Users;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UserSettingsRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserSettingsRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly UserSettingsRepository _sut;
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserSettingsRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public UserSettingsRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new UserSettingsRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenSettingsDoNotExist_ShouldAddSettingsToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(settings, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<UserSettingsEntity>? addedSettings = _mockContext.ChangeTracker.Entries<UserSettingsEntity>()
|
||||
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == settings.Id);
|
||||
Assert.NotNull(addedSettings);
|
||||
Assert.Equal(settings.UserId, addedSettings.Entity.UserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenSettingsForUserAlreadyExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create();
|
||||
_mockContext.UserSettings.Add(settings);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(settings, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.UserSettings.UserSettingsAlreadyExists, result.FirstError);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<UserSettingsEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenSettingsExist_ShouldReturnSettings()
|
||||
{
|
||||
// Arrange
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create();
|
||||
_mockContext.UserSettings.Add(settings);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<UserSettingsEntity?> result = await _sut.GetByIdAsync(settings.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(settings.Id, result.Value.Id);
|
||||
Assert.Equal(settings.UserId, result.Value.UserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenSettingsDoNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<UserSettingsEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByUserIdAsync_WhenSettingsExist_ShouldReturnSettings()
|
||||
{
|
||||
// Arrange
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create();
|
||||
_mockContext.UserSettings.Add(settings);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<UserSettingsEntity?> result = await _sut.GetByUserIdAsync(settings.UserId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(settings.Id, result.Value.Id);
|
||||
Assert.Equal(settings.UserId, result.Value.UserId);
|
||||
Assert.Equal(settings.IsPaginationEnabled, result.Value.IsPaginationEnabled);
|
||||
Assert.Equal(settings.ItemsPerPage, result.Value.ItemsPerPage);
|
||||
Assert.Equal(settings.ShouldIgnoreThePrefixForAlphaPicker, result.Value.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByUserIdAsync_WhenSettingsDoNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<UserSettingsEntity?> result = await _sut.GetByUserIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenSettingsExist_ShouldUpdateSettingsAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create();
|
||||
_mockContext.UserSettings.Add(existingSettings);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
UserSettingsEntity updatedSettings = _userSettingsEntityFixture.Create(
|
||||
id: existingSettings.Id,
|
||||
userId: existingSettings.UserId,
|
||||
isPaginationEnabled: false,
|
||||
itemsPerPage: 12,
|
||||
shouldIgnoreThePrefixForAlphaPicker: true);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedSettings, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
UserSettingsEntity? modifiedSettings = await _mockContext.UserSettings.FirstOrDefaultAsync(settings => settings.Id == existingSettings.Id);
|
||||
Assert.NotNull(modifiedSettings);
|
||||
Assert.Equal(existingSettings.UserId, modifiedSettings.UserId);
|
||||
Assert.False(modifiedSettings.IsPaginationEnabled);
|
||||
Assert.Equal(12, modifiedSettings.ItemsPerPage);
|
||||
Assert.True(modifiedSettings.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenSettingsDoNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(settings, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.UserSettings.UserSettingsNotFound, result.FirstError);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,743 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.Seed;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Seed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DataSeedService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DataSeedServiceTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IDateTimeProvider _mockDateTimeProvider;
|
||||
private readonly IPermissionRepository _mockPermissionRepository;
|
||||
private readonly DataSeedService _sut;
|
||||
private readonly DateTime _fixedUtcNow;
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DataSeedServiceTests"/> class.
|
||||
/// </summary>
|
||||
public DataSeedServiceTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
_mockPermissionRepository = Substitute.For<IPermissionRepository>();
|
||||
_fixedUtcNow = new DateTime(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc);
|
||||
|
||||
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
|
||||
_mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository);
|
||||
|
||||
_sut = new DataSeedService(_mockUnitOfWork, _mockDateTimeProvider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationPermissionsAsync_WhenSuccessful_ShouldInsertAllPermissionsAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
_mockPermissionRepository
|
||||
.InsertAsync(Arg.Any<PermissionEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
await _mockPermissionRepository
|
||||
.Received(4)
|
||||
.InsertAsync(
|
||||
Arg.Is<PermissionEntity>(p =>
|
||||
p.CreatedBy == AuditIdentities.s_systemUserId &&
|
||||
p.CreatedOnUtc == _fixedUtcNow),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationPermissionsAsync_WhenInsertFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Error expectedError = Error.Conflict("Permission.Conflict", "Permission already exists");
|
||||
_mockPermissionRepository
|
||||
.InsertAsync(Arg.Any<PermissionEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationPermissionsAsync_ShouldCreateAllDefaultPermissions()
|
||||
{
|
||||
// Arrange
|
||||
List<AuthorizationPermission> capturedPermissions = [];
|
||||
|
||||
_mockPermissionRepository
|
||||
.InsertAsync(Arg.Any<PermissionEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created)
|
||||
.AndDoes(info => capturedPermissions.Add(info.Arg<PermissionEntity>().PermissionName));
|
||||
|
||||
// Act
|
||||
await _sut.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(new[]
|
||||
{
|
||||
AuthorizationPermission.CanViewUsers,
|
||||
AuthorizationPermission.CanDeleteUsers,
|
||||
AuthorizationPermission.CanRegisterUsers,
|
||||
AuthorizationPermission.CanCreateLibraries
|
||||
}, capturedPermissions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationRolesAsync_WhenSuccessful_ShouldInsertAllRolesAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
mockRoleRepository
|
||||
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
await mockRoleRepository
|
||||
.Received(1)
|
||||
.InsertAsync(
|
||||
Arg.Is<RoleEntity>(r =>
|
||||
r.CreatedBy == AuditIdentities.s_systemUserId &&
|
||||
r.CreatedOnUtc == _fixedUtcNow &&
|
||||
r.RoleName == "Admin"),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationRolesAsync_WhenInsertFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
|
||||
Error expectedError = Error.Conflict("Role.Conflict", "Role already exists");
|
||||
mockRoleRepository
|
||||
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationRolesAsync_WhenCalled_ShouldCreateDefaultAdminRole()
|
||||
{
|
||||
// Arrange
|
||||
List<string> capturedRoleNames = [];
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
|
||||
mockRoleRepository
|
||||
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created)
|
||||
.AndDoes(info => capturedRoleNames.Add(info.Arg<RoleEntity>().RoleName));
|
||||
|
||||
// Act
|
||||
await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(new[] { "Admin" }, capturedRoleNames);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationRolesAsync_WhenCalled_ShouldSetTheSystemAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity? capturedRole = null;
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
|
||||
mockRoleRepository
|
||||
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created)
|
||||
.AndDoes(info => capturedRole = info.Arg<RoleEntity>());
|
||||
|
||||
// Act
|
||||
await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedRole);
|
||||
Assert.Equal(AuditIdentities.s_systemUserId, capturedRole!.CreatedBy);
|
||||
Assert.Equal(_fixedUtcNow, capturedRole.CreatedOnUtc);
|
||||
Assert.Null(capturedRole.UpdatedBy);
|
||||
Assert.Null(capturedRole.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRolePermissionsAsync_WhenSuccessful_ShouldAssignAllPermissionsToAdminRole()
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
List<PermissionEntity> permissions =
|
||||
[
|
||||
_permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers),
|
||||
_permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanDeleteUsers),
|
||||
_permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanRegisterUsers)
|
||||
];
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
|
||||
IRolePermissionRepository mockRolePermissionRepository = Substitute.For<IRolePermissionRepository>();
|
||||
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
_mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository);
|
||||
_mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository);
|
||||
|
||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||
mockPermissionRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(new PaginatedResultDto<PermissionEntity>
|
||||
{
|
||||
Data = permissions,
|
||||
CurrentPage = 1,
|
||||
PerPage = permissions.Count,
|
||||
Count = permissions.Count,
|
||||
NumberOfPages = 1
|
||||
});
|
||||
mockRolePermissionRepository.InsertAsync(Arg.Any<RolePermissionEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
await mockRolePermissionRepository
|
||||
.Received(3)
|
||||
.InsertAsync(
|
||||
Arg.Is<RolePermissionEntity>(rp =>
|
||||
rp.RoleId == adminRole.Id &&
|
||||
rp.CreatedBy == AuditIdentities.s_systemUserId &&
|
||||
rp.CreatedOnUtc == _fixedUtcNow),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRolePermissionsAsync_WhenAdminRoleNotFound_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
|
||||
mockRoleRepository
|
||||
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
|
||||
.Returns((RoleEntity?)null);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Authorization.AdminAccountNotFound, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRolePermissionsAsync_WhenGetPermissionsFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
Error expectedError = Error.Failure("Permissions.NotFound", "Failed to retrieve permissions");
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
|
||||
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
_mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository);
|
||||
|
||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||
mockPermissionRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRolePermissionsAsync_WhenInsertRolePermissionFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
List<PermissionEntity> permissions = [_permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers)];
|
||||
Error expectedError = Error.Failure("RolePermission.InsertFailed", "Failed to insert role permission");
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
|
||||
IRolePermissionRepository mockRolePermissionRepository = Substitute.For<IRolePermissionRepository>();
|
||||
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
_mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository);
|
||||
_mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository);
|
||||
|
||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||
mockPermissionRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(new PaginatedResultDto<PermissionEntity>
|
||||
{
|
||||
Data = permissions,
|
||||
CurrentPage = 1,
|
||||
PerPage = permissions.Count,
|
||||
Count = permissions.Count,
|
||||
NumberOfPages = 1
|
||||
});
|
||||
mockRolePermissionRepository.InsertAsync(Arg.Any<RolePermissionEntity>(), Arg.Any<CancellationToken>()).Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRolePermissionsAsync_WhenGetAdminRoleFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Error expectedError = Error.Failure("Role.NotFound", "Failed to retrieve admin role");
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
|
||||
mockRoleRepository
|
||||
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRoleToAdministratorAccount_WhenSuccessful_ShouldAssignAdminRoleToUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
UserEntity adminUser = _userEntityFixture.Create();
|
||||
// Use the adminUser.Id instead of the randomly generated userId.
|
||||
userId = adminUser.Id;
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
|
||||
IUserRoleRepository mockUserRoleRepository = Substitute.For<IUserRoleRepository>();
|
||||
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
|
||||
_mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository);
|
||||
|
||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||
mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>()).Returns(adminUser);
|
||||
mockUserRoleRepository.InsertAsync(Arg.Any<UserRoleEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
await mockUserRoleRepository
|
||||
.Received(1)
|
||||
.InsertAsync(
|
||||
Arg.Is<UserRoleEntity>(ur =>
|
||||
ur.UserId == userId &&
|
||||
ur.RoleId == adminRole.Id &&
|
||||
ur.CreatedBy == AuditIdentities.s_systemUserId &&
|
||||
ur.CreatedOnUtc == _fixedUtcNow),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRoleToAdministratorAccount_WhenAdminRoleNotFound_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
|
||||
mockRoleRepository
|
||||
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
|
||||
.Returns((RoleEntity?)null);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Authorization.AdminRoleNotFound, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRoleToAdministratorAccount_WhenUserNotFound_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
|
||||
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
|
||||
|
||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||
mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>()).Returns((UserEntity?)null);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Authorization.AdminAccountNotFound, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRoleToAdministratorAccount_WhenInsertUserRoleFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
UserEntity adminUser = _userEntityFixture.Create();
|
||||
|
||||
Error expectedError = Error.Failure("UserRole.InsertFailed", "Failed to insert user role");
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
|
||||
IUserRoleRepository mockUserRoleRepository = Substitute.For<IUserRoleRepository>();
|
||||
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
|
||||
_mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository);
|
||||
|
||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||
mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>()).Returns(adminUser);
|
||||
mockUserRoleRepository.InsertAsync(Arg.Any<UserRoleEntity>(), Arg.Any<CancellationToken>()).Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRoleToAdministratorAccount_WhenGetAdminRoleFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Error expectedError = Error.Failure("Role.NotFound", "Failed to retrieve admin role");
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
|
||||
mockRoleRepository
|
||||
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRoleToAdministratorAccount_WhenGetUserFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
Error expectedError = Error.Failure("User.NotFound", "Failed to retrieve user");
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
|
||||
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
|
||||
|
||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||
mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>()).Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultScheduledJobsAsync_WhenCalled_ShouldInsertTheSixDefaultJobsAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
Guid adminUserId = Guid.NewGuid();
|
||||
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
|
||||
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
|
||||
List<ScheduledJobEntity> capturedScheduledJobs = [];
|
||||
mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created)
|
||||
.AndDoes(info => capturedScheduledJobs.Add(info.Arg<ScheduledJobEntity>()));
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
Assert.Equal(6, capturedScheduledJobs.Count);
|
||||
Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(ScheduledJobStatus.Active, scheduledJob.Status));
|
||||
Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(adminUserId, scheduledJob.OwnerUserId));
|
||||
Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(AuditIdentities.s_systemUserId, scheduledJob.CreatedBy));
|
||||
Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(_fixedUtcNow, scheduledJob.CreatedOnUtc));
|
||||
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.ScanMediaLibraries && scheduledJob.ScheduleType == ScheduleType.DailyAtHourAndMinute && scheduledJob.Hour == 0 && scheduledJob.Minute == 0);
|
||||
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanTemporaryFiles && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup);
|
||||
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanTemporaryFiles && scheduledJob.ScheduleType == ScheduleType.WithIntervalInMinutes && scheduledJob.IntervalMinutes == 720);
|
||||
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.RepairThemes && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup);
|
||||
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanScheduledJobExecutionHistory && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup);
|
||||
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup);
|
||||
|
||||
await mockScheduledJobRepository.Received(6).InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
await mockScheduledJobRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultScheduledJobsAsync_WhenInsertScheduledJobFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid adminUserId = Guid.NewGuid();
|
||||
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
|
||||
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
|
||||
Error expectedError = Error.Failure("ScheduledJobs.InsertFailed", "Failed to insert the scheduled job");
|
||||
mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created, expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationPermissionsAsync_WhenSaveChangesFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Error expectedError = Error.Failure("Persistence.SaveFailed", "The changes could not be saved.");
|
||||
_mockPermissionRepository
|
||||
.InsertAsync(Arg.Any<PermissionEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockUnitOfWork
|
||||
.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationRolesAsync_WhenSaveChangesFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Error expectedError = Error.Failure("Persistence.SaveFailed", "The changes could not be saved.");
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
mockRoleRepository
|
||||
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockUnitOfWork
|
||||
.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRolePermissionsAsync_WhenSaveChangesFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Error expectedError = Error.Failure("Persistence.SaveFailed", "The changes could not be saved.");
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
List<PermissionEntity> permissions = [_permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers)];
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
|
||||
IRolePermissionRepository mockRolePermissionRepository = Substitute.For<IRolePermissionRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
_mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository);
|
||||
_mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository);
|
||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||
mockPermissionRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(new PaginatedResultDto<PermissionEntity>
|
||||
{
|
||||
Data = permissions,
|
||||
CurrentPage = 1,
|
||||
PerPage = permissions.Count,
|
||||
Count = permissions.Count,
|
||||
NumberOfPages = 1
|
||||
});
|
||||
mockRolePermissionRepository.InsertAsync(Arg.Any<RolePermissionEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
|
||||
_mockUnitOfWork
|
||||
.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRoleToAdministratorAccount_WhenSaveChangesFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Error expectedError = Error.Failure("Persistence.SaveFailed", "The changes could not be saved.");
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
UserEntity adminUser = _userEntityFixture.Create();
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
|
||||
IUserRoleRepository mockUserRoleRepository = Substitute.For<IUserRoleRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
|
||||
_mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository);
|
||||
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
|
||||
mockUserRepository.GetByIdAsync(adminUser.Id, cancellationToken: Arg.Any<CancellationToken>()).Returns(adminUser);
|
||||
mockUserRoleRepository.InsertAsync(Arg.Any<UserRoleEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
|
||||
_mockUnitOfWork
|
||||
.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRoleToAdministratorAccount(adminUser.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultScheduledJobsAsync_WhenSaveChangesFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid adminUserId = Guid.NewGuid();
|
||||
Error expectedError = Error.Failure("Persistence.SaveFailed", "The changes could not be saved.");
|
||||
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
|
||||
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
|
||||
mockScheduledJobRepository
|
||||
.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockUnitOfWork
|
||||
.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.DataAccess.Common.DependencyInjection;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.DataAccess.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.UoW;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UnitOfWork"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UnitOfWorkTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UnitOfWorkTests"/> class.
|
||||
/// </summary>
|
||||
public UnitOfWorkTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_fixture.Customize<LuminaDbContext>(composer => composer.FromFactory(() =>
|
||||
{
|
||||
DbContextOptions<LuminaDbContext> options = new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
return Substitute.ForPartsOf<LuminaDbContext>(options);
|
||||
}));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides the repository properties exposed by the unit of work.
|
||||
/// </summary>
|
||||
/// <returns>An enumerable of tuples containing the repository property name and its accessor.</returns>
|
||||
public static IEnumerable<object[]> GetRepositoryProperties()
|
||||
{
|
||||
yield return new object[] { nameof(IUnitOfWork.PermissionRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.PermissionRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.RolePermissionRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.RolePermissionRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.RoleRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.RoleRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.UserRoleRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.UserRoleRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.BookRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.BookRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.ArtistRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.ArtistRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.AlbumRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.AlbumRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.TrackRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.TrackRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.MediaContributorRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.MediaContributorRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.DirectoryScanFingerprintRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.DirectoryScanFingerprintRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.LibraryRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.LibraryScanRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryScanRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.LibraryScanSnapshotRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryScanSnapshotRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.LibraryScanStagingResultsRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryScanStagingResultsRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.LibraryMetadataProviderConfigurationRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryMetadataProviderConfigurationRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.ArtworkProviderConfigurationRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.ArtworkProviderConfigurationRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.LibraryBookReaderConfigurationRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryBookReaderConfigurationRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.PluginRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.PluginRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.ThemeRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.ThemeRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.UserRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.UserRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.UserSettingsRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.UserSettingsRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.MediaConsumptionRecordRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.MediaConsumptionRecordRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.MediaResumePointRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.MediaResumePointRepository) };
|
||||
yield return new object[] { nameof(IUnitOfWork.ConsumptionStatisticsRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.ConsumptionStatisticsRepository) };
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(GetRepositoryProperties))]
|
||||
public void RepositoryProperty_WhenAccessed_ShouldReturnRepositoryAndCacheInstance(string propertyName, Func<UnitOfWork, object> repositoryAccessor)
|
||||
{
|
||||
// Arrange
|
||||
UnitOfWork unitOfWork = CreateUnitOfWork();
|
||||
|
||||
// Act
|
||||
object firstAccess = repositoryAccessor(unitOfWork);
|
||||
object secondAccess = repositoryAccessor(unitOfWork);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(firstAccess);
|
||||
Assert.Same(firstAccess, secondAccess);
|
||||
Assert.EndsWith(propertyName, firstAccess.GetType().Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveChangesAsync_WhenCalled_ShouldCallDbContextSaveChangesAsync()
|
||||
{
|
||||
// Arrange
|
||||
LuminaDbContext dbContext = _fixture.Create<LuminaDbContext>();
|
||||
UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
|
||||
CancellationToken cancellationToken = new();
|
||||
|
||||
// Act
|
||||
Result<Success> result = await unitOfWork.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
await dbContext.Received(1).SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveChangesAsInitializationAsync_WhenCalled_ShouldResetTheFlagAfterTheSave()
|
||||
{
|
||||
// Arrange
|
||||
DbContextOptions<LuminaDbContext> options = new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
LuminaDbContext dbContext = new(options);
|
||||
UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
|
||||
dbContext.Roles.Add(_roleEntityFixture.Create(roleName: "TestRole"));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await unitOfWork.SaveChangesAsInitializationAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.False(dbContext.IsInitializationSave);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveChangesAsInitializationAsync_WhenSaveIsCancelled_ShouldResetTheFlag()
|
||||
{
|
||||
// Arrange
|
||||
DbContextOptions<LuminaDbContext> options = new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
LuminaDbContext dbContext = new(options);
|
||||
UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
|
||||
dbContext.Roles.Add(_roleEntityFixture.Create(roleName: "TestRole"));
|
||||
CancellationToken cancellationToken = new(canceled: true);
|
||||
|
||||
// Act
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => unitOfWork.SaveChangesAsInitializationAsync(cancellationToken));
|
||||
|
||||
// Assert
|
||||
Assert.False(dbContext.IsInitializationSave);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearTrackedEntities_WhenCalled_ShouldDetachAllTrackedEntities()
|
||||
{
|
||||
// Arrange
|
||||
DbContextOptions<LuminaDbContext> options = new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
LuminaDbContext dbContext = new(options);
|
||||
UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
|
||||
dbContext.Roles.Add(_roleEntityFixture.Create(id: Guid.NewGuid(), roleName: "TestRole"));
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
Assert.NotEmpty(dbContext.ChangeTracker.Entries());
|
||||
|
||||
// Act
|
||||
unitOfWork.ClearTrackedEntities();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(dbContext.ChangeTracker.Entries());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnitOfWork_WhenResolvedFromServiceProvider_ShouldExposeRepositories()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
DataAccessLayerServices.AddDataAccessLayerServices(services);
|
||||
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
|
||||
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
// Act
|
||||
IUnitOfWork unitOfWork = serviceProvider.GetRequiredService<IUnitOfWork>();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(unitOfWork.PermissionRepository);
|
||||
Assert.NotNull(unitOfWork.RoleRepository);
|
||||
Assert.NotNull(unitOfWork.UserRepository);
|
||||
}
|
||||
|
||||
private UnitOfWork CreateUnitOfWork()
|
||||
{
|
||||
return new(_fixture.Create<LuminaDbContext>(), Substitute.For<IDateTimeProvider>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
|
||||
<_Parameter1>DisableTestParallelization = true</_Parameter1>
|
||||
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" />
|
||||
<PackageReference Include="Bogus" />
|
||||
<PackageReference Include="coverlet.collector">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
||||
<PackageReference Include="EntityFrameworkCore.Testing.NSubstitute" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="NSubstitute" />
|
||||
<PackageReference Include="xunit" />
|
||||
<PackageReference Include="xunit.runner.visualstudio">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Lumina.DataAccess\Lumina.DataAccess.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Application.Fixtures\Lumina.Application.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Reference in new issue
Block a user