mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Normalizes tag and genre names and migrates existing values
This commit is contained in:
1 parent
8a5cb9116e
commit
eaca69bf2a
19 files changed
+4089
-58
No files matched your search
@@ -1,12 +1,12 @@
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for a shared reference entity, whose identity is its name and whose rows are shared across the whole storage medium instead of being owned by a single parent.
|
||||
/// Interface for a shared reference entity, whose identity is its normalized name and whose rows are shared across the whole storage medium instead of being owned by a single parent.
|
||||
/// </summary>
|
||||
public interface ISharedReferenceEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the name that identifies the shared reference.
|
||||
/// Gets the name that identifies the shared reference, stored in lowercase and culture-invariant form.
|
||||
/// </summary>
|
||||
string? Name { get; }
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using System.Data.Common;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Common.Interceptors;
|
||||
|
||||
/// <summary>
|
||||
/// Registers the SQL function used by the shared reference normalization migration, so that names are folded with the same culture-invariant rule as the domain value objects.
|
||||
/// </summary>
|
||||
public sealed class SqliteSharedReferenceNormalizationInterceptor : DbConnectionInterceptor
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of the SQL function that trims a name and lowercases it with the invariant culture.
|
||||
/// </summary>
|
||||
public const string NORMALIZE_FUNCTION_NAME = "lumina_normalize_shared_reference_name";
|
||||
|
||||
/// <summary>
|
||||
/// Intercepts a synchronously opened connection to register the normalization function.
|
||||
/// </summary>
|
||||
/// <param name="connection">The connection that was opened.</param>
|
||||
/// <param name="eventData">The event data of the opened connection.</param>
|
||||
public override void ConnectionOpened(DbConnection connection, ConnectionEndEventData eventData)
|
||||
{
|
||||
RegisterNormalizationFunction(connection);
|
||||
base.ConnectionOpened(connection, eventData);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Intercepts an asynchronously opened connection to register the normalization function.
|
||||
/// </summary>
|
||||
/// <param name="connection">The connection that was opened.</param>
|
||||
/// <param name="eventData">The event data of the opened connection.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public override Task ConnectionOpenedAsync(DbConnection connection, ConnectionEndEventData eventData, CancellationToken cancellationToken = default)
|
||||
{
|
||||
RegisterNormalizationFunction(connection);
|
||||
return base.ConnectionOpenedAsync(connection, eventData, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the normalization function on <paramref name="connection"/> when it is a SQLite connection.
|
||||
/// </summary>
|
||||
/// <param name="connection">The connection that was opened.</param>
|
||||
private static void RegisterNormalizationFunction(DbConnection connection)
|
||||
{
|
||||
if (connection is not SqliteConnection sqliteConnection)
|
||||
return;
|
||||
sqliteConnection.CreateFunction(NORMALIZE_FUNCTION_NAME, (string? name) => name?.Trim().ToLowerInvariant(), isDeterministic: true);
|
||||
}
|
||||
}
|
||||
Generated
+3766
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,64 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
/// <summary>
|
||||
/// Normalizes the existing tag and genre names to their trimmed lowercase form, and merges the rows that differ only by casing.
|
||||
/// </summary>
|
||||
public partial class NormalizesTagAndGenreNames : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
// The value objects now store names trimmed and lowercased with the invariant culture, so the existing rows must be normalized before new
|
||||
// scans start reusing them by their normalized name. The SQL function is registered on every opened connection by
|
||||
// SqliteSharedReferenceNormalizationInterceptor, so non-ASCII uppercase letters are folded exactly like the value objects fold them.
|
||||
// The lowercase rows are inserted first, so that the join rows can always be repointed.
|
||||
migrationBuilder.Sql("""
|
||||
INSERT OR IGNORE INTO Tags (Name)
|
||||
SELECT DISTINCT lumina_normalize_shared_reference_name(Name) FROM Tags;
|
||||
|
||||
INSERT OR IGNORE INTO Genres (Name)
|
||||
SELECT DISTINCT lumina_normalize_shared_reference_name(Name) FROM Genres;
|
||||
""");
|
||||
|
||||
// A repointed join row that would collide with an existing lowercase join row is left in its old form by OR IGNORE, and is removed below.
|
||||
migrationBuilder.Sql("""
|
||||
UPDATE OR IGNORE TrackTags SET TagId = lumina_normalize_shared_reference_name(TagId) WHERE TagId <> lumina_normalize_shared_reference_name(TagId);
|
||||
UPDATE OR IGNORE AlbumTags SET TagId = lumina_normalize_shared_reference_name(TagId) WHERE TagId <> lumina_normalize_shared_reference_name(TagId);
|
||||
UPDATE OR IGNORE ArtistTags SET TagId = lumina_normalize_shared_reference_name(TagId) WHERE TagId <> lumina_normalize_shared_reference_name(TagId);
|
||||
UPDATE OR IGNORE BookTags SET TagId = lumina_normalize_shared_reference_name(TagId) WHERE TagId <> lumina_normalize_shared_reference_name(TagId);
|
||||
|
||||
UPDATE OR IGNORE TrackGenres SET GenreId = lumina_normalize_shared_reference_name(GenreId) WHERE GenreId <> lumina_normalize_shared_reference_name(GenreId);
|
||||
UPDATE OR IGNORE AlbumGenres SET GenreId = lumina_normalize_shared_reference_name(GenreId) WHERE GenreId <> lumina_normalize_shared_reference_name(GenreId);
|
||||
UPDATE OR IGNORE ArtistGenres SET GenreId = lumina_normalize_shared_reference_name(GenreId) WHERE GenreId <> lumina_normalize_shared_reference_name(GenreId);
|
||||
UPDATE OR IGNORE BookGenres SET GenreId = lumina_normalize_shared_reference_name(GenreId) WHERE GenreId <> lumina_normalize_shared_reference_name(GenreId);
|
||||
""");
|
||||
|
||||
// The rows still carrying a mixed-case or untrimmed name are the duplicates that could not be repointed, because the lowercase join row
|
||||
// was already present. They are removed before the old tag and genre rows, so that no foreign key is left pointing at a deleted row.
|
||||
migrationBuilder.Sql("""
|
||||
DELETE FROM TrackTags WHERE TagId <> lumina_normalize_shared_reference_name(TagId);
|
||||
DELETE FROM AlbumTags WHERE TagId <> lumina_normalize_shared_reference_name(TagId);
|
||||
DELETE FROM ArtistTags WHERE TagId <> lumina_normalize_shared_reference_name(TagId);
|
||||
DELETE FROM BookTags WHERE TagId <> lumina_normalize_shared_reference_name(TagId);
|
||||
|
||||
DELETE FROM TrackGenres WHERE GenreId <> lumina_normalize_shared_reference_name(GenreId);
|
||||
DELETE FROM AlbumGenres WHERE GenreId <> lumina_normalize_shared_reference_name(GenreId);
|
||||
DELETE FROM ArtistGenres WHERE GenreId <> lumina_normalize_shared_reference_name(GenreId);
|
||||
DELETE FROM BookGenres WHERE GenreId <> lumina_normalize_shared_reference_name(GenreId);
|
||||
|
||||
DELETE FROM Tags WHERE Name <> lumina_normalize_shared_reference_name(Name);
|
||||
DELETE FROM Genres WHERE Name <> lumina_normalize_shared_reference_name(Name);
|
||||
""");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
// Normalization is irreversible: the original letter casing of the names is not retained, so there is nothing to restore.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,25 +17,26 @@ namespace Lumina.DataAccess.Common.Persistence;
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is the toolkit's only concern expressed over a family of entity shapes, through the <see cref="ISharedReferenceEntity"/> marker interface:
|
||||
/// a shared reference is resolved by its name, the stored row wins over the incoming instance, and within-request duplicates are collapsed to one instance.
|
||||
/// a shared reference is resolved by its normalized name, trimmed and lowercased with the invariant culture, the stored row wins over the incoming instance,
|
||||
/// and within-request duplicates are collapsed to one instance. Differently cased spellings of the same name therefore resolve to the same row.
|
||||
/// No per-entity method is ever needed, so a new shared reference type adds no new persistence type. A shared reference whose name is null or whitespace
|
||||
/// cannot be keyed and would be lost silently, so it fails the resolution with the caller-provided error instead of being dropped.
|
||||
/// </remarks>
|
||||
internal static class SharedReferenceResolver
|
||||
{
|
||||
/// <summary>
|
||||
/// Resolves the single <typeparamref name="TEntity"/> instance that represents each distinct name carried by <paramref name="incomingEntities"/>.
|
||||
/// Resolves the single <typeparamref name="TEntity"/> instance that represents each distinct normalized name carried by <paramref name="incomingEntities"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The stored row wins over the incoming instance, so that a shared reference that is already persisted is reused instead of inserted again. The
|
||||
/// instances are also collapsed by name, so that a name shared by several parents of the same request is only ever tracked once.
|
||||
/// instances are also collapsed by normalized name, so that a name shared by several parents of the same request is only ever tracked once.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TEntity">The type of the shared reference entity.</typeparam>
|
||||
/// <param name="context">The Entity Framework context the stored rows are read through.</param>
|
||||
/// <param name="incomingEntities">The shared references carried by the entity that is about to be persisted.</param>
|
||||
/// <param name="invalidNameError">The error returned when a shared reference carries a name that is null or whitespace.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A result containing either a dictionary that maps each distinct name to the single instance that represents it, or an error.</returns>
|
||||
/// <returns>A result containing either a dictionary that maps each distinct normalized name to the single instance that represents it, or an error.</returns>
|
||||
internal static async Task<Result<IReadOnlyDictionary<string, TEntity>>> ResolveAsync<TEntity>(LuminaDbContext context, IEnumerable<TEntity> incomingEntities, Error invalidNameError, CancellationToken cancellationToken)
|
||||
where TEntity : class, ISharedReferenceEntity
|
||||
{
|
||||
@@ -47,7 +48,7 @@ internal static class SharedReferenceResolver
|
||||
string? name = incomingEntity.Name;
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
return invalidNameError;
|
||||
resolvedByName.TryAdd(name, incomingEntity);
|
||||
resolvedByName.TryAdd(NormalizeName(name), incomingEntity);
|
||||
}
|
||||
|
||||
if (resolvedByName.Count == 0)
|
||||
@@ -58,10 +59,13 @@ internal static class SharedReferenceResolver
|
||||
foreach (TEntity trackedEntity in context.Set<TEntity>().Local)
|
||||
{
|
||||
string? trackedName = trackedEntity.Name;
|
||||
if (!string.IsNullOrWhiteSpace(trackedName) && resolvedByName.ContainsKey(trackedName))
|
||||
if (string.IsNullOrWhiteSpace(trackedName))
|
||||
continue;
|
||||
string normalizedTrackedName = NormalizeName(trackedName);
|
||||
if (resolvedByName.ContainsKey(normalizedTrackedName))
|
||||
{
|
||||
resolvedByName[trackedName] = trackedEntity;
|
||||
namesResolvedFromTrackedEntities.Add(trackedName);
|
||||
resolvedByName[normalizedTrackedName] = trackedEntity;
|
||||
namesResolvedFromTrackedEntities.Add(normalizedTrackedName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,12 +73,13 @@ internal static class SharedReferenceResolver
|
||||
List<string> unresolvedNames = [.. resolvedByName.Keys.Where(name => !namesResolvedFromTrackedEntities.Contains(name))];
|
||||
if (unresolvedNames.Count > 0)
|
||||
{
|
||||
// Stored names are normalized when they are written, so the normalized incoming names are matched directly against the primary key.
|
||||
List<TEntity> storedEntities = await context.Set<TEntity>()
|
||||
.Where(entity => unresolvedNames.Contains(EF.Property<string>(entity, nameof(ISharedReferenceEntity.Name))))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
foreach (TEntity storedEntity in storedEntities)
|
||||
resolvedByName[storedEntity.Name!] = storedEntity;
|
||||
resolvedByName[NormalizeName(storedEntity.Name!)] = storedEntity;
|
||||
}
|
||||
|
||||
return resolvedByName;
|
||||
@@ -96,12 +101,22 @@ internal static class SharedReferenceResolver
|
||||
string? name = incomingEntity.Name;
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
continue;
|
||||
if (resolvedEntities.TryGetValue(name, out TEntity? resolvedEntity) && resolvedEntity is not null)
|
||||
if (resolvedEntities.TryGetValue(NormalizeName(name), out TEntity? resolvedEntity) && resolvedEntity is not null)
|
||||
normalizedEntities.Add(resolvedEntity);
|
||||
}
|
||||
return normalizedEntities;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalizes a shared reference name to the form that identifies it: trimmed and lowercased with the invariant culture.
|
||||
/// </summary>
|
||||
/// <param name="name">The name to normalize, which must not be null or whitespace.</param>
|
||||
/// <returns>The normalized name.</returns>
|
||||
private static string NormalizeName(string name)
|
||||
{
|
||||
return name.Trim().ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reconciles the shared reference collection <paramref name="existingEntities"/> against <paramref name="incomingEntities"/>, reusing the stored rows whose names already exist.
|
||||
/// </summary>
|
||||
|
||||
@@ -10,6 +10,7 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
#endregion
|
||||
|
||||
@@ -64,6 +65,16 @@ public class LuminaDbContext : DbContext
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the database context options, including the interceptors that apply to every connection.
|
||||
/// </summary>
|
||||
/// <param name="optionsBuilder">The builder used to configure the database context.</param>
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
base.OnConfiguring(optionsBuilder);
|
||||
optionsBuilder.AddInterceptors(new SqliteSharedReferenceNormalizationInterceptor());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mappings for the database context.
|
||||
/// </summary>
|
||||
|
||||
@@ -14,17 +14,17 @@ namespace Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
public class Genre : ValueObject
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the name of the genre element of the media item.
|
||||
/// Gets the name of the genre element of the media item, in lowercase and culture-invariant form.
|
||||
/// </summary>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Genre"/> class.
|
||||
/// </summary>
|
||||
/// <param name="name">The value representing this object.</param>
|
||||
/// <param name="name">The value representing this object, which is trimmed and lowercased with the invariant culture.</param>
|
||||
private Genre(string name)
|
||||
{
|
||||
Name = name.Trim();
|
||||
Name = name.Trim().ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -15,17 +15,17 @@ namespace Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
public class Tag : ValueObject
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the name of the tag element of the media item.
|
||||
/// Gets the name of the tag element of the media item, in lowercase and culture-invariant form.
|
||||
/// </summary>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Tag"/> class.
|
||||
/// </summary>
|
||||
/// <param name="name">The value representing this object.</param>
|
||||
/// <param name="name">The value representing this object, which is trimmed and lowercased with the invariant culture.</param>
|
||||
private Tag(string name)
|
||||
{
|
||||
Name = name.Trim();
|
||||
Name = name.Trim().ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.IntegrationTests.Common.Interceptors;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SqliteSharedReferenceNormalizationInterceptor"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SqliteSharedReferenceNormalizationInterceptorTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(" Horror ", "horror")] // ASCII letters
|
||||
[InlineData(" ÉLECTRO ", "électro")] // non-ASCII Latin letters
|
||||
[InlineData("ЖАНР", "жанр")] // non-Latin letters
|
||||
public async Task ConnectionOpenedAsync_WhenTheConnectionIsOpened_ShouldRegisterTheInvariantNormalizationFunction(string name, string expectedName)
|
||||
{
|
||||
// Arrange
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
|
||||
|
||||
// Act
|
||||
await context.Database.OpenConnectionAsync();
|
||||
SqliteConnection connection = (SqliteConnection)context.Database.GetDbConnection();
|
||||
await using SqliteCommand command = connection.CreateCommand();
|
||||
command.CommandText = $"SELECT {SqliteSharedReferenceNormalizationInterceptor.NORMALIZE_FUNCTION_NAME}($name);";
|
||||
command.Parameters.AddWithValue("$name", name);
|
||||
object? result = await command.ExecuteScalarAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedName, result);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -212,10 +212,10 @@ public class AddTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
|
||||
// Genres and tags checks.
|
||||
Assert.Equal(
|
||||
metadata.Genres!.Select(genre => genre.Name).OrderBy(name => name),
|
||||
metadata.Genres!.Select(genre => genre.Name!.ToLowerInvariant()).OrderBy(name => name),
|
||||
trackResponse.Metadata.Genres!.Select(genre => genre.Name).OrderBy(name => name));
|
||||
Assert.Equal(
|
||||
metadata.Tags!.Select(tag => tag.Name).OrderBy(name => name),
|
||||
metadata.Tags!.Select(tag => tag.Name!.ToLowerInvariant()).OrderBy(name => name),
|
||||
trackResponse.Metadata.Tags!.Select(tag => tag.Name).OrderBy(name => name));
|
||||
|
||||
// Moods, ISRCs, contributors and ratings checks.
|
||||
|
||||
+4
-4
@@ -133,14 +133,14 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
// genres checks
|
||||
Assert.Equal(bookRequest.Metadata.Genres!.Count, bookResponse.Metadata.Genres!.Count);
|
||||
Assert.Equal(
|
||||
bookRequest.Metadata.Genres.Select(genre => genre.Name).OrderBy(x => x),
|
||||
bookResponse.Metadata.Genres.Select(genre => genre.Name).OrderBy(x => x));
|
||||
bookRequest.Metadata.Genres.Select(genre => genre.Name!.ToLowerInvariant()).OrderBy(name => name),
|
||||
bookResponse.Metadata.Genres.Select(genre => genre.Name).OrderBy(name => name));
|
||||
|
||||
// tags checks
|
||||
Assert.Equal(bookRequest.Metadata.Tags!.Count, bookResponse.Metadata.Tags!.Count);
|
||||
Assert.Equal(
|
||||
bookRequest.Metadata.Tags.Select(tag => tag.Name).OrderBy(x => x),
|
||||
bookResponse.Metadata.Tags.Select(tag => tag.Name).OrderBy(x => x));
|
||||
bookRequest.Metadata.Tags.Select(tag => tag.Name!.ToLowerInvariant()).OrderBy(name => name),
|
||||
bookResponse.Metadata.Tags.Select(tag => tag.Name).OrderBy(name => name));
|
||||
|
||||
// book specific properties
|
||||
Assert.Equal(bookRequest.Format, bookResponse.Format);
|
||||
|
||||
+2
-2
@@ -461,8 +461,8 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, title: title, path: $"/books/{Guid.NewGuid()}.epub", includeMetadata: false);
|
||||
book.Tags = [_tagEntityFixture.Create(name: $"Tag-{Guid.NewGuid()}")];
|
||||
book.Genres = [_genreEntityFixture.Create(name: $"Genre-{Guid.NewGuid()}")];
|
||||
book.Tags = [_tagEntityFixture.Create(name: $"tag-{Guid.NewGuid()}")];
|
||||
book.Genres = [_genreEntityFixture.Create(name: $"genre-{Guid.NewGuid()}")];
|
||||
book.ISBNs = [_isbnEntityFixture.Create(value: "9780395272237", format: IsbnFormat.Isbn13)];
|
||||
book.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)];
|
||||
dbContext.Books.Add(book);
|
||||
|
||||
+5
-5
@@ -31,7 +31,7 @@ public class GenreDtoMappingTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(genreDto.Name, result.Value.Name);
|
||||
Assert.Equal("rock", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -50,7 +50,7 @@ public class GenreDtoMappingTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(genreDto.Name, result.Value.Name);
|
||||
Assert.Equal(name.ToLowerInvariant(), result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -92,7 +92,7 @@ public class GenreDtoMappingTests
|
||||
for (int i = 0; i < genreDtos.Count; i++)
|
||||
{
|
||||
Assert.False(resultList[i].IsFailure);
|
||||
Assert.Equal(genreDtos[i].Name, resultList[i].Value.Name);
|
||||
Assert.Equal(genreDtos[i].Name!.ToLowerInvariant(), resultList[i].Value.Name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,12 +117,12 @@ public class GenreDtoMappingTests
|
||||
|
||||
List<Result<Genre>> resultList = results.ToList();
|
||||
Assert.False(resultList[0].IsFailure);
|
||||
Assert.Equal("Rock", resultList[0].Value.Name);
|
||||
Assert.Equal("rock", resultList[0].Value.Name);
|
||||
|
||||
Assert.True(resultList[1].IsFailure);
|
||||
|
||||
Assert.False(resultList[2].IsFailure);
|
||||
Assert.Equal("Jazz", resultList[2].Value.Name);
|
||||
Assert.Equal("jazz", resultList[2].Value.Name);
|
||||
|
||||
Assert.True(resultList[3].IsFailure);
|
||||
}
|
||||
|
||||
+4
-4
@@ -81,7 +81,7 @@ public class GenreEntityMappingTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(entity.Name, result.Value.Name);
|
||||
Assert.Equal("fiction", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -120,11 +120,11 @@ public class GenreEntityMappingTests
|
||||
Assert.NotNull(results);
|
||||
Assert.Equal(entities.Count, results.Count());
|
||||
|
||||
List<Result<Genre>> resultList = results.ToList();
|
||||
List<Result<Genre>> resultList = [.. results];
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
{
|
||||
Assert.False(resultList[i].IsFailure);
|
||||
Assert.Equal(entities[i].Name, resultList[i].Value.Name);
|
||||
Assert.Equal(entities[i].Name!.ToLowerInvariant(), resultList[i].Value.Name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,7 +147,7 @@ public class GenreEntityMappingTests
|
||||
Assert.NotNull(results);
|
||||
Assert.Equal(entities.Count, results.Count());
|
||||
|
||||
List<GenreDto> resultList = results.ToList();
|
||||
List<GenreDto> resultList = [.. results];
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
Assert.Equal(entities[i].Name, resultList[i].Name);
|
||||
}
|
||||
|
||||
+15
-15
@@ -23,7 +23,7 @@ public class TagDtoMappingTests
|
||||
public void ToDomainValueObject_WhenMappingValidTagDto_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TagDto tagDto = _tagDtoFixture.Create(name: "indie");
|
||||
TagDto tagDto = _tagDtoFixture.Create(name: "Indie");
|
||||
|
||||
// Act
|
||||
Result<Tag> result = tagDto.ToDomainValueObject();
|
||||
@@ -31,15 +31,15 @@ public class TagDtoMappingTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(tagDto.Name, result.Value.Name);
|
||||
Assert.Equal("indie", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("indie")]
|
||||
[InlineData("electronic")]
|
||||
[InlineData("instrumental")]
|
||||
[InlineData("live")]
|
||||
[InlineData("acoustic")]
|
||||
[InlineData("Indie")]
|
||||
[InlineData("Electronic")]
|
||||
[InlineData("Instrumental")]
|
||||
[InlineData("Live")]
|
||||
[InlineData("Acoustic")]
|
||||
public void ToDomainValueObject_WhenMappingDifferentValidTagDtos_ShouldMapCorrectly(string name)
|
||||
{
|
||||
// Arrange
|
||||
@@ -51,7 +51,7 @@ public class TagDtoMappingTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(tagDto.Name, result.Value.Name);
|
||||
Assert.Equal(name.ToLowerInvariant(), result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -76,10 +76,10 @@ public class TagDtoMappingTests
|
||||
// Arrange
|
||||
List<TagDto> tagDtos =
|
||||
[
|
||||
_tagDtoFixture.Create(name: "indie"),
|
||||
_tagDtoFixture.Create(name: "electronic"),
|
||||
_tagDtoFixture.Create(name: "instrumental"),
|
||||
_tagDtoFixture.Create(name: "live")
|
||||
_tagDtoFixture.Create(name: "Indie"),
|
||||
_tagDtoFixture.Create(name: "Electronic"),
|
||||
_tagDtoFixture.Create(name: "Instrumental"),
|
||||
_tagDtoFixture.Create(name: "Live")
|
||||
];
|
||||
|
||||
// Act
|
||||
@@ -93,7 +93,7 @@ public class TagDtoMappingTests
|
||||
for (int i = 0; i < tagDtos.Count; i++)
|
||||
{
|
||||
Assert.False(resultList[i].IsFailure);
|
||||
Assert.Equal(tagDtos[i].Name, resultList[i].Value.Name);
|
||||
Assert.Equal(tagDtos[i].Name!.ToLowerInvariant(), resultList[i].Value.Name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,9 +103,9 @@ public class TagDtoMappingTests
|
||||
// Arrange
|
||||
List<TagDto> tagDtos =
|
||||
[
|
||||
_tagDtoFixture.Create(name: "indie"),
|
||||
_tagDtoFixture.Create(name: "Indie"),
|
||||
_tagDtoFixture.Create(name: ""),
|
||||
_tagDtoFixture.Create(name: "electronic"),
|
||||
_tagDtoFixture.Create(name: "Electronic"),
|
||||
_tagDtoFixture.Create(name: " ")
|
||||
];
|
||||
|
||||
|
||||
+2
-2
@@ -81,7 +81,7 @@ public class TagEntityMappingTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(entity.Name, result.Value.Name);
|
||||
Assert.Equal("fantasy", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -124,7 +124,7 @@ public class TagEntityMappingTests
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
{
|
||||
Assert.False(resultList[i].IsFailure);
|
||||
Assert.Equal(entities[i].Name, resultList[i].Value.Name);
|
||||
Assert.Equal(entities[i].Name!.ToLowerInvariant(), resultList[i].Value.Name);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+54
@@ -95,6 +95,45 @@ public class SharedReferenceResolverTests
|
||||
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_WhenThereAreNoIncomingEntities_ShouldReturnAnEmptyDictionary()
|
||||
{
|
||||
@@ -137,6 +176,21 @@ public class SharedReferenceResolverTests
|
||||
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()
|
||||
{
|
||||
|
||||
@@ -17,14 +17,14 @@ public class GenreTests
|
||||
private readonly GenreFixture _genreFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidName_ShouldCreateGenreWithTrimmedName()
|
||||
public void Create_WhenCalledWithValidName_ShouldCreateGenreWithTrimmedLowercaseInvariantName()
|
||||
{
|
||||
// Act
|
||||
Result<Genre> result = Genre.Create(" Science Fiction ");
|
||||
Result<Genre> result = Genre.Create(" Science FICTION ");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Science Fiction", result.Value.Name);
|
||||
Assert.Equal("science fiction", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -55,6 +55,20 @@ public class GenreTests
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithNamesDifferingOnlyByCasing_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Genre firstGenre = _genreFixture.Create(name: "Science Fiction");
|
||||
Genre secondGenre = _genreFixture.Create(name: "science fiction");
|
||||
|
||||
// Act
|
||||
bool result = firstGenre.Equals(secondGenre);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentName_ShouldReturnFalse()
|
||||
{
|
||||
@@ -79,6 +93,6 @@ public class GenreTests
|
||||
string result = genre.ToString();
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Science Fiction", result);
|
||||
Assert.Equal("science fiction", result);
|
||||
}
|
||||
}
|
||||
@@ -17,10 +17,10 @@ public class TagTests
|
||||
private readonly TagFixture _tagFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidName_ShouldCreateTagWithTrimmedName()
|
||||
public void Create_WhenCalledWithValidName_ShouldCreateTagWithTrimmedLowercaseInvariantName()
|
||||
{
|
||||
// Act
|
||||
Result<Tag> result = Tag.Create(" bestseller ");
|
||||
Result<Tag> result = Tag.Create(" BeStSeLLeR ");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -55,6 +55,20 @@ public class TagTests
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithNamesDifferingOnlyByCasing_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Tag firstTag = _tagFixture.Create(name: "BestSeller");
|
||||
Tag secondTag = _tagFixture.Create(name: "bestseller");
|
||||
|
||||
// Act
|
||||
bool result = firstTag.Equals(secondTag);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentName_ShouldReturnFalse()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user