mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Implements tests for commit eaca69bf2a
This commit is contained in:
1 parent
94a67aded4
commit
d185c77999
15 files changed
+527
-128
No files matched your search
-55
@@ -1,55 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
}
|
||||
+24
-24
@@ -12,46 +12,46 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
/// <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.
|
||||
// The value objects now store names trimmed and lowercased, so the existing rows must be normalized before new scans start reusing them
|
||||
// by their normalized name. SQLite's built-in lower() folds ASCII letters only, so a legacy name whose uppercase letters are outside
|
||||
// ASCII is not fully folded and is not merged with its lowercase counterpart. 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;
|
||||
SELECT DISTINCT trim(lower(Name)) FROM Tags;
|
||||
|
||||
INSERT OR IGNORE INTO Genres (Name)
|
||||
SELECT DISTINCT lumina_normalize_shared_reference_name(Name) FROM Genres;
|
||||
SELECT DISTINCT trim(lower(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 TrackTags SET TagId = trim(lower(TagId)) WHERE TagId <> trim(lower(TagId));
|
||||
UPDATE OR IGNORE AlbumTags SET TagId = trim(lower(TagId)) WHERE TagId <> trim(lower(TagId));
|
||||
UPDATE OR IGNORE ArtistTags SET TagId = trim(lower(TagId)) WHERE TagId <> trim(lower(TagId));
|
||||
UPDATE OR IGNORE BookTags SET TagId = trim(lower(TagId)) WHERE TagId <> trim(lower(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);
|
||||
UPDATE OR IGNORE TrackGenres SET GenreId = trim(lower(GenreId)) WHERE GenreId <> trim(lower(GenreId));
|
||||
UPDATE OR IGNORE AlbumGenres SET GenreId = trim(lower(GenreId)) WHERE GenreId <> trim(lower(GenreId));
|
||||
UPDATE OR IGNORE ArtistGenres SET GenreId = trim(lower(GenreId)) WHERE GenreId <> trim(lower(GenreId));
|
||||
UPDATE OR IGNORE BookGenres SET GenreId = trim(lower(GenreId)) WHERE GenreId <> trim(lower(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 TrackTags WHERE TagId <> trim(lower(TagId));
|
||||
DELETE FROM AlbumTags WHERE TagId <> trim(lower(TagId));
|
||||
DELETE FROM ArtistTags WHERE TagId <> trim(lower(TagId));
|
||||
DELETE FROM BookTags WHERE TagId <> trim(lower(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 TrackGenres WHERE GenreId <> trim(lower(GenreId));
|
||||
DELETE FROM AlbumGenres WHERE GenreId <> trim(lower(GenreId));
|
||||
DELETE FROM ArtistGenres WHERE GenreId <> trim(lower(GenreId));
|
||||
DELETE FROM BookGenres WHERE GenreId <> trim(lower(GenreId));
|
||||
|
||||
DELETE FROM Tags WHERE Name <> lumina_normalize_shared_reference_name(Name);
|
||||
DELETE FROM Genres WHERE Name <> lumina_normalize_shared_reference_name(Name);
|
||||
DELETE FROM Tags WHERE Name <> trim(lower(Name));
|
||||
DELETE FROM Genres WHERE Name <> trim(lower(Name));
|
||||
""");
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ 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
|
||||
|
||||
@@ -67,16 +66,6 @@ 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>
|
||||
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
}
|
||||
+52
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
@@ -238,6 +240,56 @@ public class AddTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
Assert.EndsWith($"/api/v1/libraries/{_libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackResponse.Id}", locationUri);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddTrack_WhenTwoTracksShareTagAndGenreNamesWithDifferentCasingAndWhitespace_ShouldStoreOneNormalizedRowPerName()
|
||||
{
|
||||
// Arrange
|
||||
(Guid artistId, Guid albumId) = await SeedArtistAndAlbumAsync();
|
||||
string suffix = Guid.NewGuid().ToString("N")[..8];
|
||||
string tagName = $"tag-{suffix}";
|
||||
string genreName = $"genre-{suffix}";
|
||||
AddTrackRequest firstRequest = _addTrackRequestFixture.Create(
|
||||
path: Path.Combine(_libraryContentLocation, $"{Guid.NewGuid():N}.flac"),
|
||||
metadata: _musicTrackMetadataDtoFixture.Create(
|
||||
genres: [_genreDtoFixture.Create(name: $" {genreName.ToUpperInvariant()} ")],
|
||||
tags: [_tagDtoFixture.Create(name: $" {tagName.ToUpperInvariant()} ")]),
|
||||
contributors: []);
|
||||
AddTrackRequest secondRequest = _addTrackRequestFixture.Create(
|
||||
path: Path.Combine(_libraryContentLocation, $"{Guid.NewGuid():N}.flac"),
|
||||
metadata: _musicTrackMetadataDtoFixture.Create(
|
||||
genres: [_genreDtoFixture.Create(name: genreName)],
|
||||
tags: [_tagDtoFixture.Create(name: tagName)]),
|
||||
contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await PostTrackAsync(artistId, albumId, firstRequest);
|
||||
HttpResponseMessage secondResponse = await PostTrackAsync(artistId, albumId, secondRequest);
|
||||
|
||||
// Assert
|
||||
firstResponse.EnsureSuccessStatusCode();
|
||||
secondResponse.EnsureSuccessStatusCode();
|
||||
TrackResponse? firstTrack = await firstResponse.Content.ReadFromJsonAsync<TrackResponse>(_jsonOptions);
|
||||
TrackResponse? secondTrack = await secondResponse.Content.ReadFromJsonAsync<TrackResponse>(_jsonOptions);
|
||||
Assert.NotNull(firstTrack);
|
||||
Assert.NotNull(secondTrack);
|
||||
Assert.Equal(new[] { tagName }, firstTrack!.Metadata.Tags!.Select(tag => tag.Name));
|
||||
Assert.Equal(new[] { genreName }, firstTrack.Metadata.Genres!.Select(genre => genre.Name));
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
// Both spellings must collapse into a single row each, keyed by the normalized name.
|
||||
Assert.Equal(1, await dbContext.Set<TagEntity>().CountAsync(tag => tag.Name == tagName));
|
||||
Assert.Equal(1, await dbContext.Set<GenreEntity>().CountAsync(genre => genre.Name == genreName));
|
||||
|
||||
List<TrackEntity> tracks = [.. dbContext.Tracks
|
||||
.Include(track => track.Tags)
|
||||
.Include(track => track.Genres)
|
||||
.Where(track => track.Id == firstTrack.Id || track.Id == secondTrack!.Id)];
|
||||
Assert.Equal(2, tracks.Count);
|
||||
Assert.All(tracks, track => Assert.Contains(track.Tags, tag => tag.Name == tagName));
|
||||
Assert.All(tracks, track => Assert.Contains(track.Genres, genre => genre.Name == genreName));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddTrack_WhenPathIsMissing_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
|
||||
+50
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
@@ -1751,6 +1752,55 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenTwoBooksShareTagAndGenreNamesWithDifferentCasingAndWhitespace_ShouldStoreOneNormalizedRowPerName()
|
||||
{
|
||||
// Arrange
|
||||
string suffix = Guid.NewGuid().ToString("N")[..8];
|
||||
string tagName = $"horror-{suffix}";
|
||||
string genreName = $"fiction-{suffix}";
|
||||
AddBookRequest firstRequest = _addBookRequestFixture.Create(
|
||||
path: Path.Combine(_libraryContentLocation, $"{Guid.NewGuid():N}.epub"),
|
||||
metadata: _writtenContentMetadataDtoFixture.Create(
|
||||
genres: [_genreDtoFixture.Create(name: $" {genreName.ToUpperInvariant()} ")],
|
||||
tags: [_tagDtoFixture.Create(name: $" {tagName.ToUpperInvariant()} ")]),
|
||||
contributors: []);
|
||||
AddBookRequest secondRequest = _addBookRequestFixture.Create(
|
||||
path: Path.Combine(_libraryContentLocation, $"{Guid.NewGuid():N}.epub"),
|
||||
metadata: _writtenContentMetadataDtoFixture.Create(
|
||||
genres: [_genreDtoFixture.Create(name: genreName)],
|
||||
tags: [_tagDtoFixture.Create(name: tagName)]),
|
||||
contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await PostBookAsync(firstRequest);
|
||||
HttpResponseMessage secondResponse = await PostBookAsync(secondRequest);
|
||||
|
||||
// Assert
|
||||
firstResponse.EnsureSuccessStatusCode();
|
||||
secondResponse.EnsureSuccessStatusCode();
|
||||
BookResponse? firstBook = await firstResponse.Content.ReadFromJsonAsync<BookResponse>(_jsonOptions);
|
||||
BookResponse? secondBook = await secondResponse.Content.ReadFromJsonAsync<BookResponse>(_jsonOptions);
|
||||
Assert.NotNull(firstBook);
|
||||
Assert.NotNull(secondBook);
|
||||
Assert.Equal(new[] { tagName }, firstBook!.Metadata.Tags!.Select(tag => tag.Name));
|
||||
Assert.Equal(new[] { genreName }, firstBook.Metadata.Genres!.Select(genre => genre.Name));
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
// Both spellings must collapse into a single row each, keyed by the normalized name.
|
||||
Assert.Equal(1, await dbContext.Set<TagEntity>().CountAsync(tag => tag.Name == tagName));
|
||||
Assert.Equal(1, await dbContext.Set<GenreEntity>().CountAsync(genre => genre.Name == genreName));
|
||||
|
||||
List<BookEntity> books = [.. dbContext.Books
|
||||
.Include(book => book.Tags)
|
||||
.Include(book => book.Genres)
|
||||
.Where(book => book.Id == firstBook.Id || book.Id == secondBook!.Id)];
|
||||
Assert.Equal(2, books.Count);
|
||||
Assert.All(books, book => Assert.Contains(book.Tags, tag => tag.Name == tagName));
|
||||
Assert.All(books, book => Assert.Contains(book.Genres, genre => genre.Name == genreName));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
|
||||
+58
@@ -1,7 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
@@ -34,9 +37,13 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
private readonly HttpClient _client;
|
||||
private readonly AddTrackRequestFixture _addTrackRequestFixture = new();
|
||||
private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly TagDtoFixture _tagDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
@@ -220,6 +227,57 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tags; --")] // destructive injection in a tag and genre name
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection in a tag and genre name
|
||||
public async Task AddTrack_WithSQLInjectionInTagAndGenreNames_ShouldNotCorruptOrLeakData(string maliciousName)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
|
||||
string suffix = Guid.NewGuid().ToString("N")[..8];
|
||||
string seededTagName = $"seeded-tag-{suffix}";
|
||||
string seededGenreName = $"seeded-genre-{suffix}";
|
||||
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
seedDbContext.Set<TagEntity>().Add(_tagEntityFixture.Create(name: seededTagName));
|
||||
seedDbContext.Set<GenreEntity>().Add(_genreEntityFixture.Create(name: seededGenreName));
|
||||
await seedDbContext.SaveChangesAsync();
|
||||
}
|
||||
string injectedTagName = $"{maliciousName} {suffix}";
|
||||
string injectedGenreName = $"{maliciousName} genre {suffix}";
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create(
|
||||
path: Path.Combine(_libraryContentLocation, $"{Guid.NewGuid():N}.flac"),
|
||||
metadata: _musicTrackMetadataDtoFixture.Create(
|
||||
genres: [_genreDtoFixture.Create(name: injectedGenreName)],
|
||||
tags: [_tagDtoFixture.Create(name: injectedTagName)]),
|
||||
contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The malicious names are user data, not SQL: they must be stored verbatim (normalized) without breaking the request or the schema.
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("StackTrace", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.Libraries.CountAsync(library => library.Id == libraryId));
|
||||
Assert.Equal(1, await dbContext.Tracks.CountAsync(track => track.LibraryId == libraryId));
|
||||
Assert.True(await dbContext.Set<TagEntity>().AnyAsync(tag => tag.Name == seededTagName));
|
||||
Assert.True(await dbContext.Set<GenreEntity>().AnyAsync(genre => genre.Name == seededGenreName));
|
||||
Assert.True(await dbContext.Set<TagEntity>().AnyAsync(tag => tag.Name == injectedTagName.ToLowerInvariant()));
|
||||
Assert.True(await dbContext.Set<GenreEntity>().AnyAsync(genre => genre.Name == injectedGenreName.ToLowerInvariant()));
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
|
||||
+69
@@ -1,6 +1,9 @@
|
||||
#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.Management;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
@@ -33,7 +36,11 @@ public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
private readonly HttpClient _client;
|
||||
private readonly AddBookRequestFixture _addBookRequestFixture = new();
|
||||
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly TagDtoFixture _tagDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -176,6 +183,68 @@ public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tags; --")] // destructive injection in a tag and genre name
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection in a tag and genre name
|
||||
public async Task AddBook_WithSQLInjectionInTagAndGenreNames_ShouldNotCorruptOrLeakData(string maliciousName)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string contentLocation = Path.GetTempPath();
|
||||
string suffix = Guid.NewGuid().ToString("N")[..8];
|
||||
string seededTagName = $"seeded-tag-{suffix}";
|
||||
string seededGenreName = $"seeded-genre-{suffix}";
|
||||
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
seedDbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [contentLocation]));
|
||||
seedDbContext.Set<TagEntity>().Add(_tagEntityFixture.Create(name: seededTagName));
|
||||
seedDbContext.Set<GenreEntity>().Add(_genreEntityFixture.Create(name: seededGenreName));
|
||||
await seedDbContext.SaveChangesAsync();
|
||||
}
|
||||
string injectedTagName = $"{maliciousName} {suffix}";
|
||||
string injectedGenreName = $"{maliciousName} genre {suffix}";
|
||||
AddBookRequest request = _addBookRequestFixture.Create(
|
||||
path: Path.Combine(contentLocation, $"{Guid.NewGuid()}.epub"),
|
||||
metadata: _writtenContentMetadataDtoFixture.Create(
|
||||
genres: [_genreDtoFixture.Create(name: injectedGenreName)],
|
||||
tags: [_tagDtoFixture.Create(name: injectedTagName)]),
|
||||
contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The malicious names are user data, not SQL: they must be stored verbatim (normalized) without breaking the request or the schema.
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("StackTrace", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.Libraries.CountAsync(library => library.Id == libraryId));
|
||||
Assert.Equal(1, await dbContext.Books.CountAsync(book => book.LibraryId == libraryId));
|
||||
// The join rows must still exist and point at the normalized tag and genre that the request supplied.
|
||||
BookEntity storedBook = await dbContext.Books
|
||||
.Include(book => book.Tags)
|
||||
.Include(book => book.Genres)
|
||||
.SingleAsync(book => book.LibraryId == libraryId);
|
||||
Assert.Equal(injectedTagName.ToLowerInvariant(), Assert.Single(storedBook.Tags).Name);
|
||||
Assert.Equal(injectedGenreName.ToLowerInvariant(), Assert.Single(storedBook.Genres).Name);
|
||||
Assert.True(await dbContext.Set<TagEntity>().AnyAsync(tag => tag.Name == seededTagName));
|
||||
Assert.True(await dbContext.Set<GenreEntity>().AnyAsync(genre => genre.Name == seededGenreName));
|
||||
Assert.True(await dbContext.Set<TagEntity>().AnyAsync(tag => tag.Name == injectedTagName.ToLowerInvariant()));
|
||||
Assert.True(await dbContext.Set<GenreEntity>().AnyAsync(genre => genre.Name == injectedGenreName.ToLowerInvariant()));
|
||||
}
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Books; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
|
||||
+15
@@ -53,6 +53,21 @@ public class GenreDtoMappingTests
|
||||
Assert.Equal(name.ToLowerInvariant(), result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainValueObject_WhenGenreNameHasSurroundingWhitespaceAndMixedCase_ShouldStoreTheTrimmedLowercaseInvariantName()
|
||||
{
|
||||
// Arrange
|
||||
GenreDto genreDto = _genreDtoFixture.Create(name: " ÉLECTRO ");
|
||||
|
||||
// Act
|
||||
Result<Genre> result = genreDto.ToDomainValueObject();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal("électro", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
|
||||
+15
@@ -84,6 +84,21 @@ public class GenreEntityMappingTests
|
||||
Assert.Equal("fiction", result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainValueObject_WhenGenreNameHasSurroundingWhitespaceAndMixedCase_ShouldStoreTheTrimmedLowercaseInvariantName()
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity entity = _genreEntityFixture.Create(name: " ÉLECTRO ");
|
||||
|
||||
// Act
|
||||
Result<Genre> result = entity.ToDomainValueObject();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal("électro", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
|
||||
+15
@@ -54,6 +54,21 @@ public class TagDtoMappingTests
|
||||
Assert.Equal(name.ToLowerInvariant(), result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainValueObject_WhenTagNameHasSurroundingWhitespaceAndMixedCase_ShouldStoreTheTrimmedLowercaseInvariantName()
|
||||
{
|
||||
// Arrange
|
||||
TagDto tagDto = _tagDtoFixture.Create(name: " InDiE ");
|
||||
|
||||
// Act
|
||||
Result<Tag> result = tagDto.ToDomainValueObject();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal("indie", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
|
||||
+15
@@ -84,6 +84,21 @@ public class TagEntityMappingTests
|
||||
Assert.Equal("fantasy", result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainValueObject_WhenTagNameHasSurroundingWhitespaceAndMixedCase_ShouldStoreTheTrimmedLowercaseInvariantName()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity entity = _tagEntityFixture.Create(name: " InDiE ");
|
||||
|
||||
// Act
|
||||
Result<Tag> result = entity.ToDomainValueObject();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal("indie", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
|
||||
+130
@@ -134,6 +134,136 @@ public class SharedReferenceResolverTests
|
||||
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()
|
||||
{
|
||||
|
||||
@@ -4,6 +4,7 @@ using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata;
|
||||
@@ -27,6 +28,47 @@ public class GenreTests
|
||||
Assert.Equal("science fiction", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(" Science FICTION ", "science fiction")] // ASCII mixed case with surrounding whitespace
|
||||
[InlineData("ÉLECTRO", "électro")] // non-ASCII Latin uppercase
|
||||
[InlineData("ЖАНР", "жанр")] // non-Latin uppercase
|
||||
[InlineData(" indie ", "indie")] // surrounding whitespace
|
||||
public void Create_WhenNameHasMixedCaseOrSurroundingWhitespace_ShouldNormalizeIt(string name, string expectedName)
|
||||
{
|
||||
// Act
|
||||
Result<Genre> result = Genre.Create(name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedName, result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCurrentCultureIsTurkish_ShouldLowercaseWithTheInvariantCulture()
|
||||
{
|
||||
CultureInfo originalCulture = CultureInfo.CurrentCulture;
|
||||
CultureInfo originalUiCulture = CultureInfo.CurrentUICulture;
|
||||
try
|
||||
{
|
||||
// Arrange
|
||||
CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
|
||||
CultureInfo.CurrentUICulture = new CultureInfo("tr-TR");
|
||||
|
||||
// Act
|
||||
Result<Genre> result = Genre.Create("INDIE");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
// The Turkish culture maps an uppercase I to a dotless lowercase i, so this proves the invariant culture is used.
|
||||
Assert.Equal("indie", result.Value.Name);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CultureInfo.CurrentCulture = originalCulture;
|
||||
CultureInfo.CurrentUICulture = originalUiCulture;
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // null name
|
||||
[InlineData("")] // empty name
|
||||
|
||||
@@ -4,6 +4,7 @@ using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata;
|
||||
@@ -27,6 +28,47 @@ public class TagTests
|
||||
Assert.Equal("bestseller", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(" BeStSeLLeR ", "bestseller")] // ASCII mixed case with surrounding whitespace
|
||||
[InlineData("ÉLECTRO", "électro")] // non-ASCII Latin uppercase
|
||||
[InlineData("ЖАНР", "жанр")] // non-Latin uppercase
|
||||
[InlineData(" indie ", "indie")] // surrounding whitespace
|
||||
public void Create_WhenNameHasMixedCaseOrSurroundingWhitespace_ShouldNormalizeIt(string name, string expectedName)
|
||||
{
|
||||
// Act
|
||||
Result<Tag> result = Tag.Create(name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedName, result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCurrentCultureIsTurkish_ShouldLowercaseWithTheInvariantCulture()
|
||||
{
|
||||
CultureInfo originalCulture = CultureInfo.CurrentCulture;
|
||||
CultureInfo originalUiCulture = CultureInfo.CurrentUICulture;
|
||||
try
|
||||
{
|
||||
// Arrange
|
||||
CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
|
||||
CultureInfo.CurrentUICulture = new CultureInfo("tr-TR");
|
||||
|
||||
// Act
|
||||
Result<Tag> result = Tag.Create("INDIE");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
// The Turkish culture maps an uppercase I to a dotless lowercase i, so this proves the invariant culture is used.
|
||||
Assert.Equal("indie", result.Value.Name);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CultureInfo.CurrentCulture = originalCulture;
|
||||
CultureInfo.CurrentUICulture = originalUiCulture;
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // null name
|
||||
[InlineData("")] // empty name
|
||||
|
||||
Reference in new issue
Block a user