Renames project paths from Lumina to Nemera

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

No files matched your search

@@ -0,0 +1,98 @@
#region ========================================================================= USING =====================================================================================
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.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Authorization;
/// <summary>
/// Contains integration tests for the <see cref="RoleRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class RoleRepositoryTests
{
private readonly RoleEntityFixture _roleEntityFixture = new();
private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new();
private readonly PermissionEntityFixture _permissionEntityFixture = new();
[Fact]
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-rolerepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
RoleRepository sut = new(context);
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
Guid storedCreatedBy = Guid.NewGuid();
RoleEntity storedRole = _roleEntityFixture.Create(roleName: "Admin", createdOnUtc: storedCreatedOnUtc, createdBy: storedCreatedBy);
context.Roles.Add(storedRole);
await context.SaveChangesAsync();
RoleEntity updatedRole = _roleEntityFixture.Create(id: storedRole.Id, roleName: "SuperAdmin", createdOnUtc: DateTime.UtcNow.AddYears(-10), createdBy: Guid.NewGuid());
updatedRole.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5);
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);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
RoleEntity reloadedRole = await context.Roles.AsNoTracking().FirstAsync(role => role.Id == storedRole.Id);
Assert.Equal("SuperAdmin", reloadedRole.RoleName);
Assert.Equal(storedCreatedOnUtc, reloadedRole.CreatedOnUtc);
Assert.Equal(storedCreatedBy, reloadedRole.CreatedBy);
Assert.Null(reloadedRole.UpdatedOnUtc);
Assert.Null(reloadedRole.UpdatedBy);
}
[Fact]
public async Task UpdateAsync_WhenNothingChanged_ShouldNotDuplicateThePermissions()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-rolerepo-permissions-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
RoleRepository sut = new(context);
PermissionEntity firstPermission = _permissionEntityFixture.Create();
PermissionEntity secondPermission = _permissionEntityFixture.Create();
RoleEntity storedRole = _roleEntityFixture.Create(roleName: $"perm-role-{Guid.NewGuid():N}");
context.Permissions.AddRange(firstPermission, secondPermission);
context.Roles.Add(storedRole);
await context.SaveChangesAsync();
storedRole.RolePermissions.Add(_rolePermissionEntityFixture.Create(role: storedRole, permission: firstPermission));
storedRole.RolePermissions.Add(_rolePermissionEntityFixture.Create(role: storedRole, permission: secondPermission));
await context.SaveChangesAsync();
// Detach the seeded role, so that the update must load it through its include chain instead of returning the already populated seeded instance.
context.ChangeTracker.Clear();
RoleEntity incoming = await context.Roles.AsNoTracking().Include(candidate => candidate.RolePermissions).FirstAsync(candidate => candidate.Id == storedRole.Id);
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
RoleEntity? reloadedRole = await context.Roles.AsNoTracking().Include(candidate => candidate.RolePermissions).FirstOrDefaultAsync(candidate => candidate.Id == storedRole.Id);
Assert.NotNull(reloadedRole);
Assert.Equal(2, reloadedRole!.RolePermissions.Count);
}
}
@@ -0,0 +1,861 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
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.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Common.Interceptors;
using Lumina.DataAccess.Core.Repositories.BookLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
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.IntegrationTests.Core.Repositories.BookLibrary;
/// <summary>
/// Contains integration tests for the <see cref="BookRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookRepositoryTests
{
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
private readonly BookRatingEntityFixture _bookRatingEntityFixture = new();
private readonly IsbnEntityFixture _isbnEntityFixture = new();
private readonly TagEntityFixture _tagEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
[Fact]
public async Task ResetEnrichmentStateForPathsAsync_WhenCalled_ShouldResetTheMetadataAndArtworkStatusesForThePaths()
{
// Arrange
// The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used.
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity changedBook = _bookEntityFixture.Create();
changedBook.LibraryId = libraryId;
changedBook.Path = "/books/changed.epub";
changedBook.MetadataStatus = MetadataStatus.Enriched;
changedBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: changedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
BookEntity unchangedBook = _bookEntityFixture.Create();
unchangedBook.LibraryId = libraryId;
unchangedBook.Path = "/books/unchanged.epub";
unchangedBook.MetadataStatus = MetadataStatus.Enriched;
unchangedBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
context.Books.AddRange(changedBook, unchangedBook);
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.ResetEnrichmentStateForPathsAsync(libraryId, ["/books/changed.epub"], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
BookEntity? resetBook = await context.Books.AsNoTracking().Include(book => book.Artwork).FirstOrDefaultAsync(book => book.Id == changedBook.Id);
Assert.NotNull(resetBook);
Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus);
Assert.Equal(ArtworkStatus.Pending, resetBook.Artwork.Single().Status);
BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == unchangedBook.Id);
Assert.NotNull(keptBook);
Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus);
}
[Fact]
public async Task GetExistingPathsAsync_WhenMorePathsAreRequestedThanTheStorageAccepts_ShouldReturnTheExistingPaths()
{
// Arrange
// A scan of a very large library stages more paths than SQLite accepts as the parameters of one statement, which used to fail the whole scan.
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-existingpaths-large-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create();
book.LibraryId = libraryId;
book.Path = "/books/tolkien/the-hobbit.epub";
context.Books.Add(book);
await context.SaveChangesAsync();
List<string> requestedPaths = [.. Enumerable.Range(0, 120_000).Select(index => $"/books/tolkien/book-{index}.epub")];
requestedPaths.Add("/books/tolkien/the-hobbit.epub");
// Act
Result<IReadOnlyCollection<string>> result = await sut.GetExistingPathsAsync(libraryId, requestedPaths, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
string existingPath = Assert.Single(result.Value);
Assert.Equal("/books/tolkien/the-hobbit.epub", existingPath);
}
[Fact]
public async Task ResetMetadataStatusForLibraryAsync_WhenCalled_ShouldResetTheMetadataStatusOfAllBooksOfTheLibrary()
{
// Arrange
// The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used.
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity enrichedBook = _bookEntityFixture.Create();
enrichedBook.LibraryId = libraryId;
enrichedBook.MetadataStatus = MetadataStatus.Enriched;
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Enriched;
context.Books.AddRange(enrichedBook, bookOfAnotherLibrary);
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.ResetMetadataStatusForLibraryAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
BookEntity? resetBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == enrichedBook.Id);
Assert.NotNull(resetBook);
Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus);
BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == bookOfAnotherLibrary.Id);
Assert.NotNull(keptBook);
Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus);
}
[Fact]
public async Task ResetArtworkStatusForLibraryAsync_WhenCalled_ShouldResetTheArtworkStatusOfTheLibraryBooks()
{
// Arrange
// The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used.
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create();
book.LibraryId = libraryId;
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookOfAnotherLibrary.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
context.Books.AddRange(book, bookOfAnotherLibrary);
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.ResetArtworkStatusForLibraryAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
BookArtworkEntity? resetArtwork = await context.Set<BookArtworkEntity>().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == book.Id);
Assert.NotNull(resetArtwork);
Assert.Equal(ArtworkStatus.Pending, resetArtwork!.Status);
BookArtworkEntity? keptArtwork = await context.Set<BookArtworkEntity>().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == bookOfAnotherLibrary.Id);
Assert.NotNull(keptArtwork);
Assert.Equal(ArtworkStatus.Enriched, keptArtwork!.Status);
}
[Fact]
public async Task InsertAsync_WhenCalledWithAValidBook_ShouldPersistTheBook()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create();
// Act
Result<Created> result = await sut.InsertAsync(book, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
BookEntity? storedBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == book.Id);
Assert.NotNull(storedBook);
Assert.Equal(book.Path, storedBook!.Path);
Assert.Equal(book.Title, storedBook.Title);
}
[Fact]
public async Task InsertAsync_WhenAnotherBookOfTheSameLibraryHasTheSamePath_ShouldReturnBookAlreadyExists()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity existingBook = _bookEntityFixture.Create();
existingBook.LibraryId = libraryId;
existingBook.Path = "/books/existing.epub";
context.Books.Add(existingBook);
await context.SaveChangesAsync();
BookEntity book = _bookEntityFixture.Create();
book.LibraryId = libraryId;
book.Path = "/books/existing.epub";
// Act
Result<Created> result = await sut.InsertAsync(book, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeAnyAuditColumn()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)];
book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)];
book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13)];
context.Books.Add(book);
await context.SaveChangesAsync();
Guid contributorId = book.Contributors[0].Id;
DateTime contributorCreatedOnUtc = book.Contributors[0].CreatedOnUtc;
BookEntity incoming = await LoadDetachedBookAsync(context, book.Id);
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
BookEntity? storedBook = await context.Books.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == book.Id);
Assert.NotNull(storedBook);
Assert.Null(storedBook!.UpdatedOnUtc);
BookContributorEntity storedContributor = Assert.Single(storedBook.Contributors);
Assert.Equal(contributorId, storedContributor.Id);
Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc);
}
[Fact]
public async Task UpdateAsync_WhenOnlyTheMetadataChanged_ShouldStampTheBookAndKeepTheChildRowsUntouched()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-metadata-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)];
book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)];
book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13)];
context.Books.Add(book);
await context.SaveChangesAsync();
Guid contributorId = book.Contributors[0].Id;
DateTime contributorCreatedOnUtc = book.Contributors[0].CreatedOnUtc;
BookEntity incoming = await LoadDetachedBookAsync(context, book.Id);
incoming.Title = "A brand new title";
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
BookEntity? storedBook = await context.Books.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == book.Id);
Assert.NotNull(storedBook);
Assert.Equal("A brand new title", storedBook!.Title);
Assert.Equal(utcNow, storedBook.UpdatedOnUtc);
Assert.Equal(userId, storedBook.UpdatedBy);
BookContributorEntity storedContributor = Assert.Single(storedBook.Contributors);
Assert.Equal(contributorId, storedContributor.Id);
Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc);
}
[Fact]
public async Task UpdateAsync_WhenAContributorIsRemoved_ShouldDeleteOnlyThatParticipationAndKeepTheOtherIdentity()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-removecontributor-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
Guid keptMediaContributorId = Guid.NewGuid();
BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId);
BookContributorEntity removedContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid());
book.Contributors = [keptContributor, removedContributor];
context.Books.Add(book);
await context.SaveChangesAsync();
Guid keptContributorId = keptContributor.Id;
BookEntity incoming = await LoadDetachedBookAsync(context, book.Id);
incoming.Contributors = [incoming.Contributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId)];
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
List<BookContributorEntity> storedContributors = await context.Set<BookContributorEntity>().AsNoTracking().Where(contributor => contributor.BookId == book.Id).ToListAsync();
BookContributorEntity storedContributor = Assert.Single(storedContributors);
Assert.Equal(keptContributorId, storedContributor.Id);
Assert.Equal(keptMediaContributorId, storedContributor.MediaContributorId);
}
[Fact]
public async Task UpdateAsync_WhenAContributorIsAdded_ShouldInsertOnlyTheNewParticipationAndKeepTheExistingIdentity()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-addcontributor-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
Guid keptMediaContributorId = Guid.NewGuid();
BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId);
book.Contributors = [keptContributor];
context.Books.Add(book);
await context.SaveChangesAsync();
Guid keptContributorId = keptContributor.Id;
BookEntity incoming = await LoadDetachedBookAsync(context, book.Id);
Guid addedMediaContributorId = Guid.NewGuid();
incoming.Contributors.Add(_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: addedMediaContributorId));
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
List<BookContributorEntity> storedContributors = await context.Set<BookContributorEntity>().AsNoTracking().Where(contributor => contributor.BookId == book.Id).ToListAsync();
Assert.Equal(2, storedContributors.Count);
Assert.Equal(keptContributorId, storedContributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId).Id);
Assert.Contains(storedContributors, contributor => contributor.MediaContributorId == addedMediaContributorId);
}
[Fact]
public async Task UpdateAsync_WhenNothingChanged_ShouldNotDuplicateAnyReconciledChildCollection()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-noop-collections-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Tags = [_tagEntityFixture.Create(name: $"noop-book-tag-{Guid.NewGuid():N}"), _tagEntityFixture.Create(name: $"noop-book-tag-two-{Guid.NewGuid():N}")];
book.Genres = [_genreEntityFixture.Create(name: $"noop-book-genre-{Guid.NewGuid():N}"), _genreEntityFixture.Create(name: $"noop-book-genre-two-{Guid.NewGuid():N}")];
book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13), _isbnEntityFixture.Create(value: "9780261102693", format: IsbnFormat.Isbn13)];
book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks), _bookRatingEntityFixture.Create(source: BookRatingSource.Goodreads)];
book.Contributors =
[
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid()),
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid())
];
context.Books.Add(book);
await context.SaveChangesAsync();
// Detach the seeded graph, so that the update must load the tracked book through its include chain instead of returning the already populated seeded instance.
context.ChangeTracker.Clear();
BookEntity incoming = await LoadDetachedBookAsync(context, book.Id);
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
BookEntity? storedBook = await context.Books
.AsNoTracking()
.Include(candidate => candidate.Tags)
.Include(candidate => candidate.Genres)
.Include(candidate => candidate.ISBNs)
.Include(candidate => candidate.Ratings)
.Include(candidate => candidate.Contributors)
.FirstOrDefaultAsync(candidate => candidate.Id == book.Id);
Assert.NotNull(storedBook);
Assert.Equal(2, storedBook!.Tags.Count);
Assert.Equal(2, storedBook.Genres.Count);
Assert.Equal(2, storedBook.ISBNs.Count);
Assert.Equal(2, storedBook.Ratings.Count);
Assert.Equal(2, storedBook.Contributors.Count);
}
[Fact]
public async Task UpdateAsync_WhenOneItemIsRemovedFromEachReconciledChildCollection_ShouldRemoveOnlyThoseItems()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-remove-collections-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
string keptTagName = $"remove-book-tag-{Guid.NewGuid():N}";
string keptGenreName = $"remove-book-genre-{Guid.NewGuid():N}";
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Tags = [_tagEntityFixture.Create(name: keptTagName), _tagEntityFixture.Create(name: $"remove-book-tag-two-{Guid.NewGuid():N}")];
book.Genres = [_genreEntityFixture.Create(name: keptGenreName), _genreEntityFixture.Create(name: $"remove-book-genre-two-{Guid.NewGuid():N}")];
book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13), _isbnEntityFixture.Create(value: "9780261102693", format: IsbnFormat.Isbn13)];
book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks), _bookRatingEntityFixture.Create(source: BookRatingSource.Goodreads)];
BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid());
book.Contributors = [keptContributor, _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid())];
context.Books.Add(book);
await context.SaveChangesAsync();
// Detach the seeded graph, so that the update must load the tracked book through its include chain instead of returning the already populated seeded instance.
context.ChangeTracker.Clear();
BookEntity incoming = await LoadDetachedBookAsync(context, book.Id);
incoming.Tags = [incoming.Tags.Single(tag => tag.Name == keptTagName)];
incoming.Genres = [incoming.Genres.Single(genre => genre.Name == keptGenreName)];
incoming.ISBNs = [incoming.ISBNs.Single(isbn => isbn.Value == "9783161484100")];
incoming.Ratings = [incoming.Ratings.Single(rating => rating.Source == BookRatingSource.GoogleBooks)];
incoming.Contributors = [incoming.Contributors.Single(contributor => contributor.Id == keptContributor.Id)];
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
BookEntity? storedBook = await context.Books
.AsNoTracking()
.Include(candidate => candidate.Tags)
.Include(candidate => candidate.Genres)
.Include(candidate => candidate.ISBNs)
.Include(candidate => candidate.Ratings)
.Include(candidate => candidate.Contributors)
.FirstOrDefaultAsync(candidate => candidate.Id == book.Id);
Assert.NotNull(storedBook);
Assert.Equal(keptTagName, Assert.Single(storedBook!.Tags).Name);
Assert.Equal(keptGenreName, Assert.Single(storedBook.Genres).Name);
Assert.Equal("9783161484100", Assert.Single(storedBook.ISBNs).Value);
Assert.Equal(BookRatingSource.GoogleBooks, Assert.Single(storedBook.Ratings).Source);
Assert.Equal(keptContributor.Id, Assert.Single(storedBook.Contributors).Id);
}
[Fact]
public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldDeleteOnlyThatLibrariesBooks()
{
// Arrange
// The delete uses ExecuteDeleteAsync, which is not supported by the in-memory provider, so a real SQLite database is used.
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-deletebylibrary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity bookOfLibrary = _bookEntityFixture.Create();
bookOfLibrary.LibraryId = libraryId;
bookOfLibrary.Path = "/books/library.epub";
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.Path = "/books/other.epub";
context.Books.AddRange(bookOfLibrary, bookOfAnotherLibrary);
await context.SaveChangesAsync();
// Act
Result<Deleted> result = await sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
context.ChangeTracker.Clear();
BookEntity survivor = Assert.Single(await context.Books.AsNoTracking().ToListAsync());
Assert.Equal(bookOfAnotherLibrary.Id, survivor.Id);
}
[Fact]
public async Task GetByIdsAsync_WhenIdsIsEmpty_ShouldReturnAnEmptyList()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
context.Books.Add(_bookEntityFixture.Create(includeMetadata: false));
await context.SaveChangesAsync();
// Act
Result<IReadOnlyList<BookEntity>> result = await sut.GetByIdsAsync([], false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetByIdsAsync_WhenCalled_ShouldReturnOnlyTheRequestedBooks()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity firstBook = _bookEntityFixture.Create(includeMetadata: false);
BookEntity secondBook = _bookEntityFixture.Create(includeMetadata: false);
BookEntity thirdBook = _bookEntityFixture.Create(includeMetadata: false);
context.Books.AddRange(firstBook, secondBook, thirdBook);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
Result<IReadOnlyList<BookEntity>> result = await sut.GetByIdsAsync([firstBook.Id, thirdBook.Id], false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Contains(result.Value, book => book.Id == firstBook.Id);
Assert.Contains(result.Value, book => book.Id == thirdBook.Id);
Assert.DoesNotContain(result.Value, book => book.Id == secondBook.Id);
}
[Fact]
public async Task GetByIdsAsync_WhenNavigationPropertiesShouldNotBeIncluded_ShouldNotLoadTheRelatedCollections()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Tags = [_tagEntityFixture.Create(name: "HiddenTag")];
book.Genres = [_genreEntityFixture.Create(name: "HiddenGenre")];
book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13)];
book.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)];
book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: author.Id, role: MediaContributorRole.Author)];
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
context.Books.Add(book);
context.MediaContributors.Add(author);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
Result<IReadOnlyList<BookEntity>> result = await sut.GetByIdsAsync([book.Id], false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
BookEntity returnedBook = Assert.Single(result.Value);
Assert.Equal(book.Id, returnedBook.Id);
Assert.Empty(returnedBook.Tags);
Assert.Empty(returnedBook.Genres);
Assert.Empty(returnedBook.Contributors);
Assert.Empty(returnedBook.Artwork);
// ISBNs and Ratings are owned collections, so EF Core materializes them together with the book even when the optional graph is not
// included. The flag only controls the non-owned navigation properties, which is why those are asserted empty above.
Assert.Single(returnedBook.ISBNs);
Assert.Single(returnedBook.Ratings);
// The rows are read without tracking, so the read statistics never leak into the unit of work.
Assert.Empty(context.ChangeTracker.Entries<BookEntity>());
Assert.Equal(EntityState.Detached, context.Entry(returnedBook).State);
}
[Fact]
public async Task GetByIdsAsync_WhenNavigationPropertiesShouldBeIncluded_ShouldLoadTheRelatedCollections()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-include-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Tags = [_tagEntityFixture.Create(name: "LoadedTag"), _tagEntityFixture.Create(name: "SecondLoadedTag")];
book.Genres = [_genreEntityFixture.Create(name: "LoadedGenre")];
book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13)];
book.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)];
book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: author.Id, role: MediaContributorRole.Author)];
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched, fileName: "cover.jpg")];
context.Books.Add(book);
context.MediaContributors.Add(author);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
Result<IReadOnlyList<BookEntity>> result = await sut.GetByIdsAsync([book.Id], true, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
BookEntity returnedBook = Assert.Single(result.Value);
Assert.Equal(2, returnedBook.Tags.Count);
Assert.Single(returnedBook.Genres);
Assert.Equal("9783161484100", Assert.Single(returnedBook.ISBNs).Value);
Assert.Equal(4.5M, Assert.Single(returnedBook.Ratings).Value);
Assert.Equal(author.Id, Assert.Single(returnedBook.Contributors).MediaContributorId);
Assert.Equal("cover.jpg", Assert.Single(returnedBook.Artwork).FileName);
}
[Fact]
public async Task GetByIdsAsync_WhenExactlyFiveHundredIdsAreRequested_ShouldReturnEveryBook()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-boundary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
const int BOOK_COUNT = 500;
List<BookEntity> books = CreateBooks(BOOK_COUNT);
context.Books.AddRange(books);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
// A single full chunk proves the boundary does not drop the last chunk.
Result<IReadOnlyList<BookEntity>> result = await sut.GetByIdsAsync([.. books.Select(book => book.Id)], false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(BOOK_COUNT, result.Value.Count);
Assert.Equal(
books.Select(book => book.Id).OrderBy(id => id),
result.Value.Select(book => book.Id).OrderBy(id => id));
}
[Fact]
public async Task GetByIdsAsync_WhenMoreThanFiveHundredIdsAreRequested_ShouldReturnEveryBook()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
const int BOOK_COUNT = 501;
List<BookEntity> books = CreateBooks(BOOK_COUNT);
context.Books.AddRange(books);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
// The lookup is chunked in batches of 500, so the 501st Id proves the second chunk is queried as well.
Result<IReadOnlyList<BookEntity>> result = await sut.GetByIdsAsync([.. books.Select(book => book.Id)], false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(BOOK_COUNT, result.Value.Count);
Assert.Equal(
books.Select(book => book.Id).OrderBy(id => id),
result.Value.Select(book => book.Id).OrderBy(id => id));
}
[Fact]
public async Task GetAuthorsDisplayNamesByBookIdsAsync_WhenBookHasMultipleAuthors_ShouldReturnTheMinimumAuthorDisplayName()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-min-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
MediaContributorEntity firstAuthor = _mediaContributorEntityFixture.Create(displayName: "Zoe Author");
MediaContributorEntity secondAuthor = _mediaContributorEntityFixture.Create(displayName: "Alice Author");
MediaContributorEntity translator = _mediaContributorEntityFixture.Create(displayName: "Aaron Translator");
context.Books.Add(book);
context.MediaContributors.AddRange(firstAuthor, secondAuthor, translator);
await context.SaveChangesAsync();
context.BookContributors.AddRange(
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: firstAuthor.Id, role: MediaContributorRole.Author),
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: secondAuthor.Id, role: MediaContributorRole.Author),
// The translator sorts before every author, so the result would change if a non-Author role were included.
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: translator.Id, role: MediaContributorRole.Translator));
await context.SaveChangesAsync();
// Act
Result<IReadOnlyDictionary<Guid, string?>> result = await sut.GetAuthorsDisplayNamesByBookIdsAsync([book.Id], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Alice Author", result.Value[book.Id]);
}
[Fact]
public async Task GetAuthorsDisplayNamesByBookIdsAsync_WhenABookIsNotRequested_ShouldNotReturnIt()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-requested-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity requestedBook = _bookEntityFixture.Create(includeMetadata: false);
BookEntity bookNotRequested = _bookEntityFixture.Create(includeMetadata: false);
MediaContributorEntity requestedAuthor = _mediaContributorEntityFixture.Create(displayName: "Requested Author");
MediaContributorEntity otherAuthor = _mediaContributorEntityFixture.Create(displayName: "Other Author");
context.Books.AddRange(requestedBook, bookNotRequested);
context.MediaContributors.AddRange(requestedAuthor, otherAuthor);
await context.SaveChangesAsync();
context.BookContributors.AddRange(
_bookContributorEntityFixture.Create(bookId: requestedBook.Id, mediaContributorId: requestedAuthor.Id, role: MediaContributorRole.Author),
_bookContributorEntityFixture.Create(bookId: bookNotRequested.Id, mediaContributorId: otherAuthor.Id, role: MediaContributorRole.Author));
await context.SaveChangesAsync();
// Act
Result<IReadOnlyDictionary<Guid, string?>> result = await sut.GetAuthorsDisplayNamesByBookIdsAsync([requestedBook.Id], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Requested Author", result.Value[requestedBook.Id]);
Assert.DoesNotContain(bookNotRequested.Id, result.Value.Keys);
}
[Fact]
public async Task GetAuthorsDisplayNamesByBookIdsAsync_WhenBookIdsIsEmpty_ShouldReturnAnEmptyDictionary()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
MediaContributorEntity author = _mediaContributorEntityFixture.Create();
context.Books.Add(book);
context.MediaContributors.Add(author);
await context.SaveChangesAsync();
context.BookContributors.Add(
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: author.Id, role: MediaContributorRole.Author));
await context.SaveChangesAsync();
// Act
Result<IReadOnlyDictionary<Guid, string?>> result = await sut.GetAuthorsDisplayNamesByBookIdsAsync([], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetAuthorsDisplayNamesByBookIdsAsync_WhenMoreThanFiveHundredIdsAreRequested_ShouldReturnTheAuthorOfEveryRequestedBook()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
const int BOOK_COUNT = 501;
List<BookEntity> books = CreateBooks(BOOK_COUNT);
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Shared Author");
context.Books.AddRange(books);
context.MediaContributors.Add(author);
await context.SaveChangesAsync();
context.BookContributors.AddRange([.. books.Select(book =>
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: author.Id, role: MediaContributorRole.Author))]);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
// The lookup is chunked in batches of 500, so the 501st book proves the second chunk is queried as well.
Result<IReadOnlyDictionary<Guid, string?>> result = await sut.GetAuthorsDisplayNamesByBookIdsAsync(
[.. books.Select(book => book.Id)], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(BOOK_COUNT, result.Value.Count);
Assert.All(result.Value.Keys, bookId => Assert.Equal("Shared Author", result.Value[bookId]));
}
/// <summary>
/// Creates a list of books with distinct paths and empty metadata collections, so that the chunked lookups can be exercised without extra graph data.
/// </summary>
/// <param name="count">The number of books to create.</param>
/// <returns>The created books.</returns>
private List<BookEntity> CreateBooks(int count)
{
return [.. Enumerable.Range(0, count).Select(_ => _bookEntityFixture.Create(
path: $"/books/generated-{Guid.NewGuid():N}.epub", includeMetadata: false))];
}
/// <summary>
/// Creates a real SQLite backed context, so that the stored values are read exactly as they were written.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateContext(SqliteConnection anchorConnection)
{
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.Options);
context.Database.EnsureCreated();
return context;
}
/// <summary>
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <param name="userId">The Id of the user reported as the current user.</param>
/// <param name="utcNow">The current UTC time reported by the time provider.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow)
{
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
currentUserService.UserId.Returns(userId);
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
dateTimeProvider.UtcNow.Returns(utcNow);
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
.Options);
context.Database.EnsureCreated();
return context;
}
/// <summary>
/// Loads a detached copy of a stored book, with its children, so that it can be handed to the repository as the desired state of an edit.
/// </summary>
/// <param name="context">The context that tracks the stored book.</param>
/// <param name="bookId">The Id of the book to load.</param>
/// <returns>The detached copy of the book.</returns>
private static async Task<BookEntity> LoadDetachedBookAsync(LuminaDbContext context, Guid bookId)
{
return await context.Books
.AsNoTracking()
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.Contributors)
.FirstAsync(book => book.Id == bookId);
}
}
@@ -0,0 +1,190 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications;
using Lumina.DataAccess.Core.UoW;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.BookLibrary.Specifications;
/// <summary>
/// Contains integration tests for the <see cref="BookAlphaFilterSpecification"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookAlphaFilterSpecificationTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly LuminaDbContext _context;
private readonly BookEntityFixture _bookEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookAlphaFilterSpecificationTests"/> class.
/// </summary>
public BookAlphaFilterSpecificationTests()
{
// The specification translates to the SQLite glob() function, so it can only be exercised against a real SQLite database.
_connection = new SqliteConnection("Data Source=:memory:");
_connection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connection).Options);
_context.Database.EnsureCreated();
}
[Fact]
public void ToExpression_WhenAlphaKeyIsNull_ShouldMatchEveryBook()
{
// Arrange
List<BookEntity> books = SeedBooks(("Alpha", null), ("Beta", null), ("1984", null));
BookAlphaFilterSpecification specification = new(null, false);
// Act
List<BookEntity> result = [.. _context.Books.Where(specification.ToExpression())];
// Assert
Assert.Equal(books.Count, result.Count);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsALowercaseLetter_ShouldMatchOnlyBooksWhoseTitleStartsWithIt()
{
// Arrange
SeedBooks(("Fellowship", null), ("Hobbit", null), ("The Two Towers", null));
BookAlphaFilterSpecification specification = new("f", false);
// Act
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
// Assert
Assert.Equal(["Fellowship"], result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsAnUppercaseLetter_ShouldMatchBooksWhoseTitleStartsWithItsLowercase()
{
// Arrange
SeedBooks(("Fellowship", null), ("Hobbit", null));
BookAlphaFilterSpecification specification = new("F", false);
// Act
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
// Assert
Assert.Equal(["Fellowship"], result);
}
[Fact]
public void ToExpression_WhenNoTitleStartsWithTheAlphaKey_ShouldNotMatchAnyBook()
{
// Arrange
SeedBooks(("Fellowship", null), ("Hobbit", null));
BookAlphaFilterSpecification specification = new("z", false);
// Act
List<BookEntity> result = [.. _context.Books.Where(specification.ToExpression())];
// Assert
Assert.Empty(result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsTheNumberKey_ShouldMatchOnlyBooksWhoseTitleStartsWithADigit()
{
// Arrange
SeedBooks(("1984", null), ("Alpha", null), ("Beta", null));
BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.NUMBER, false);
// Act
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
// Assert
Assert.Equal(["1984"], result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsTheSymbolKey_ShouldMatchOnlyBooksWhoseTitleStartsWithASymbol()
{
// Arrange
SeedBooks(("!Important", null), ("1984", null), ("Alpha", null));
BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.SYMBOL, false);
// Act
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
// Assert
Assert.Equal(["!Important"], result);
}
[Fact]
public void ToExpression_WhenTitleIsEmpty_ShouldMatchOnTheOriginalTitle()
{
// Arrange
BookEntity book = _bookEntityFixture.Create(title: string.Empty, originalTitle: "Rendezvous", includeMetadata: false);
_context.Books.Add(book);
_context.SaveChanges();
BookAlphaFilterSpecification specification = new("r", false);
// Act
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(entity => entity.OriginalTitle!)];
// Assert
Assert.Equal(["Rendezvous"], result);
}
[Fact]
public void ToExpression_WhenIgnoringThePrefixAndTitleStartsWithThe_ShouldMatchOnTheStrippedTitle()
{
// Arrange
SeedBooks(("The Art of War", null), ("Beneath the Surface", null));
BookAlphaFilterSpecification specification = new("a", true);
// Act
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
// Assert
Assert.Equal(["The Art of War"], result);
}
[Fact]
public void ToExpression_WhenNotIgnoringThePrefixAndTitleStartsWithThe_ShouldNotMatchOnTheStrippedTitle()
{
// Arrange
SeedBooks(("The Art of War", null), ("Beneath the Surface", null));
BookAlphaFilterSpecification specification = new("a", false);
// Act
List<BookEntity> result = [.. _context.Books.Where(specification.ToExpression())];
// Assert
Assert.Empty(result);
}
/// <summary>
/// Seeds books with the provided titles.
/// </summary>
/// <param name="books">The title and original title pairs of the books to seed.</param>
/// <returns>The seeded <see cref="BookEntity"/> instances.</returns>
private List<BookEntity> SeedBooks(params (string Title, string? OriginalTitle)[] books)
{
List<BookEntity> entities = [];
foreach ((string title, string? originalTitle) in books)
entities.Add(_bookEntityFixture.Create(title: title, originalTitle: originalTitle, includeMetadata: false));
_context.Books.AddRange(entities);
_context.SaveChanges();
return entities;
}
/// <summary>
/// Disposes the database context and its underlying connection.
/// </summary>
public void Dispose()
{
_context.Dispose();
_connection.Dispose();
}
}
@@ -0,0 +1,217 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Common.Dapper;
using Lumina.DataAccess.Core.Repositories.Libraries;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Libraries;
/// <summary>
/// Contains integration tests for the <see cref="DirectoryScanFingerprintRepository"/> class.
/// </summary>
/// <remarks>
/// The repository executes parameterized raw SQL on a dedicated database connection, so the tests exercise it against a real SQLite database
/// instead of the mocked in-memory context used by the Entity Framework based repositories.
/// </remarks>
[ExcludeFromCodeCoverage]
public class DirectoryScanFingerprintRepositoryTests : IDisposable
{
private readonly string _connectionString;
private readonly SqliteConnection _anchorConnection;
private readonly LuminaDbContext _context;
private readonly DirectoryScanFingerprintRepository _sut;
private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryScanFingerprintRepositoryTests"/> class.
/// </summary>
public DirectoryScanFingerprintRepositoryTests()
{
DapperTypeHandlers.Register();
_connectionString = $"Data Source=luminadataccess-fingerprint-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared";
_anchorConnection = new SqliteConnection(_connectionString);
_anchorConnection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connectionString).Options);
_context.Database.EnsureCreated();
_sut = new DirectoryScanFingerprintRepository(_context);
}
[Fact]
public async Task GetMappedByLibraryIdAsync_WhenCalled_ShouldReturnFingerprintsOfTheLibraryMappedByPath()
{
// Arrange
(Guid libraryId, _) = await SeedLibraryGraphAsync();
UserEntity otherUser = _userEntityFixture.Create();
_context.Users.Add(otherUser);
Guid otherLibraryId = Guid.NewGuid();
LibraryEntity otherLibrary = _libraryEntityFixture.Create(id: otherLibraryId, userId: otherUser.Id);
_context.Libraries.Add(otherLibrary);
DirectoryScanFingerprintEntity firstFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1", lastWriteTimeUtc: DateTime.UtcNow.AddDays(-1));
DirectoryScanFingerprintEntity secondFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir2", lastWriteTimeUtc: DateTime.UtcNow.AddDays(-2));
DirectoryScanFingerprintEntity fingerprintOfOtherLibrary = _directoryScanFingerprintEntityFixture.Create(libraryId: otherLibraryId, path: "/dir3");
_context.DirectoryScanFingerprints.AddRange(firstFingerprint, secondFingerprint, fingerprintOfOtherLibrary);
await _context.SaveChangesAsync();
// Act
Result<Dictionary<string, DirectoryScanFingerprintEntity>> result = await _sut.GetMappedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.True(result.Value.ContainsKey("/dir1"));
Assert.True(result.Value.ContainsKey("/dir2"));
Assert.False(result.Value.ContainsKey("/dir3"));
Assert.Equal(firstFingerprint.Id, result.Value["/dir1"].Id);
Assert.Equal(secondFingerprint.Id, result.Value["/dir2"].Id);
}
[Fact]
public async Task GetMappedByLibraryIdAsync_WhenNoFingerprintsExist_ShouldReturnEmptyDictionary()
{
// Arrange
(Guid libraryId, _) = await SeedLibraryGraphAsync();
// Act
Result<Dictionary<string, DirectoryScanFingerprintEntity>> result = await _sut.GetMappedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldDeleteOnlyTheFingerprintsOfThatLibrary()
{
// Arrange
(Guid libraryId, _) = await SeedLibraryGraphAsync();
UserEntity otherUser = _userEntityFixture.Create();
_context.Users.Add(otherUser);
Guid otherLibraryId = Guid.NewGuid();
LibraryEntity otherLibrary = _libraryEntityFixture.Create(id: otherLibraryId, userId: otherUser.Id);
_context.Libraries.Add(otherLibrary);
DirectoryScanFingerprintEntity firstFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1");
DirectoryScanFingerprintEntity secondFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir2");
DirectoryScanFingerprintEntity fingerprintOfOtherLibrary = _directoryScanFingerprintEntityFixture.Create(libraryId: otherLibraryId, path: "/dir3");
_context.DirectoryScanFingerprints.AddRange(firstFingerprint, secondFingerprint, fingerprintOfOtherLibrary);
await _context.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
DirectoryScanFingerprintEntity remainingFingerprint = await _context.DirectoryScanFingerprints.AsNoTracking().SingleAsync();
Assert.Equal(fingerprintOfOtherLibrary.Id, remainingFingerprint.Id);
}
[Fact]
public async Task DeleteByLibraryIdAsync_WhenNoFingerprintsExist_ShouldReturnDeleted()
{
// Arrange
(Guid libraryId, _) = await SeedLibraryGraphAsync();
// Act
Result<Deleted> result = await _sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
Assert.False(await _context.DirectoryScanFingerprints.AnyAsync());
}
[Fact]
public async Task UpsertRangeAsync_WhenCalledWithNewFingerprints_ShouldInsertThemAndReturnUpdated()
{
// Arrange
(Guid libraryId, _) = await SeedLibraryGraphAsync();
List<DirectoryScanFingerprintEntity> fingerprints =
[
_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1"),
_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir2")
];
// Act
Result<Updated> result = await _sut.UpsertRangeAsync(fingerprints, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
Assert.Equal(2, await _context.DirectoryScanFingerprints.CountAsync());
}
[Fact]
public async Task UpsertRangeAsync_WhenCalledWithExistingFingerprints_ShouldUpdateTheirLastWriteTime()
{
// Arrange
(Guid libraryId, _) = await SeedLibraryGraphAsync();
DirectoryScanFingerprintEntity existingFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1", lastWriteTimeUtc: DateTime.UtcNow.AddDays(-1));
_context.DirectoryScanFingerprints.Add(existingFingerprint);
await _context.SaveChangesAsync();
DateTime newLastWriteTimeUtc = DateTime.UtcNow.AddDays(1);
DirectoryScanFingerprintEntity updatedFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1", lastWriteTimeUtc: newLastWriteTimeUtc);
// Act
Result<Updated> result = await _sut.UpsertRangeAsync([updatedFingerprint], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
DirectoryScanFingerprintEntity retrievedFingerprint = await _context.DirectoryScanFingerprints.AsNoTracking().SingleAsync();
Assert.Equal(newLastWriteTimeUtc, retrievedFingerprint.LastWriteTimeUtc);
}
[Fact]
public async Task UpsertRangeAsync_WhenCollectionIsEmpty_ShouldReturnUpdatedWithoutUpserting()
{
// Arrange
(Guid libraryId, _) = await SeedLibraryGraphAsync();
// Act
Result<Updated> result = await _sut.UpsertRangeAsync([], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
Assert.False(await _context.DirectoryScanFingerprints.AnyAsync());
}
/// <summary>
/// Seeds the user and media library required by the foreign key of the fingerprints table.
/// </summary>
/// <returns>The seeded library Id and user Id.</returns>
private async Task<(Guid LibraryId, Guid UserId)> SeedLibraryGraphAsync()
{
UserEntity user = _userEntityFixture.Create();
_context.Users.Add(user);
LibraryEntity library = _libraryEntityFixture.Create(userId: user.Id);
_context.Libraries.Add(library);
await _context.SaveChangesAsync();
return (library.Id, user.Id);
}
/// <inheritdoc/>
public void Dispose()
{
_context.Dispose();
_anchorConnection.Dispose();
}
}
@@ -0,0 +1,323 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
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.UsersManagement;
using Lumina.DataAccess.Common.Interceptors;
using Lumina.DataAccess.Core.Repositories.Libraries;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
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.IntegrationTests.Core.Repositories.Libraries;
/// <summary>
/// Contains integration tests for the <see cref="LibraryRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryRepositoryTests
{
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LibraryContentLocationEntityFixture _libraryContentLocationEntityFixture = new();
[Fact]
public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeTheLibraryAudit()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, contentLocations: ["/media/one", "/media/two"]);
context.Libraries.Add(library);
await context.SaveChangesAsync();
LibraryEntity incoming = await LoadDetachedLibraryAsync(context, library.Id);
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().Include(candidate => candidate.ContentLocations).FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.Null(storedLibrary!.UpdatedOnUtc);
Assert.Equal(2, storedLibrary.ContentLocations.Count);
}
[Fact]
public async Task UpdateAsync_WhenContentLocationsChange_ShouldApplyOnlyTheDeltasAndKeepTheUnchangedOnes()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-update-locations-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, contentLocations: ["/media/one", "/media/two", "/media/keep"]);
context.Libraries.Add(library);
await context.SaveChangesAsync();
Guid keptLocationId = context.Entry(library.ContentLocations.Single(location => location.Path == "/media/keep")).Property<Guid>("Id").CurrentValue;
Guid retainedLocationId = context.Entry(library.ContentLocations.Single(location => location.Path == "/media/one")).Property<Guid>("Id").CurrentValue;
LibraryEntity incoming = await LoadDetachedLibraryAsync(context, library.Id);
incoming.ContentLocations.Clear();
foreach (string path in new[] { "/media/one", "/media/keep", "/media/three" })
incoming.ContentLocations.Add(_libraryContentLocationEntityFixture.Create(path: path));
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().Include(candidate => candidate.ContentLocations).FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.Equal(3, storedLibrary!.ContentLocations.Count);
Assert.Equal(["/media/keep", "/media/one", "/media/three"], [.. storedLibrary.ContentLocations.Select(location => location.Path).OrderBy(path => path)]);
// The two locations that did not change must keep their stored row identity, instead of being deleted and re-inserted.
Assert.Equal(retainedLocationId, context.Entry(library.ContentLocations.Single(location => location.Path == "/media/one")).Property<Guid>("Id").CurrentValue);
Assert.Equal(keptLocationId, context.Entry(library.ContentLocations.Single(location => location.Path == "/media/keep")).Property<Guid>("Id").CurrentValue);
}
[Fact]
public async Task InsertAsync_WhenLibraryTracksConsumptionProgress_ShouldPersistTheTrackingAndThreshold()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-insert-consumption-tracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 75, contentLocations: []);
// Act
Result<Created> result = await sut.InsertAsync(library, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(75, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task InsertAsync_WhenLibraryDoesNotTrackConsumptionProgress_ShouldPersistTrackingOffWithoutThreshold()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-insert-consumption-off-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, shouldTrackConsumptionProgress: false, completionThresholdPercentage: null, contentLocations: []);
// Act
Result<Created> result = await sut.InsertAsync(library, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.False(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Null(storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task InsertAsync_WhenLibraryContentIsOnSsd_ShouldPersistTheSetting()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-insert-ssd-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, isContentOnSsd: true, contentLocations: []);
// Act
Result<Created> result = await sut.InsertAsync(library, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.IsContentOnSsd);
}
[Fact]
public async Task UpdateAsync_WhenConsumptionSettingsAreEnabled_ShouldPersistTheTrackingAndThreshold()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-update-consumption-on-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, shouldTrackConsumptionProgress: false, completionThresholdPercentage: null, contentLocations: []);
context.Libraries.Add(library);
await context.SaveChangesAsync();
LibraryEntity incoming = _libraryEntityFixture.Create(
id: library.Id,
userId: userId,
title: library.Title,
coverImage: library.CoverImage,
libraryType: library.LibraryType,
contentLocations: [],
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 60);
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(60, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateAsync_WhenConsumptionSettingsAreDisabled_ShouldPersistTrackingOffWithoutThreshold()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-update-consumption-off-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 80, contentLocations: []);
context.Libraries.Add(library);
await context.SaveChangesAsync();
LibraryEntity incoming = _libraryEntityFixture.Create(
id: library.Id,
userId: userId,
title: library.Title,
coverImage: library.CoverImage,
libraryType: library.LibraryType,
contentLocations: [],
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.False(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Null(storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateAsync_WhenOnlyConsumptionSettingsChange_ShouldStampTheUpdateAudit()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-update-consumption-audit-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, shouldTrackConsumptionProgress: false, completionThresholdPercentage: null, contentLocations: []);
context.Libraries.Add(library);
await context.SaveChangesAsync();
LibraryEntity incoming = _libraryEntityFixture.Create(
id: library.Id,
userId: userId,
title: library.Title,
coverImage: library.CoverImage,
libraryType: library.LibraryType,
contentLocations: [],
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 55);
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(55, storedLibrary.CompletionThresholdPercentage);
Assert.Equal(utcNow, storedLibrary.UpdatedOnUtc);
Assert.Equal(userId, storedLibrary.UpdatedBy);
}
/// <summary>
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <param name="userId">The Id of the user reported as the current user.</param>
/// <param name="utcNow">The current UTC time reported by the time provider.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow)
{
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
currentUserService.UserId.Returns(userId);
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
dateTimeProvider.UtcNow.Returns(utcNow);
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
.Options);
context.Database.EnsureCreated();
return context;
}
/// <summary>
/// Loads a detached copy of a stored library, with its content locations, so that it can be handed to the repository as the desired state of an edit.
/// </summary>
/// <param name="context">The context that tracks the stored library.</param>
/// <param name="libraryId">The Id of the library to load.</param>
/// <returns>The detached copy of the library.</returns>
private static async Task<LibraryEntity> LoadDetachedLibraryAsync(LuminaDbContext context, Guid libraryId)
{
return await context.Libraries
.AsNoTracking()
.Include(library => library.ContentLocations)
.FirstAsync(library => library.Id == libraryId);
}
}
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.Repositories.Libraries;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Libraries;
/// <summary>
/// Contains integration tests for the <see cref="LibraryScanRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanRepositoryTests
{
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
[Fact]
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryscanrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
LibraryScanRepository sut = new(context);
UserEntity storedUser = _userEntityFixture.Create(username: "scan-user", password: "Password123");
context.Users.Add(storedUser);
LibraryEntity storedLibrary = _libraryEntityFixture.Create(userId: storedUser.Id);
context.Libraries.Add(storedLibrary);
await context.SaveChangesAsync();
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
Guid storedCreatedBy = Guid.NewGuid();
LibraryScanEntity storedScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Running, libraryEntity: storedLibrary);
storedScan.CreatedOnUtc = storedCreatedOnUtc;
storedScan.CreatedBy = storedCreatedBy;
context.LibraryScans.Add(storedScan);
await context.SaveChangesAsync();
LibraryScanEntity updatedScan = _libraryScanEntityFixture.Create(id: storedScan.Id, libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Completed, libraryEntity: storedLibrary);
updatedScan.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
updatedScan.CreatedBy = Guid.NewGuid();
updatedScan.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5);
updatedScan.UpdatedBy = Guid.NewGuid();
// Act
Result<Updated> result = await sut.UpdateAsync(updatedScan, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
LibraryScanEntity reloadedScan = await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == storedScan.Id);
Assert.Equal(LibraryScanJobStatus.Completed, reloadedScan.Status);
Assert.Equal(storedCreatedOnUtc, reloadedScan.CreatedOnUtc);
Assert.Equal(storedCreatedBy, reloadedScan.CreatedBy);
Assert.Null(reloadedScan.UpdatedOnUtc);
Assert.Null(reloadedScan.UpdatedBy);
}
[Fact]
public async Task FailInterruptedScansAsync_WhenScansArePendingOrRunning_ShouldMarkThemAsFailedAndLeaveTheOthersUnchanged()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryscanrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
LibraryScanRepository sut = new(context);
UserEntity storedUser = _userEntityFixture.Create(username: "scan-user", password: "Password123");
context.Users.Add(storedUser);
LibraryEntity storedLibrary = _libraryEntityFixture.Create(userId: storedUser.Id);
context.Libraries.Add(storedLibrary);
await context.SaveChangesAsync();
LibraryScanEntity pendingScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Pending, libraryEntity: storedLibrary);
LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Running, libraryEntity: storedLibrary);
LibraryScanEntity completedScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Completed, libraryEntity: storedLibrary);
LibraryScanEntity canceledScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Canceled, libraryEntity: storedLibrary);
LibraryScanEntity failedScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Failed, libraryEntity: storedLibrary);
context.LibraryScans.AddRange(pendingScan, runningScan, completedScan, canceledScan, failedScan);
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.FailInterruptedScansAsync(CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
context.ChangeTracker.Clear();
Assert.Equal(LibraryScanJobStatus.Failed, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == pendingScan.Id)).Status);
Assert.Equal(LibraryScanJobStatus.Failed, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == runningScan.Id)).Status);
Assert.Equal(LibraryScanJobStatus.Completed, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == completedScan.Id)).Status);
Assert.Equal(LibraryScanJobStatus.Canceled, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == canceledScan.Id)).Status);
Assert.Equal(LibraryScanJobStatus.Failed, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == failedScan.Id)).Status);
}
}
@@ -0,0 +1,280 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Common.Dapper;
using Lumina.DataAccess.Core.Repositories.Libraries;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Libraries;
/// <summary>
/// Contains integration tests for the <see cref="LibraryScanSnapshotRepository"/> class.
/// </summary>
/// <remarks>
/// The repository executes parameterized raw SQL on a dedicated database connection, so the tests exercise it against a real SQLite database
/// instead of the mocked in-memory context used by the Entity Framework based repositories.
/// </remarks>
[ExcludeFromCodeCoverage]
public class LibraryScanSnapshotRepositoryTests : IDisposable
{
private readonly string _connectionString;
private readonly SqliteConnection _anchorConnection;
private readonly LuminaDbContext _context;
private readonly LibraryScanSnapshotRepository _sut;
private readonly LibraryScanSnapshotEntityFixture _libraryScanSnapshotEntityFixture = new();
private readonly LibraryScanStagingResultsEntityFixture _libraryScanStagingResultsEntityFixture = new();
private readonly LibraryScanResultEntityFixture _libraryScanResultEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanSnapshotRepositoryTests"/> class.
/// </summary>
public LibraryScanSnapshotRepositoryTests()
{
_connectionString = $"Data Source=luminadataccess-snapshot-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared";
_anchorConnection = new SqliteConnection(_connectionString);
_anchorConnection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connectionString).Options);
_context.Database.EnsureCreated();
// The production composition root registers this handler, so the integration tests must exercise the same Guid representation.
DapperTypeHandlers.Register();
_sut = new LibraryScanSnapshotRepository(_context);
}
[Fact]
public async Task GetDeletedPathsAsync_WhenSnapshotPathsAreMissingFromStaging_ShouldReturnThosePaths()
{
// Arrange
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity keptSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub");
LibraryScanSnapshotEntity deletedSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/delete.epub");
_context.LibraryScanSnapshots.AddRange(keptSnapshot, deletedSnapshot);
LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/keep.epub");
_context.LibraryScanStagingResults.Add(staging);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<string>> result = await _sut.GetDeletedPathsAsync(library.Id, scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
string deletedPath = Assert.Single(result.Value);
Assert.Equal("/books/delete.epub", deletedPath);
}
[Fact]
public async Task GetDeletedPathsAsync_WhenAllSnapshotPathsArePresentInStaging_ShouldReturnEmptyList()
{
// Arrange
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub");
_context.LibraryScanSnapshots.Add(snapshot);
LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/keep.epub");
_context.LibraryScanStagingResults.Add(staging);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<string>> result = await _sut.GetDeletedPathsAsync(library.Id, scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetDeletedPathsAsync_WhenStagingOfAnotherScanMatches_ShouldStillReturnThePaths()
{
// Arrange
(UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanEntity otherScan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Completed);
_context.LibraryScans.Add(otherScan);
LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub");
_context.LibraryScanSnapshots.Add(snapshot);
LibraryScanStagingResultsEntity stagingOfOtherScan = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: otherScan.Id, path: "/books/a.epub");
_context.LibraryScanStagingResults.Add(stagingOfOtherScan);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<string>> result = await _sut.GetDeletedPathsAsync(library.Id, scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
string deletedPath = Assert.Single(result.Value);
Assert.Equal("/books/a.epub", deletedPath);
}
[Fact]
public async Task GetPathsAsync_WhenCalled_ShouldReturnAllSnapshotPathsOfTheLibrary()
{
// Arrange
(_, LibraryEntity library, _) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity firstSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub");
LibraryScanSnapshotEntity secondSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/b.epub");
_context.LibraryScanSnapshots.AddRange(firstSnapshot, secondSnapshot);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlySet<string>> result = await _sut.GetPathsAsync(library.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Contains("/books/a.epub", result.Value);
Assert.Contains("/books/b.epub", result.Value);
}
[Fact]
public async Task GetPathsAsync_WhenNoSnapshotsExist_ShouldReturnEmptyList()
{
// Arrange
(_, LibraryEntity library, _) = await SeedScanGraphAsync();
// Act
Result<IReadOnlySet<string>> result = await _sut.GetPathsAsync(library.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task ApplySnapshotSwapAsync_WhenCalled_ShouldAuditDeletedChangedAndNewItemsAndUpdateSnapshot()
{
// Arrange
(UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity keptSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub", contentHash: 111, fileSize: 100, ticks: 1000);
LibraryScanSnapshotEntity deletedSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/delete.epub", contentHash: 222, fileSize: 200, ticks: 2000);
_context.LibraryScanSnapshots.AddRange(keptSnapshot, deletedSnapshot);
LibraryScanStagingResultsEntity unchangedStaging = _libraryScanStagingResultsEntityFixture.Create(
libraryScanId: scanId, path: "/books/keep.epub", size: 100, ticks: 1000, contentHash: 999, needsRehash: false, isNew: false);
LibraryScanStagingResultsEntity newStaging = _libraryScanStagingResultsEntityFixture.Create(
libraryScanId: scanId, path: "/books/new.epub", size: 300, ticks: 3000, contentHash: 300, needsRehash: true, isNew: true);
LibraryScanStagingResultsEntity modifiedStaging = _libraryScanStagingResultsEntityFixture.Create(
libraryScanId: scanId, path: "/books/modified.epub", size: 400, ticks: 4000, contentHash: 400, needsRehash: true, isNew: false);
_context.LibraryScanStagingResults.AddRange(unchangedStaging, newStaging, modifiedStaging);
await _context.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.ApplySnapshotSwapAsync(library.Id, scanId, user.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
// Audit entries: deleted, new and modified items.
List<LibraryScanResultEntity> scanResults = await _context.LibraryScanResults.AsNoTracking()
.Where(scanResult => scanResult.LibraryScanId == scanId)
.ToListAsync();
Assert.Equal(3, scanResults.Count);
Assert.Contains(scanResults, scanResult => scanResult.Path == "/books/delete.epub" && scanResult.Status == LibraryScanFileStatus.Deleted);
Assert.Contains(scanResults, scanResult => scanResult.Path == "/books/new.epub" && scanResult.Status == LibraryScanFileStatus.New);
Assert.Contains(scanResults, scanResult => scanResult.Path == "/books/modified.epub" && scanResult.Status == LibraryScanFileStatus.Modified);
Assert.DoesNotContain(scanResults, scanResult => scanResult.Path == "/books/keep.epub");
// The snapshot now contains the kept, new and modified items and no longer contains the deleted one.
List<LibraryScanSnapshotEntity> snapshots = await _context.LibraryScanSnapshots.AsNoTracking()
.Where(snapshot => snapshot.LibraryId == library.Id)
.ToListAsync();
Assert.Equal(3, snapshots.Count);
Assert.Contains(snapshots, snapshot => snapshot.Path == "/books/keep.epub" && snapshot.ContentHash == 111);
Assert.Contains(snapshots, snapshot => snapshot.Path == "/books/new.epub" && snapshot.ContentHash == 300);
Assert.Contains(snapshots, snapshot => snapshot.Path == "/books/modified.epub" && snapshot.ContentHash == 400);
Assert.DoesNotContain(snapshots, snapshot => snapshot.Path == "/books/delete.epub");
// The staging results of the scan have been cleared.
Assert.False(await _context.LibraryScanStagingResults.AsNoTracking().AnyAsync(staging => staging.LibraryScanId == scanId));
}
[Fact]
public async Task ApplySnapshotSwapAsync_WhenNoStagingNeedsRehash_ShouldOnlyClearStagingAndAuditDeletedItems()
{
// Arrange
(UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity keptSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub", contentHash: 111, fileSize: 100, ticks: 1000);
_context.LibraryScanSnapshots.Add(keptSnapshot);
LibraryScanStagingResultsEntity unchangedStaging = _libraryScanStagingResultsEntityFixture.Create(
libraryScanId: scanId, path: "/books/keep.epub", size: 100, ticks: 1000, needsRehash: false, isNew: false);
_context.LibraryScanStagingResults.Add(unchangedStaging);
await _context.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.ApplySnapshotSwapAsync(library.Id, scanId, user.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
Assert.False(await _context.LibraryScanResults.AsNoTracking().AnyAsync());
Assert.False(await _context.LibraryScanStagingResults.AsNoTracking().AnyAsync(staging => staging.LibraryScanId == scanId));
}
[Fact]
public async Task RollbackSnapshotForScanAsync_WhenCalled_ShouldRemoveOnlyTheSnapshotEntriesTheScanAddedOrModified()
{
// Arrange
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity untouchedSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/untouched.epub");
LibraryScanSnapshotEntity newSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/new.epub");
LibraryScanSnapshotEntity modifiedSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/modified.epub");
_context.LibraryScanSnapshots.AddRange(untouchedSnapshot, newSnapshot, modifiedSnapshot);
LibraryScanResultEntity newResult = _libraryScanResultEntityFixture.Create(libraryScanId: scanId, status: LibraryScanFileStatus.New, path: "/books/new.epub");
LibraryScanResultEntity modifiedResult = _libraryScanResultEntityFixture.Create(libraryScanId: scanId, status: LibraryScanFileStatus.Modified, path: "/books/modified.epub");
LibraryScanResultEntity deletedResult = _libraryScanResultEntityFixture.Create(libraryScanId: scanId, status: LibraryScanFileStatus.Deleted, path: "/books/deleted.epub");
_context.LibraryScanResults.AddRange(newResult, modifiedResult, deletedResult);
await _context.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.RollbackSnapshotForScanAsync(library.Id, scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
List<LibraryScanSnapshotEntity> snapshots = await _context.LibraryScanSnapshots.AsNoTracking()
.Where(snapshot => snapshot.LibraryId == library.Id)
.ToListAsync();
LibraryScanSnapshotEntity remainingSnapshot = Assert.Single(snapshots);
Assert.Equal("/books/untouched.epub", remainingSnapshot.Path);
// The audit results are kept: they describe what the failed scan found, and only the snapshot is rolled back.
Assert.Equal(3, await _context.LibraryScanResults.AsNoTracking().CountAsync(scanResult => scanResult.LibraryScanId == scanId));
}
/// <summary>
/// Seeds the user, media library and media library scan required by the foreign keys of the snapshot and staging tables.
/// </summary>
/// <returns>The seeded user, media library and scan Id.</returns>
private async Task<(UserEntity User, LibraryEntity Library, Guid ScanId)> SeedScanGraphAsync()
{
UserEntity user = _userEntityFixture.Create();
_context.Users.Add(user);
LibraryEntity library = _libraryEntityFixture.Create(userId: user.Id);
_context.Libraries.Add(library);
LibraryScanEntity scan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Running);
_context.LibraryScans.Add(scan);
await _context.SaveChangesAsync();
return (user, library, scan.Id);
}
/// <inheritdoc/>
public void Dispose()
{
_context.Dispose();
_anchorConnection.Dispose();
}
}
@@ -0,0 +1,337 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
using Lumina.DataAccess.Core.Repositories.Libraries;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Libraries;
/// <summary>
/// Contains integration tests for the <see cref="LibraryScanStagingResultsRepository"/> class.
/// </summary>
/// <remarks>
/// The repository executes parameterized raw SQL on a dedicated database connection, so the tests exercise it against a real SQLite database
/// instead of the mocked in-memory context used by the Entity Framework based repositories.
/// </remarks>
[ExcludeFromCodeCoverage]
public class LibraryScanStagingResultsRepositoryTests : IDisposable
{
private readonly string _connectionString;
private readonly SqliteConnection _anchorConnection;
private readonly LuminaDbContext _context;
private readonly LibraryScanStagingResultsRepository _sut;
private readonly LibraryScanStagingResultsEntityFixture _libraryScanStagingResultsEntityFixture = new();
private readonly LibraryScanSnapshotEntityFixture _libraryScanSnapshotEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
private readonly HashedFileSystemFileDtoFixture _hashedFileSystemFileDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanStagingResultsRepositoryTests"/> class.
/// </summary>
public LibraryScanStagingResultsRepositoryTests()
{
_connectionString = $"Data Source=luminadataccess-staging-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared";
_anchorConnection = new SqliteConnection(_connectionString);
_anchorConnection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connectionString).Options);
_context.Database.EnsureCreated();
_sut = new LibraryScanStagingResultsRepository(_context);
}
[Fact]
public async Task InsertRangeAsync_WhenCalled_ShouldInsertAllEntitiesAndReturnCreated()
{
// Arrange
(_, _, Guid scanId) = await SeedScanGraphAsync();
List<LibraryScanStagingResultsEntity> stagingResults = _libraryScanStagingResultsEntityFixture.CreateMany(3);
for (int i = 0; i < stagingResults.Count; i++)
stagingResults[i] = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId);
// Act
Result<Created> result = await _sut.InsertRangeAsync(stagingResults, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
Assert.Equal(3, await _context.LibraryScanStagingResults.CountAsync());
}
[Fact]
public async Task InsertRangeAsync_WhenCollectionIsEmpty_ShouldReturnCreatedWithoutInserting()
{
// Arrange
await SeedScanGraphAsync();
// Act
Result<Created> result = await _sut.InsertRangeAsync([], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
Assert.False(await _context.LibraryScanStagingResults.AnyAsync());
}
[Fact]
public async Task MarkChangesAgainstSnapshotAsync_WhenSnapshotHasSameSizeAndTicks_ShouldMarkAsUnchanged()
{
// Arrange
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub", contentHash: 111, fileSize: 100, ticks: 1000);
_context.LibraryScanSnapshots.Add(snapshot);
LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", size: 100, ticks: 1000);
_context.LibraryScanStagingResults.Add(staging);
await _context.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.MarkChangesAgainstSnapshotAsync(scanId, library.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
LibraryScanStagingResultsEntity markedStaging = await _context.LibraryScanStagingResults.AsNoTracking().SingleAsync();
Assert.Equal(111UL, markedStaging.ContentHash);
Assert.Equal(111UL, markedStaging.PreviousContentHash);
Assert.False(markedStaging.NeedsRehash);
Assert.False(markedStaging.IsNew);
}
[Fact]
public async Task MarkChangesAgainstSnapshotAsync_WhenSnapshotHasDifferentSizeOrTicks_ShouldMarkAsChanged()
{
// Arrange
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub", contentHash: 222, fileSize: 100, ticks: 1000);
_context.LibraryScanSnapshots.Add(snapshot);
LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", size: 500, ticks: 5000);
_context.LibraryScanStagingResults.Add(staging);
await _context.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.MarkChangesAgainstSnapshotAsync(scanId, library.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
LibraryScanStagingResultsEntity markedStaging = await _context.LibraryScanStagingResults.AsNoTracking().SingleAsync();
Assert.Equal(222UL, markedStaging.ContentHash);
Assert.Equal(222UL, markedStaging.PreviousContentHash);
Assert.True(markedStaging.NeedsRehash);
Assert.False(markedStaging.IsNew);
}
[Fact]
public async Task MarkChangesAgainstSnapshotAsync_WhenNoSnapshotExists_ShouldKeepTheItemMarkedAsNew()
{
// Arrange
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
// The file system discovery job seeds new items with no hash and marks them as new, needing a rehash.
LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", contentHash: 0, previousContentHash: 0, needsRehash: true, isNew: true);
_context.LibraryScanStagingResults.Add(staging);
await _context.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.MarkChangesAgainstSnapshotAsync(scanId, library.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
LibraryScanStagingResultsEntity markedStaging = await _context.LibraryScanStagingResults.AsNoTracking().SingleAsync();
Assert.Equal(0UL, markedStaging.ContentHash);
Assert.Equal(0UL, markedStaging.PreviousContentHash);
Assert.True(markedStaging.NeedsRehash);
Assert.True(markedStaging.IsNew);
}
[Fact]
public async Task GetFilesToHashCountAsync_WhenCalled_ShouldReturnOnlyStagingResultsNeedingRehash()
{
// Arrange
(_, _, Guid scanId) = await SeedScanGraphAsync();
LibraryScanStagingResultsEntity firstRehash = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, needsRehash: true);
LibraryScanStagingResultsEntity secondRehash = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, needsRehash: true);
LibraryScanStagingResultsEntity noRehash = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, needsRehash: false);
_context.LibraryScanStagingResults.AddRange(firstRehash, secondRehash, noRehash);
await _context.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetFilesToHashCountAsync(scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value);
}
[Fact]
public async Task GetFilesToHashPageAsync_WhenCalled_ShouldReturnOrderedPageOfStagingResultsNeedingRehash()
{
// Arrange
(_, _, Guid scanId) = await SeedScanGraphAsync();
LibraryScanStagingResultsEntity aFile = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", size: 10, ticks: 100, needsRehash: true);
LibraryScanStagingResultsEntity bFile = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/b.epub", size: 20, ticks: 200, needsRehash: true);
LibraryScanStagingResultsEntity noRehash = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/z.epub", needsRehash: false);
_context.LibraryScanStagingResults.AddRange(aFile, bFile, noRehash);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<HashedFileSystemFileDto>> result = await _sut.GetFilesToHashPageAsync(scanId, null, 10, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Equal("/books/a.epub", result.Value[0].Path);
Assert.Equal("/books/b.epub", result.Value[1].Path);
Assert.Equal(10, result.Value[0].Size);
Assert.Equal(20, result.Value[1].Size);
Assert.Equal(100, result.Value[0].Ticks);
Assert.Equal(200, result.Value[1].Ticks);
}
[Fact]
public async Task GetFilesToHashPageAsync_WhenLastPathProvided_ShouldReturnOnlyResultsAfterIt()
{
// Arrange
(_, _, Guid scanId) = await SeedScanGraphAsync();
LibraryScanStagingResultsEntity aFile = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", needsRehash: true);
LibraryScanStagingResultsEntity bFile = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/b.epub", needsRehash: true);
_context.LibraryScanStagingResults.AddRange(aFile, bFile);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<HashedFileSystemFileDto>> result = await _sut.GetFilesToHashPageAsync(scanId, "/books/a.epub", 10, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
HashedFileSystemFileDto retrievedFile = Assert.Single(result.Value);
Assert.Equal("/books/b.epub", retrievedFile.Path);
}
[Fact]
public async Task GetChangedPathsAsync_WhenStagingResultsChanged_ShouldReturnOnlyTheChangedPathsExcludingNewItems()
{
// Arrange
(_, _, Guid scanId) = await SeedScanGraphAsync();
LibraryScanStagingResultsEntity changedStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", needsRehash: true, isNew: false);
LibraryScanStagingResultsEntity newStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/b.epub", needsRehash: true, isNew: true);
LibraryScanStagingResultsEntity unchangedStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/c.epub", needsRehash: false, isNew: false);
_context.LibraryScanStagingResults.AddRange(changedStaging, newStaging, unchangedStaging);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<string>> result = await _sut.GetChangedPathsAsync(scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
string changedPath = Assert.Single(result.Value);
Assert.Equal("/books/a.epub", changedPath);
}
[Fact]
public async Task GetChangedPathsAsync_WhenNoStagingResultsAreChanged_ShouldReturnEmptyList()
{
// Arrange
(_, _, Guid scanId) = await SeedScanGraphAsync();
LibraryScanStagingResultsEntity newStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/b.epub", needsRehash: true, isNew: true);
_context.LibraryScanStagingResults.Add(newStaging);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<string>> result = await _sut.GetChangedPathsAsync(scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task UpdateFileHashesAsync_WhenCalled_ShouldUpdateTheContentHashes()
{
// Arrange
(_, _, Guid scanId) = await SeedScanGraphAsync();
LibraryScanStagingResultsEntity firstStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", contentHash: 111);
LibraryScanStagingResultsEntity secondStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/b.epub", contentHash: 222);
_context.LibraryScanStagingResults.AddRange(firstStaging, secondStaging);
await _context.SaveChangesAsync();
List<HashedFileSystemFileDto> hashedFiles =
[
_hashedFileSystemFileDtoFixture.Create(path: "/books/a.epub", size: 10, ticks: 100, currentHash: 999, oldHash: 0),
_hashedFileSystemFileDtoFixture.Create(path: "/books/b.epub", size: 20, ticks: 200, currentHash: 888, oldHash: 0)
];
// Act
Result<Updated> result = await _sut.UpdateFileHashesAsync(scanId, hashedFiles, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
List<LibraryScanStagingResultsEntity> stagingResults = await _context.LibraryScanStagingResults.AsNoTracking().OrderBy(staging => staging.Path).ToListAsync();
Assert.Equal(999UL, stagingResults[0].ContentHash);
Assert.Equal(888UL, stagingResults[1].ContentHash);
}
[Fact]
public async Task ClearForScanAsync_WhenCalled_ShouldRemoveOnlyTheStagingResultsOfTheScan()
{
// Arrange
(UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanEntity otherScan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Completed);
_context.LibraryScans.Add(otherScan);
LibraryScanStagingResultsEntity stagingOfScan = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId);
LibraryScanStagingResultsEntity stagingOfOtherScan = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: otherScan.Id);
_context.LibraryScanStagingResults.AddRange(stagingOfScan, stagingOfOtherScan);
await _context.SaveChangesAsync();
// Act
Result<Success> result = await _sut.ClearForScanAsync(scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
Assert.False(await _context.LibraryScanStagingResults.AsNoTracking().AnyAsync(staging => staging.LibraryScanId == scanId));
Assert.Single(await _context.LibraryScanStagingResults.AsNoTracking().Where(staging => staging.LibraryScanId == otherScan.Id).ToListAsync());
}
/// <summary>
/// Seeds the user, media library and media library scan required by the foreign keys of the staging table.
/// </summary>
/// <returns>The seeded user, media library and scan Id.</returns>
private async Task<(UserEntity User, LibraryEntity Library, Guid ScanId)> SeedScanGraphAsync()
{
UserEntity user = _userEntityFixture.Create();
_context.Users.Add(user);
LibraryEntity library = _libraryEntityFixture.Create(userId: user.Id);
_context.Libraries.Add(library);
LibraryScanEntity scan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Running);
_context.LibraryScans.Add(scan);
await _context.SaveChangesAsync();
return (user, library, scan.Id);
}
/// <inheritdoc/>
public void Dispose()
{
_context.Dispose();
_anchorConnection.Dispose();
}
}
@@ -0,0 +1,408 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
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.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.MediaConsumption;
/// <summary>
/// Contains integration tests for the <see cref="ConsumptionStatisticsRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class ConsumptionStatisticsRepositoryTests
{
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
[Fact]
public async Task GetForUserAsync_WhenTheUserHasRecords_ShouldReturnOnlyTheirRecordsWithEveryPersistedValue()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-get-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
ConsumptionStatisticsRepository sut = new(context);
Guid userId = Guid.NewGuid();
Guid otherUserId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
Guid movieMediaItemId = Guid.NewGuid();
Guid bookMediaItemId = Guid.NewGuid();
DateTime movieStartedOnUtc = new(2025, 1, 1, 8, 0, 0, DateTimeKind.Utc);
DateTime movieLastActivityOnUtc = new(2025, 1, 1, 8, 45, 0, DateTimeKind.Utc);
DateTime movieEndedOnUtc = new(2025, 1, 1, 9, 0, 0, DateTimeKind.Utc);
MediaConsumptionRecordEntity movieRecord = _mediaConsumptionRecordEntityFixture.Create(
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.Movie,
mediaItemId: movieMediaItemId,
status: ConsumptionStatus.Completed,
startedOnUtc: movieStartedOnUtc,
lastActivityOnUtc: movieLastActivityOnUtc,
endedOnUtc: movieEndedOnUtc,
consumedDurationMilliseconds: 1_800_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 1_234_567,
includeLastPositionLocation: false,
lastProgressFraction: 0.42,
consecutivePagesRead: 0,
version: 7);
MediaConsumptionRecordEntity bookRecord = _mediaConsumptionRecordEntityFixture.Create(
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.Book,
mediaItemId: bookMediaItemId,
status: ConsumptionStatus.InProgress,
startedOnUtc: new DateTime(2025, 1, 1, 10, 0, 0, DateTimeKind.Utc),
lastActivityOnUtc: new DateTime(2025, 1, 1, 10, 20, 0, DateTimeKind.Utc),
includeEndedOnUtc: false,
consumedDurationMilliseconds: 90_000,
lastPositionKind: MediaPositionKind.Location,
includeLastPositionTimeOffsetMilliseconds: false,
lastPositionLocation: "chapter-3:paragraph-14",
lastProgressFraction: 0.17,
consecutivePagesRead: 12,
version: 1);
MediaConsumptionRecordEntity otherUserRecord = _mediaConsumptionRecordEntityFixture.Create(
userId: otherUserId, libraryId: libraryId, mediaKind: MediaKind.Movie);
context.Users.AddRange(_userEntityFixture.Create(id: userId), _userEntityFixture.Create(id: otherUserId));
context.MediaConsumptionRecords.AddRange(movieRecord, bookRecord, otherUserRecord);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// 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.DoesNotContain(result.Value, record => record.Id == otherUserRecord.Id);
MediaConsumptionRecordEntity storedMovieRecord = result.Value.Single(record => record.Id == movieRecord.Id);
Assert.Equal(userId, storedMovieRecord.UserId);
Assert.Equal(libraryId, storedMovieRecord.LibraryId);
Assert.Equal(MediaKind.Movie, storedMovieRecord.MediaKind);
Assert.Equal(movieMediaItemId, storedMovieRecord.MediaItemId);
Assert.Equal(ConsumptionStatus.Completed, storedMovieRecord.Status);
Assert.Equal(movieStartedOnUtc, storedMovieRecord.StartedOnUtc);
Assert.Equal(movieLastActivityOnUtc, storedMovieRecord.LastActivityOnUtc);
Assert.Equal(movieEndedOnUtc, storedMovieRecord.EndedOnUtc);
Assert.Equal(1_800_000L, storedMovieRecord.ConsumedDurationMilliseconds);
Assert.Equal(MediaPositionKind.TimeOffset, storedMovieRecord.LastPositionKind);
Assert.Equal(1_234_567L, storedMovieRecord.LastPositionTimeOffsetMilliseconds);
Assert.Null(storedMovieRecord.LastPositionLocation);
Assert.Equal(0.42, storedMovieRecord.LastProgressFraction);
Assert.Equal(0, storedMovieRecord.ConsecutivePagesRead);
Assert.Equal(7L, storedMovieRecord.Version);
MediaConsumptionRecordEntity storedBookRecord = result.Value.Single(record => record.Id == bookRecord.Id);
Assert.Equal(MediaKind.Book, storedBookRecord.MediaKind);
Assert.Equal(bookMediaItemId, storedBookRecord.MediaItemId);
Assert.Equal(ConsumptionStatus.InProgress, storedBookRecord.Status);
Assert.Null(storedBookRecord.EndedOnUtc);
Assert.Equal(90_000L, storedBookRecord.ConsumedDurationMilliseconds);
Assert.Equal(MediaPositionKind.Location, storedBookRecord.LastPositionKind);
Assert.Null(storedBookRecord.LastPositionTimeOffsetMilliseconds);
Assert.Equal("chapter-3:paragraph-14", storedBookRecord.LastPositionLocation);
Assert.Equal(0.17, storedBookRecord.LastProgressFraction);
Assert.Equal(12, storedBookRecord.ConsecutivePagesRead);
}
[Fact]
public async Task GetForUserAsync_WhenAnotherUserHasAMatchingRecord_ShouldNotReturnIt()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-otheruser-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
ConsumptionStatisticsRepository sut = new(context);
Guid userId = Guid.NewGuid();
Guid otherUserId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
DateTime startedOnUtc = new(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc);
MediaConsumptionRecordEntity userRecord = _mediaConsumptionRecordEntityFixture.Create(
userId: userId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: startedOnUtc);
MediaConsumptionRecordEntity otherUserRecord = _mediaConsumptionRecordEntityFixture.Create(
userId: otherUserId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: startedOnUtc);
context.Users.AddRange(_userEntityFixture.Create(id: userId), _userEntityFixture.Create(id: otherUserId));
context.MediaConsumptionRecords.AddRange(userRecord, otherUserRecord);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
// Every other filter matches the foreign record too, so the user scope has to be the reason it is excluded.
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await sut.GetForUserAsync(
userId, libraryId, MediaKind.Movie, startedOnUtc.AddDays(-1), startedOnUtc.AddDays(1), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
MediaConsumptionRecordEntity returnedRecord = Assert.Single(result.Value);
Assert.Equal(userRecord.Id, returnedRecord.Id);
Assert.Equal(userId, returnedRecord.UserId);
}
[Fact]
public async Task GetForUserAsync_WhenTheRangeBoundariesMatchExactly_ShouldIncludeTheBoundaryRecords()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-boundary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
ConsumptionStatisticsRepository sut = new(context);
Guid userId = Guid.NewGuid();
DateTime fromUtc = new(2025, 1, 10, 12, 0, 0, DateTimeKind.Utc);
DateTime toUtc = new(2025, 1, 20, 12, 0, 0, DateTimeKind.Utc);
MediaConsumptionRecordEntity recordBeforeTheRange = _mediaConsumptionRecordEntityFixture.Create(
userId: userId, startedOnUtc: fromUtc.AddMilliseconds(-1));
MediaConsumptionRecordEntity recordAtTheStartBoundary = _mediaConsumptionRecordEntityFixture.Create(
userId: userId, startedOnUtc: fromUtc);
MediaConsumptionRecordEntity recordInsideTheRange = _mediaConsumptionRecordEntityFixture.Create(
userId: userId, startedOnUtc: fromUtc.AddDays(5));
MediaConsumptionRecordEntity recordAtTheEndBoundary = _mediaConsumptionRecordEntityFixture.Create(
userId: userId, startedOnUtc: toUtc);
MediaConsumptionRecordEntity recordAfterTheRange = _mediaConsumptionRecordEntityFixture.Create(
userId: userId, startedOnUtc: toUtc.AddMilliseconds(1));
context.Users.Add(_userEntityFixture.Create(id: userId));
context.MediaConsumptionRecords.AddRange(
recordBeforeTheRange, recordAtTheStartBoundary, recordInsideTheRange, recordAtTheEndBoundary, recordAfterTheRange);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await sut.GetForUserAsync(userId, null, null, fromUtc, toUtc, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(3, result.Value.Count);
Assert.Contains(result.Value, record => record.Id == recordAtTheStartBoundary.Id);
Assert.Contains(result.Value, record => record.Id == recordInsideTheRange.Id);
Assert.Contains(result.Value, record => record.Id == recordAtTheEndBoundary.Id);
Assert.DoesNotContain(result.Value, record => record.Id == recordBeforeTheRange.Id);
Assert.DoesNotContain(result.Value, record => record.Id == recordAfterTheRange.Id);
}
[Fact]
public async Task GetForUserAsync_WhenAllFiltersAreProvided_ShouldApplyEveryFilter()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-allfilters-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
ConsumptionStatisticsRepository sut = new(context);
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 recordOutsideTheRange = _mediaConsumptionRecordEntityFixture.Create(
userId: userId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: toUtc.AddDays(1));
context.Users.Add(_userEntityFixture.Create(id: userId));
context.MediaConsumptionRecords.AddRange(matchingRecord, recordOfAnotherLibrary, recordOfAnotherKind, recordOutsideTheRange);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// 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
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-emptymatch-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
ConsumptionStatisticsRepository sut = new(context);
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));
context.Users.Add(_userEntityFixture.Create(id: userId));
context.MediaConsumptionRecords.Add(record);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// 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 GetForUserAsync_WhenCalled_ShouldReturnDetachedRecordsAndAllowRepeatedReads()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
ConsumptionStatisticsRepository sut = new(context);
Guid userId = Guid.NewGuid();
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
context.Users.Add(_userEntityFixture.Create(id: userId));
context.MediaConsumptionRecords.Add(record);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
Result<IReadOnlyList<MediaConsumptionRecordEntity>> firstResult = await sut.GetForUserAsync(userId, null, null, null, null, CancellationToken.None);
Result<IReadOnlyList<MediaConsumptionRecordEntity>> secondResult = await sut.GetForUserAsync(userId, null, null, null, null, CancellationToken.None);
// Assert
Assert.False(firstResult.IsFailure);
Assert.False(secondResult.IsFailure);
// The read is untracked, so the context never holds the returned statistics records, and a second read works the same way.
Assert.Empty(context.ChangeTracker.Entries<MediaConsumptionRecordEntity>());
Assert.Equal(EntityState.Detached, context.Entry(firstResult.Value.Single()).State);
MediaConsumptionRecordEntity firstReturnedRecord = Assert.Single(firstResult.Value);
MediaConsumptionRecordEntity secondReturnedRecord = Assert.Single(secondResult.Value);
Assert.Equal(record.Id, firstReturnedRecord.Id);
Assert.Equal(record.Id, secondReturnedRecord.Id);
Assert.Empty(context.ChangeTracker.Entries<MediaConsumptionRecordEntity>());
}
[Fact]
public async Task GetForAllUsersAsync_WhenCalled_ShouldReturnTheRecordsOfEveryUser()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-allusers-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
ConsumptionStatisticsRepository sut = new(context);
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);
context.Users.AddRange(_userEntityFixture.Create(id: firstUserId), _userEntityFixture.Create(id: secondUserId));
context.MediaConsumptionRecords.AddRange(firstUserRecord, secondUserMovieRecord, secondUserBookRecord);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// 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_WhenAllFiltersAreProvided_ShouldApplyEveryFilterAcrossUsers()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-allusers-filters-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
ConsumptionStatisticsRepository sut = new(context);
Guid firstUserId = Guid.NewGuid();
Guid secondUserId = 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 matchingFirstUserRecord = _mediaConsumptionRecordEntityFixture.Create(
userId: firstUserId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
MediaConsumptionRecordEntity matchingSecondUserRecord = _mediaConsumptionRecordEntityFixture.Create(
userId: secondUserId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 16, 0, 0, 0, DateTimeKind.Utc));
MediaConsumptionRecordEntity recordOfAnotherLibrary = _mediaConsumptionRecordEntityFixture.Create(
userId: firstUserId, libraryId: Guid.NewGuid(), mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
MediaConsumptionRecordEntity recordOfAnotherKind = _mediaConsumptionRecordEntityFixture.Create(
userId: secondUserId, libraryId: libraryId, mediaKind: MediaKind.Book, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
MediaConsumptionRecordEntity recordOutsideTheRange = _mediaConsumptionRecordEntityFixture.Create(
userId: secondUserId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: toUtc.AddDays(1));
context.Users.AddRange(_userEntityFixture.Create(id: firstUserId), _userEntityFixture.Create(id: secondUserId));
context.MediaConsumptionRecords.AddRange(
matchingFirstUserRecord, matchingSecondUserRecord, recordOfAnotherLibrary, recordOfAnotherKind, recordOutsideTheRange);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// 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);
// The filters are applied across every user, instead of one user at a time.
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
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-allusers-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
ConsumptionStatisticsRepository sut = new(context);
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));
context.Users.Add(_userEntityFixture.Create(id: userId));
context.MediaConsumptionRecords.Add(record);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// 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);
}
/// <summary>
/// Creates a real SQLite backed context, so that the stored rows are read exactly as they were written.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateContext(SqliteConnection anchorConnection)
{
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.Options);
context.Database.EnsureCreated();
return context;
}
}
@@ -0,0 +1,640 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Common.Interceptors;
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.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
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.IntegrationTests.Core.Repositories.MediaConsumption;
/// <summary>
/// Contains integration tests for the <see cref="MediaConsumptionRecordRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaConsumptionRecordRepositoryTests
{
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
[Fact]
public async Task InsertAsync_WhenRecordsAreNew_ShouldPersistEveryStoredColumn()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaconsumptionrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaConsumptionRecordRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
Guid libraryId = Guid.NewGuid();
Guid timeOffsetMediaItemId = Guid.NewGuid();
Guid locationMediaItemId = Guid.NewGuid();
DateTime timeOffsetStartedOnUtc = new(2025, 1, 1, 8, 0, 0, DateTimeKind.Utc);
DateTime timeOffsetLastActivityOnUtc = new(2025, 1, 1, 8, 45, 0, DateTimeKind.Utc);
DateTime timeOffsetEndedOnUtc = new(2025, 1, 1, 9, 0, 0, DateTimeKind.Utc);
MediaConsumptionRecordEntity timeOffsetRecord = _mediaConsumptionRecordEntityFixture.Create(
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.Movie,
mediaItemId: timeOffsetMediaItemId,
status: ConsumptionStatus.Completed,
startedOnUtc: timeOffsetStartedOnUtc,
lastActivityOnUtc: timeOffsetLastActivityOnUtc,
endedOnUtc: timeOffsetEndedOnUtc,
consumedDurationMilliseconds: 1_800_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 1_234_567,
includeLastPositionLocation: false,
lastProgressFraction: 0.42,
consecutivePagesRead: 0,
version: 7);
MediaConsumptionRecordEntity locationRecord = _mediaConsumptionRecordEntityFixture.Create(
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.Book,
mediaItemId: locationMediaItemId,
status: ConsumptionStatus.InProgress,
startedOnUtc: new(2025, 1, 1, 10, 0, 0, DateTimeKind.Utc),
lastActivityOnUtc: new(2025, 1, 1, 10, 20, 0, DateTimeKind.Utc),
includeEndedOnUtc: false,
consumedDurationMilliseconds: 90_000,
lastPositionKind: MediaPositionKind.Location,
includeLastPositionTimeOffsetMilliseconds: false,
lastPositionLocation: "chapter-3:paragraph-14",
lastProgressFraction: 0.17,
consecutivePagesRead: 12,
version: 1);
// Act
Result<Created> timeOffsetResult = await sut.InsertAsync(timeOffsetRecord, CancellationToken.None);
Result<Created> locationResult = await sut.InsertAsync(locationRecord, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(timeOffsetResult.IsFailure);
Assert.Equal(Result.Created, timeOffsetResult.Value);
Assert.False(locationResult.IsFailure);
Assert.Equal(Result.Created, locationResult.Value);
// A fresh context round-trips the stored rows, which proves the values went through the real provider instead of the identity map.
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
MediaConsumptionRecordEntity storedTimeOffsetRecord = await verificationContext.MediaConsumptionRecords
.AsNoTracking()
.SingleAsync(record => record.Id == timeOffsetRecord.Id);
Assert.Equal(userId, storedTimeOffsetRecord.UserId);
Assert.Equal(libraryId, storedTimeOffsetRecord.LibraryId);
Assert.Equal(MediaKind.Movie, storedTimeOffsetRecord.MediaKind);
Assert.Equal(timeOffsetMediaItemId, storedTimeOffsetRecord.MediaItemId);
Assert.Equal(ConsumptionStatus.Completed, storedTimeOffsetRecord.Status);
Assert.Equal(timeOffsetStartedOnUtc, storedTimeOffsetRecord.StartedOnUtc);
Assert.Equal(timeOffsetLastActivityOnUtc, storedTimeOffsetRecord.LastActivityOnUtc);
Assert.Equal(timeOffsetEndedOnUtc, storedTimeOffsetRecord.EndedOnUtc);
Assert.Equal(1_800_000L, storedTimeOffsetRecord.ConsumedDurationMilliseconds);
Assert.Equal(MediaPositionKind.TimeOffset, storedTimeOffsetRecord.LastPositionKind);
Assert.Equal(1_234_567L, storedTimeOffsetRecord.LastPositionTimeOffsetMilliseconds);
Assert.Null(storedTimeOffsetRecord.LastPositionLocation);
Assert.Equal(0.42, storedTimeOffsetRecord.LastProgressFraction);
Assert.Equal(0, storedTimeOffsetRecord.ConsecutivePagesRead);
Assert.Equal(7L, storedTimeOffsetRecord.Version);
// The audit interceptor owns the creation columns.
Assert.Equal(utcNow, storedTimeOffsetRecord.CreatedOnUtc);
Assert.Equal(userId, storedTimeOffsetRecord.CreatedBy);
Assert.Null(storedTimeOffsetRecord.UpdatedOnUtc);
Assert.Null(storedTimeOffsetRecord.UpdatedBy);
MediaConsumptionRecordEntity storedLocationRecord = await verificationContext.MediaConsumptionRecords
.AsNoTracking()
.SingleAsync(record => record.Id == locationRecord.Id);
Assert.Equal(MediaKind.Book, storedLocationRecord.MediaKind);
Assert.Equal(ConsumptionStatus.InProgress, storedLocationRecord.Status);
Assert.Null(storedLocationRecord.EndedOnUtc);
Assert.Equal(MediaPositionKind.Location, storedLocationRecord.LastPositionKind);
Assert.Null(storedLocationRecord.LastPositionTimeOffsetMilliseconds);
Assert.Equal("chapter-3:paragraph-14", storedLocationRecord.LastPositionLocation);
Assert.Equal(0.17, storedLocationRecord.LastProgressFraction);
Assert.Equal(12, storedLocationRecord.ConsecutivePagesRead);
// The enums are stored as their names, not as their numeric values.
(string timeOffsetMediaKind, string timeOffsetStatus) = await ReadStoredEnumColumnsAsync(verificationContext, timeOffsetRecord.Id);
Assert.Equal(nameof(MediaKind.Movie), timeOffsetMediaKind);
Assert.Equal(nameof(ConsumptionStatus.Completed), timeOffsetStatus);
(string locationMediaKind, string locationStatus) = await ReadStoredEnumColumnsAsync(verificationContext, locationRecord.Id);
Assert.Equal(nameof(MediaKind.Book), locationMediaKind);
Assert.Equal(nameof(ConsumptionStatus.InProgress), locationStatus);
}
[Fact]
public async Task GetByIdForUserAsync_WhenTheRecordBelongsToTheUser_ShouldReturnTheStoredRecord()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaconsumptionrepo-get-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaConsumptionRecordRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
userId: userId,
mediaKind: MediaKind.Movie,
lastProgressFraction: 0.3);
context.MediaConsumptionRecords.Add(record);
await context.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(record.MediaItemId, result.Value.MediaItemId);
Assert.Equal(record.LibraryId, result.Value.LibraryId);
Assert.Equal(0.3, result.Value.LastProgressFraction);
Assert.Equal(EntityState.Unchanged, context.Entry(result.Value).State);
}
[Fact]
public async Task GetByIdForUserAsync_WhenTheRecordBelongsToAnotherUser_ShouldReturnNull()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaconsumptionrepo-get-other-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
Guid otherUserId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaConsumptionRecordRepository sut = new(context);
context.Users.AddRange(_userEntityFixture.Create(id: userId), _userEntityFixture.Create(id: otherUserId));
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
context.MediaConsumptionRecords.Add(record);
await context.SaveChangesAsync();
// Act
Result<MediaConsumptionRecordEntity?> result = await sut.GetByIdForUserAsync(record.Id, otherUserId, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByIdForUserAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnADetachedInstance()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaconsumptionrepo-get-detached-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaConsumptionRecordRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
context.MediaConsumptionRecords.Add(record);
await context.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.False(ReferenceEquals(record, result.Value));
Assert.Equal(EntityState.Detached, context.Entry(result.Value!).State);
Assert.Equal(EntityState.Unchanged, context.Entry(record).State);
}
[Fact]
public async Task UpdateForUserAsync_WhenNothingChanged_ShouldNotWriteOrBumpTheVersion()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaconsumptionrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
DateTime laterUtcNow = new(2025, 1, 1, 13, 0, 0, DateTimeKind.Utc);
MediaConsumptionRecordEntity record;
long storedVersion;
using (LuminaDbContext seedContext = CreateAuditedContext(anchorConnection, userId, utcNow))
{
seedContext.Users.Add(_userEntityFixture.Create(id: userId));
record = _mediaConsumptionRecordEntityFixture.Create(userId: userId, mediaKind: MediaKind.Movie, lastProgressFraction: 0.4);
seedContext.MediaConsumptionRecords.Add(record);
await seedContext.SaveChangesAsync();
storedVersion = record.Version;
}
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, laterUtcNow);
MediaConsumptionRecordRepository sut = new(context);
// A detached copy is the shape the command mapping produces for an update, so this is a real no-op round-trip.
MediaConsumptionRecordEntity incoming = await context.MediaConsumptionRecords
.AsNoTracking()
.SingleAsync(candidate => candidate.Id == record.Id);
// Act
Result<Updated> result = await sut.UpdateForUserAsync(incoming, userId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
Assert.DoesNotContain(context.ChangeTracker.Entries<MediaConsumptionRecordEntity>(), entry => entry.State == EntityState.Modified);
await context.SaveChangesAsync();
MediaConsumptionRecordEntity storedRecord = await context.MediaConsumptionRecords
.AsNoTracking()
.SingleAsync(candidate => candidate.Id == record.Id);
Assert.Equal(storedVersion, storedRecord.Version);
Assert.Equal(0.4, storedRecord.LastProgressFraction);
Assert.Equal(utcNow, storedRecord.CreatedOnUtc);
Assert.Null(storedRecord.UpdatedOnUtc);
Assert.Null(storedRecord.UpdatedBy);
}
[Fact]
public async Task UpdateForUserAsync_WhenEditableValuesChanged_ShouldIncrementTheVersionAndStampTheAudit()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaconsumptionrepo-update-changed-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
DateTime laterUtcNow = new(2025, 1, 1, 13, 0, 0, DateTimeKind.Utc);
Guid libraryId = Guid.NewGuid();
Guid mediaItemId = Guid.NewGuid();
DateTime startedOnUtc = new(2025, 1, 1, 8, 0, 0, DateTimeKind.Utc);
MediaConsumptionRecordEntity record;
long storedVersion;
using (LuminaDbContext seedContext = CreateAuditedContext(anchorConnection, userId, utcNow))
{
seedContext.Users.Add(_userEntityFixture.Create(id: userId));
record = _mediaConsumptionRecordEntityFixture.Create(
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId,
status: ConsumptionStatus.InProgress,
startedOnUtc: startedOnUtc,
lastActivityOnUtc: startedOnUtc.AddMinutes(10),
includeEndedOnUtc: false,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 30_000,
includeLastPositionLocation: false,
lastProgressFraction: 0.5,
consecutivePagesRead: 0,
version: 3);
seedContext.MediaConsumptionRecords.Add(record);
await seedContext.SaveChangesAsync();
storedVersion = record.Version;
}
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, laterUtcNow);
MediaConsumptionRecordRepository sut = new(context);
DateTime endedOnUtc = new(2025, 1, 1, 11, 0, 0, DateTimeKind.Utc);
MediaConsumptionRecordEntity incoming = _mediaConsumptionRecordEntityFixture.Create(
id: record.Id,
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: storedVersion);
// Act
Result<Updated> result = await sut.UpdateForUserAsync(incoming, userId, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
MediaConsumptionRecordEntity storedRecord = await context.MediaConsumptionRecords
.AsNoTracking()
.SingleAsync(candidate => candidate.Id == record.Id);
// The stored identity is preserved even when the incoming record carries different values for it.
Assert.Equal(userId, storedRecord.UserId);
Assert.Equal(libraryId, storedRecord.LibraryId);
Assert.Equal(MediaKind.Movie, storedRecord.MediaKind);
Assert.Equal(mediaItemId, storedRecord.MediaItemId);
Assert.Equal(startedOnUtc, storedRecord.StartedOnUtc);
// The editable values are copied from the incoming record.
Assert.Equal(ConsumptionStatus.Completed, storedRecord.Status);
Assert.Equal(new DateTime(2025, 1, 1, 10, 55, 0, DateTimeKind.Utc), storedRecord.LastActivityOnUtc);
Assert.Equal(endedOnUtc, storedRecord.EndedOnUtc);
Assert.Equal(600_000L, storedRecord.ConsumedDurationMilliseconds);
Assert.Equal(MediaPositionKind.Location, storedRecord.LastPositionKind);
Assert.Null(storedRecord.LastPositionTimeOffsetMilliseconds);
Assert.Equal("chapter-12", storedRecord.LastPositionLocation);
Assert.Equal(1.0, storedRecord.LastProgressFraction);
Assert.Equal(42, storedRecord.ConsecutivePagesRead);
// The version is incremented by exactly one, and the audit interceptor stamps the modification columns.
Assert.Equal(storedVersion + 1, storedRecord.Version);
Assert.Equal(utcNow, storedRecord.CreatedOnUtc);
Assert.Equal(userId, storedRecord.CreatedBy);
Assert.Equal(laterUtcNow, storedRecord.UpdatedOnUtc);
Assert.Equal(userId, storedRecord.UpdatedBy);
}
[Fact]
public async Task UpdateForUserAsync_WhenAnotherContextAlreadyBumpedTheVersion_ShouldThrowDbUpdateConcurrencyException()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaconsumptionrepo-update-concurrency-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
DateTime laterUtcNow = new(2025, 1, 1, 13, 0, 0, DateTimeKind.Utc);
MediaConsumptionRecordEntity record;
using (LuminaDbContext seedContext = CreateAuditedContext(anchorConnection, userId, utcNow))
{
seedContext.Users.Add(_userEntityFixture.Create(id: userId));
record = _mediaConsumptionRecordEntityFixture.Create(
userId: userId,
lastProgressFraction: 0.2,
includeEndedOnUtc: false,
status: ConsumptionStatus.InProgress,
version: 4);
seedContext.MediaConsumptionRecords.Add(record);
await seedContext.SaveChangesAsync();
}
using LuminaDbContext firstContext = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaConsumptionRecordRepository firstSut = new(firstContext);
Result<MediaConsumptionRecordEntity?> readResult = await firstSut.GetByIdForUserAsync(record.Id, userId, cancellationToken: CancellationToken.None);
Assert.False(readResult.IsFailure);
Assert.NotNull(readResult.Value);
using LuminaDbContext secondContext = CreateAuditedContext(anchorConnection, userId, laterUtcNow);
MediaConsumptionRecordRepository secondSut = new(secondContext);
MediaConsumptionRecordEntity secondIncoming = _mediaConsumptionRecordEntityFixture.Create(
id: record.Id,
userId: userId,
status: ConsumptionStatus.Stopped,
endedOnUtc: new(2025, 1, 1, 12, 30, 0, DateTimeKind.Utc),
lastProgressFraction: 0.8,
version: 4);
Result<Updated> secondUpdateResult = await secondSut.UpdateForUserAsync(secondIncoming, userId, CancellationToken.None);
Assert.False(secondUpdateResult.IsFailure);
await secondContext.SaveChangesAsync();
// The first context still holds the instance it read before the second writer committed its own version.
MediaConsumptionRecordEntity firstIncoming = _mediaConsumptionRecordEntityFixture.Create(
id: record.Id,
userId: userId,
status: ConsumptionStatus.Completed,
endedOnUtc: new(2025, 1, 1, 12, 45, 0, DateTimeKind.Utc),
lastProgressFraction: 1.0,
version: 4);
Result<Updated> firstUpdateResult = await firstSut.UpdateForUserAsync(firstIncoming, userId, CancellationToken.None);
Assert.False(firstUpdateResult.IsFailure);
// Act
DbUpdateConcurrencyException exception = await Assert.ThrowsAsync<DbUpdateConcurrencyException>(() => firstContext.SaveChangesAsync());
// Assert
Assert.NotNull(exception);
// The stale writer did not overwrite the row the other context already committed.
secondContext.ChangeTracker.Clear();
MediaConsumptionRecordEntity storedRecord = await secondContext.MediaConsumptionRecords
.AsNoTracking()
.SingleAsync(candidate => candidate.Id == record.Id);
Assert.Equal(ConsumptionStatus.Stopped, storedRecord.Status);
Assert.Equal(0.8, storedRecord.LastProgressFraction);
Assert.Equal(5L, storedRecord.Version);
Assert.Equal(laterUtcNow, storedRecord.UpdatedOnUtc);
}
[Fact]
public async Task DeleteForUserAsync_WhenTheRecordBelongsToTheUser_ShouldDeleteOnlyThatRow()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaconsumptionrepo-delete-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
Guid otherUserId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaConsumptionRecordRepository sut = new(context);
context.Users.AddRange(_userEntityFixture.Create(id: userId), _userEntityFixture.Create(id: otherUserId));
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
MediaConsumptionRecordEntity otherUserRecord = _mediaConsumptionRecordEntityFixture.Create(userId: otherUserId);
context.MediaConsumptionRecords.AddRange(record, otherUserRecord);
await context.SaveChangesAsync();
// Act
Result<Deleted> result = await sut.DeleteForUserAsync(record.Id, userId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
Assert.Equal(EntityState.Deleted, context.Entry(record).State);
await context.SaveChangesAsync();
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
Assert.False(await verificationContext.MediaConsumptionRecords.AsNoTracking().AnyAsync(candidate => candidate.Id == record.Id));
Assert.True(await verificationContext.MediaConsumptionRecords.AsNoTracking().AnyAsync(candidate => candidate.Id == otherUserRecord.Id));
}
[Fact]
public async Task DeleteAllByMediaItemIdForUserAsync_WhenRecordsMatchAllFourParts_ShouldRemoveOnlyTheMatchingRecords()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaconsumptionrepo-delete-item-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
Guid otherUserId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaConsumptionRecordRepository sut = new(context);
context.Users.AddRange(_userEntityFixture.Create(id: userId), _userEntityFixture.Create(id: otherUserId));
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);
context.MediaConsumptionRecords.AddRange(matchingFirst, matchingSecond, otherUser, otherKind, otherItem, otherLibrary);
await context.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);
await context.SaveChangesAsync();
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
List<Guid> remainingRecordIds = await verificationContext.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 DeleteAllForUserAsync_WhenTheUserHasRecords_ShouldRemoveOnlyTheirRecords()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaconsumptionrepo-delete-user-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
Guid otherUserId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaConsumptionRecordRepository sut = new(context);
context.Users.AddRange(_userEntityFixture.Create(id: userId), _userEntityFixture.Create(id: otherUserId));
MediaConsumptionRecordEntity firstRecord = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
MediaConsumptionRecordEntity secondRecord = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
MediaConsumptionRecordEntity otherUserRecord = _mediaConsumptionRecordEntityFixture.Create(userId: otherUserId);
context.MediaConsumptionRecords.AddRange(firstRecord, secondRecord, otherUserRecord);
await context.SaveChangesAsync();
// Act
Result<Deleted> result = await sut.DeleteAllForUserAsync(userId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
await context.SaveChangesAsync();
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
List<Guid> remainingRecordIds = await verificationContext.MediaConsumptionRecords
.AsNoTracking()
.Select(record => record.Id)
.ToListAsync();
Assert.Equal([otherUserRecord.Id], remainingRecordIds);
}
[Fact]
public async Task UserDeletion_WhenTheUserOwnsConsumptionRecords_ShouldCascadeToTheRecords()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaconsumptionrepo-cascade-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
UserEntity user = _userEntityFixture.Create(id: userId);
context.Users.Add(user);
MediaConsumptionRecordEntity firstRecord = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
MediaConsumptionRecordEntity secondRecord = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
context.MediaConsumptionRecords.AddRange(firstRecord, secondRecord);
await context.SaveChangesAsync();
// A real deletion starts with nothing tracked, so the database cascade is the path that has to remove the records.
context.ChangeTracker.Clear();
// Act
UserEntity storedUser = await context.Users.SingleAsync(candidate => candidate.Id == userId);
context.Users.Remove(storedUser);
await context.SaveChangesAsync();
// Assert
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
Assert.False(await verificationContext.MediaConsumptionRecords.AsNoTracking().AnyAsync(record => record.UserId == userId));
}
/// <summary>
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <param name="userId">The Id of the user reported as the current user.</param>
/// <param name="utcNow">The current UTC time reported by the time provider.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow)
{
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
currentUserService.UserId.Returns(userId);
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
dateTimeProvider.UtcNow.Returns(utcNow);
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
.Options);
context.Database.EnsureCreated();
return context;
}
/// <summary>
/// Creates a real SQLite backed context without the auditing interceptor, so that stored values are read exactly as they were written.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateContext(SqliteConnection anchorConnection)
{
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.Options);
context.Database.EnsureCreated();
return context;
}
/// <summary>
/// Reads the raw stored text of the enum columns of a consumption record, which proves the enum to string conversion is applied by the provider.
/// </summary>
/// <param name="context">The context to read through.</param>
/// <param name="recordId">The Id of the record to read.</param>
/// <returns>The stored media kind and status names.</returns>
private static async Task<(string MediaKind, string Status)> ReadStoredEnumColumnsAsync(LuminaDbContext context, Guid recordId)
{
string mediaKind = await context.Database
.SqlQueryRaw<string>("SELECT MediaKind AS \"Value\" FROM MediaConsumptionRecords WHERE Id = {0}", recordId)
.SingleAsync();
string status = await context.Database
.SqlQueryRaw<string>("SELECT Status AS \"Value\" FROM MediaConsumptionRecords WHERE Id = {0}", recordId)
.SingleAsync();
return (mediaKind, status);
}
}
@@ -0,0 +1,583 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Common.Interceptors;
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.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
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.IntegrationTests.Core.Repositories.MediaConsumption;
/// <summary>
/// Contains integration tests for the <see cref="MediaResumePointRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaResumePointRepositoryTests
{
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
[Fact]
public async Task UpsertForUserAsync_WhenTheResumePointDoesNotExist_ShouldInsertItWithTheAuthoritativeOwner()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaresumerepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaResumePointRepository sut = new(context);
// The owner carried by the incoming resume point is deliberately different from the authoritative owner argument.
MediaResumePointEntity incoming = _mediaResumePointEntityFixture.Create(
userId: Guid.NewGuid(),
libraryId: Guid.NewGuid(),
mediaKind: MediaKind.Movie,
mediaItemId: Guid.NewGuid(),
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 120_000,
includeLastPositionLocation: false,
lastProgressFraction: 0.25,
version: 2);
context.Users.Add(_userEntityFixture.Create(id: userId));
// Act
Result<Updated> result = await sut.UpsertForUserAsync(incoming, userId, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
MediaResumePointEntity storedResumePoint = await verificationContext.MediaResumePoints
.AsNoTracking()
.SingleAsync();
Assert.Equal(userId, storedResumePoint.UserId);
Assert.Equal(incoming.LibraryId, storedResumePoint.LibraryId);
Assert.Equal(MediaKind.Movie, storedResumePoint.MediaKind);
Assert.Equal(incoming.MediaItemId, storedResumePoint.MediaItemId);
Assert.Equal(MediaPositionKind.TimeOffset, storedResumePoint.LastPositionKind);
Assert.Equal(120_000L, storedResumePoint.LastPositionTimeOffsetMilliseconds);
Assert.Null(storedResumePoint.LastPositionLocation);
Assert.Equal(0.25, storedResumePoint.LastProgressFraction);
Assert.Equal(2L, storedResumePoint.Version);
Assert.Equal(utcNow, storedResumePoint.CreatedOnUtc);
Assert.Equal(userId, storedResumePoint.CreatedBy);
Assert.Null(storedResumePoint.UpdatedOnUtc);
Assert.Null(storedResumePoint.UpdatedBy);
}
[Fact]
public async Task UpsertForUserAsync_WhenCalledTwiceForTheSameMediaItem_ShouldUpdateTheExistingRow()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaresumerepo-upsert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
DateTime laterUtcNow = new(2025, 1, 1, 13, 0, 0, DateTimeKind.Utc);
Guid mediaItemId = Guid.NewGuid();
Guid resumePointId;
long firstVersion;
Guid libraryId;
using (LuminaDbContext seedContext = CreateAuditedContext(anchorConnection, userId, utcNow))
{
MediaResumePointRepository seedSut = new(seedContext);
seedContext.Users.Add(_userEntityFixture.Create(id: userId));
MediaResumePointEntity firstIncoming = _mediaResumePointEntityFixture.Create(
userId: userId,
libraryId: Guid.NewGuid(),
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
includeLastPositionLocation: false,
lastProgressFraction: 0.25,
version: 4);
Result<Updated> firstResult = await seedSut.UpsertForUserAsync(firstIncoming, userId, CancellationToken.None);
Assert.False(firstResult.IsFailure);
await seedContext.SaveChangesAsync();
resumePointId = firstIncoming.Id;
firstVersion = firstIncoming.Version;
libraryId = firstIncoming.LibraryId;
}
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, laterUtcNow);
MediaResumePointRepository sut = new(context);
MediaResumePointEntity secondIncoming = _mediaResumePointEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: Guid.NewGuid(),
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 300_000,
includeLastPositionLocation: false,
lastProgressFraction: 0.75,
version: firstVersion);
// Act
Result<Updated> result = await sut.UpsertForUserAsync(secondIncoming, userId, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
MediaResumePointEntity storedResumePoint = await verificationContext.MediaResumePoints
.AsNoTracking()
.SingleAsync();
// The unique business key keeps the row count at one and preserves the stored identity and creation audit.
Assert.Equal(resumePointId, storedResumePoint.Id);
Assert.Equal(userId, storedResumePoint.UserId);
Assert.Equal(MediaKind.Movie, storedResumePoint.MediaKind);
Assert.Equal(mediaItemId, storedResumePoint.MediaItemId);
Assert.Equal(utcNow, storedResumePoint.CreatedOnUtc);
Assert.Equal(userId, storedResumePoint.CreatedBy);
// The editable values are advanced by the second save.
Assert.Equal(secondIncoming.LibraryId, storedResumePoint.LibraryId);
Assert.NotEqual(libraryId, storedResumePoint.LibraryId);
Assert.Equal(300_000L, storedResumePoint.LastPositionTimeOffsetMilliseconds);
Assert.Equal(0.75, storedResumePoint.LastProgressFraction);
Assert.Equal(firstVersion + 1, storedResumePoint.Version);
Assert.Equal(laterUtcNow, storedResumePoint.UpdatedOnUtc);
Assert.Equal(userId, storedResumePoint.UpdatedBy);
}
[Fact]
public async Task UpsertForUserAsync_WhenADuplicateIsInsertedDirectly_ShouldBeRejectedByTheUniqueIndex()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaresumerepo-duplicate-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
context.Users.Add(_userEntityFixture.Create(id: userId));
Guid mediaItemId = Guid.NewGuid();
MediaResumePointEntity storedResumePoint = _mediaResumePointEntityFixture.Create(
userId: userId,
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId);
context.MediaResumePoints.Add(storedResumePoint);
await context.SaveChangesAsync();
MediaResumePointEntity duplicateResumePoint = _mediaResumePointEntityFixture.Create(
userId: userId,
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId);
context.MediaResumePoints.Add(duplicateResumePoint);
// Act
DbUpdateException exception = await Assert.ThrowsAsync<DbUpdateException>(() => context.SaveChangesAsync());
// Assert
Assert.NotNull(exception);
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
Assert.Equal(1, await verificationContext.MediaResumePoints.AsNoTracking().CountAsync(resumePoint => resumePoint.UserId == userId && resumePoint.MediaItemId == mediaItemId));
}
[Fact]
public async Task UpsertForUserAsync_WhenNothingChanged_ShouldNotBumpTheVersionOrStampTheAudit()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaresumerepo-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
DateTime laterUtcNow = new(2025, 1, 1, 13, 0, 0, DateTimeKind.Utc);
Guid mediaItemId = Guid.NewGuid();
long storedVersion;
using (LuminaDbContext seedContext = CreateAuditedContext(anchorConnection, userId, utcNow))
{
seedContext.Users.Add(_userEntityFixture.Create(id: userId));
MediaResumePointEntity storedResumePoint = _mediaResumePointEntityFixture.Create(
userId: userId,
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 90_000,
includeLastPositionLocation: false,
lastProgressFraction: 0.4,
version: 3);
seedContext.MediaResumePoints.Add(storedResumePoint);
await seedContext.SaveChangesAsync();
storedVersion = storedResumePoint.Version;
}
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, laterUtcNow);
MediaResumePointRepository sut = new(context);
// A detached copy is the shape the command mapping produces for a save, so this is a real no-op round-trip.
MediaResumePointEntity incoming = await context.MediaResumePoints
.AsNoTracking()
.SingleAsync(resumePoint => resumePoint.UserId == userId && resumePoint.MediaItemId == mediaItemId);
// Act
Result<Updated> result = await sut.UpsertForUserAsync(incoming, userId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
Assert.DoesNotContain(context.ChangeTracker.Entries<MediaResumePointEntity>(), entry => entry.State == EntityState.Modified);
await context.SaveChangesAsync();
MediaResumePointEntity storedResumePointAfterSave = await context.MediaResumePoints
.AsNoTracking()
.SingleAsync(resumePoint => resumePoint.UserId == userId && resumePoint.MediaItemId == mediaItemId);
Assert.Equal(storedVersion, storedResumePointAfterSave.Version);
Assert.Equal(0.4, storedResumePointAfterSave.LastProgressFraction);
Assert.Null(storedResumePointAfterSave.UpdatedOnUtc);
Assert.Null(storedResumePointAfterSave.UpdatedBy);
}
[Fact]
public async Task GetForUserAndMediaItemAsync_WhenTheResumePointMatchesUserKindAndItem_ShouldReturnTheStoredResumePoint()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaresumerepo-get-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaResumePointRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
Guid mediaItemId = Guid.NewGuid();
MediaResumePointEntity resumePoint = _mediaResumePointEntityFixture.Create(
userId: userId,
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId,
lastProgressFraction: 0.6);
context.MediaResumePoints.Add(resumePoint);
await context.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(0.6, result.Value.LastProgressFraction);
}
[Fact]
public async Task GetForUserAndMediaItemAsync_WhenTheUserKindOrItemDoesNotMatch_ShouldReturnNull()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaresumerepo-get-miss-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaResumePointRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
Guid mediaItemId = Guid.NewGuid();
MediaResumePointEntity resumePoint = _mediaResumePointEntityFixture.Create(
userId: userId,
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId);
context.MediaResumePoints.Add(resumePoint);
await context.SaveChangesAsync();
// Act
Result<MediaResumePointEntity?> otherUserResult = await sut.GetForUserAndMediaItemAsync(Guid.NewGuid(), MediaKind.Movie, mediaItemId, cancellationToken: CancellationToken.None);
Result<MediaResumePointEntity?> otherKindResult = await sut.GetForUserAndMediaItemAsync(userId, MediaKind.Book, mediaItemId, cancellationToken: CancellationToken.None);
Result<MediaResumePointEntity?> otherItemResult = await sut.GetForUserAndMediaItemAsync(userId, MediaKind.Movie, Guid.NewGuid(), cancellationToken: CancellationToken.None);
// Assert
Assert.False(otherUserResult.IsFailure);
Assert.Null(otherUserResult.Value);
Assert.False(otherKindResult.IsFailure);
Assert.Null(otherKindResult.Value);
Assert.False(otherItemResult.IsFailure);
Assert.Null(otherItemResult.Value);
}
[Fact]
public async Task GetForUserAndMediaItemAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnADetachedInstance()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaresumerepo-get-detached-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaResumePointRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
Guid mediaItemId = Guid.NewGuid();
MediaResumePointEntity resumePoint = _mediaResumePointEntityFixture.Create(
userId: userId,
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId);
context.MediaResumePoints.Add(resumePoint);
await context.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.False(ReferenceEquals(resumePoint, result.Value));
Assert.Equal(EntityState.Detached, context.Entry(result.Value!).State);
Assert.Equal(EntityState.Unchanged, context.Entry(resumePoint).State);
}
[Fact]
public async Task DeleteForUserAndMediaItemAsync_WhenTheResumePointMatches_ShouldDeleteOnlyThatRow()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaresumerepo-delete-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
Guid otherUserId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaResumePointRepository sut = new(context);
context.Users.AddRange(_userEntityFixture.Create(id: userId), _userEntityFixture.Create(id: otherUserId));
Guid mediaItemId = Guid.NewGuid();
Guid otherMediaItemId = Guid.NewGuid();
MediaResumePointEntity resumePoint = _mediaResumePointEntityFixture.Create(
userId: userId,
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId);
MediaResumePointEntity otherUserResumePoint = _mediaResumePointEntityFixture.Create(
userId: otherUserId,
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId);
MediaResumePointEntity otherItemResumePoint = _mediaResumePointEntityFixture.Create(
userId: userId,
mediaKind: MediaKind.Movie,
mediaItemId: otherMediaItemId);
context.MediaResumePoints.AddRange(resumePoint, otherUserResumePoint, otherItemResumePoint);
await context.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);
await context.SaveChangesAsync();
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
List<Guid> remainingResumePointIds = await verificationContext.MediaResumePoints
.AsNoTracking()
.Select(candidate => candidate.Id)
.ToListAsync();
Assert.Equal(
new[] { otherUserResumePoint.Id, otherItemResumePoint.Id }.OrderBy(id => id),
remainingResumePointIds.OrderBy(id => id));
}
[Fact]
public async Task DeleteAllForUserAsync_WhenTheUserHasResumePoints_ShouldRemoveOnlyTheirResumePoints()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaresumerepo-delete-user-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
Guid otherUserId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaResumePointRepository sut = new(context);
context.Users.AddRange(_userEntityFixture.Create(id: userId), _userEntityFixture.Create(id: otherUserId));
MediaResumePointEntity firstResumePoint = _mediaResumePointEntityFixture.Create(userId: userId, libraryId: Guid.NewGuid());
MediaResumePointEntity secondResumePoint = _mediaResumePointEntityFixture.Create(userId: userId, libraryId: Guid.NewGuid());
MediaResumePointEntity otherUserResumePoint = _mediaResumePointEntityFixture.Create(userId: otherUserId);
context.MediaResumePoints.AddRange(firstResumePoint, secondResumePoint, otherUserResumePoint);
await context.SaveChangesAsync();
// Act
Result<Deleted> result = await sut.DeleteAllForUserAsync(userId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
await context.SaveChangesAsync();
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
List<Guid> remainingResumePointIds = await verificationContext.MediaResumePoints
.AsNoTracking()
.Select(candidate => candidate.Id)
.ToListAsync();
Assert.Equal([otherUserResumePoint.Id], remainingResumePointIds);
}
[Fact]
public async Task DeleteAllForUserInLibraryAsync_WhenTheUserHasResumePointsInTheLibrary_ShouldRemoveOnlyThoseResumePoints()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaresumerepo-delete-library-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
Guid otherUserId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaResumePointRepository sut = new(context);
context.Users.AddRange(_userEntityFixture.Create(id: userId), _userEntityFixture.Create(id: otherUserId));
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: otherUserId, libraryId: libraryId);
context.MediaResumePoints.AddRange(matchingResumePoint, otherLibraryResumePoint, otherUserResumePoint);
await context.SaveChangesAsync();
// Act
Result<Deleted> result = await sut.DeleteAllForUserInLibraryAsync(userId, libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
await context.SaveChangesAsync();
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
List<Guid> remainingResumePointIds = await verificationContext.MediaResumePoints
.AsNoTracking()
.Select(candidate => candidate.Id)
.ToListAsync();
Assert.Equal(
new[] { otherLibraryResumePoint.Id, otherUserResumePoint.Id }.OrderBy(id => id),
remainingResumePointIds.OrderBy(id => id));
}
[Fact]
public async Task UpsertForUserAsync_WhenAnotherContextAlreadyBumpedTheVersion_ShouldThrowDbUpdateConcurrencyException()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaresumerepo-concurrency-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
DateTime laterUtcNow = new(2025, 1, 1, 13, 0, 0, DateTimeKind.Utc);
Guid mediaItemId = Guid.NewGuid();
using (LuminaDbContext seedContext = CreateAuditedContext(anchorConnection, userId, utcNow))
{
seedContext.Users.Add(_userEntityFixture.Create(id: userId));
MediaResumePointEntity storedResumePoint = _mediaResumePointEntityFixture.Create(
userId: userId,
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId,
lastProgressFraction: 0.2,
version: 4);
seedContext.MediaResumePoints.Add(storedResumePoint);
await seedContext.SaveChangesAsync();
}
using LuminaDbContext firstContext = CreateAuditedContext(anchorConnection, userId, utcNow);
MediaResumePointRepository firstSut = new(firstContext);
Result<MediaResumePointEntity?> readResult = await firstSut.GetForUserAndMediaItemAsync(userId, MediaKind.Movie, mediaItemId, cancellationToken: CancellationToken.None);
Assert.False(readResult.IsFailure);
Assert.NotNull(readResult.Value);
using LuminaDbContext secondContext = CreateAuditedContext(anchorConnection, userId, laterUtcNow);
MediaResumePointRepository secondSut = new(secondContext);
MediaResumePointEntity secondIncoming = _mediaResumePointEntityFixture.Create(
userId: userId,
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId,
lastProgressFraction: 0.8,
version: 4);
Result<Updated> secondResult = await secondSut.UpsertForUserAsync(secondIncoming, userId, CancellationToken.None);
Assert.False(secondResult.IsFailure);
await secondContext.SaveChangesAsync();
// The first context still holds the instance it read before the second writer committed its own version.
MediaResumePointEntity firstIncoming = _mediaResumePointEntityFixture.Create(
userId: userId,
mediaKind: MediaKind.Movie,
mediaItemId: mediaItemId,
lastProgressFraction: 1.0,
version: 4);
Result<Updated> firstResult = await firstSut.UpsertForUserAsync(firstIncoming, userId, CancellationToken.None);
Assert.False(firstResult.IsFailure);
// Act
DbUpdateConcurrencyException exception = await Assert.ThrowsAsync<DbUpdateConcurrencyException>(() => firstContext.SaveChangesAsync());
// Assert
Assert.NotNull(exception);
secondContext.ChangeTracker.Clear();
MediaResumePointEntity storedResumePointAfterSave = await secondContext.MediaResumePoints
.AsNoTracking()
.SingleAsync(resumePoint => resumePoint.UserId == userId && resumePoint.MediaItemId == mediaItemId);
Assert.Equal(0.8, storedResumePointAfterSave.LastProgressFraction);
Assert.Equal(5L, storedResumePointAfterSave.Version);
Assert.Equal(laterUtcNow, storedResumePointAfterSave.UpdatedOnUtc);
}
[Fact]
public async Task UserDeletion_WhenTheUserOwnsResumePoints_ShouldCascadeToTheResumePoints()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediaresumerepo-cascade-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
UserEntity user = _userEntityFixture.Create(id: userId);
context.Users.Add(user);
MediaResumePointEntity firstResumePoint = _mediaResumePointEntityFixture.Create(userId: userId);
MediaResumePointEntity secondResumePoint = _mediaResumePointEntityFixture.Create(userId: userId);
context.MediaResumePoints.AddRange(firstResumePoint, secondResumePoint);
await context.SaveChangesAsync();
// A real deletion starts with nothing tracked, so the database cascade is the path that has to remove the resume points.
context.ChangeTracker.Clear();
// Act
UserEntity storedUser = await context.Users.SingleAsync(candidate => candidate.Id == userId);
context.Users.Remove(storedUser);
await context.SaveChangesAsync();
// Assert
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
Assert.False(await verificationContext.MediaResumePoints.AsNoTracking().AnyAsync(resumePoint => resumePoint.UserId == userId));
}
/// <summary>
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <param name="userId">The Id of the user reported as the current user.</param>
/// <param name="utcNow">The current UTC time reported by the time provider.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow)
{
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
currentUserService.UserId.Returns(userId);
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
dateTimeProvider.UtcNow.Returns(utcNow);
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
.Options);
context.Database.EnsureCreated();
return context;
}
/// <summary>
/// Creates a real SQLite backed context without the auditing interceptor, so that stored values are read exactly as they were written.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateContext(SqliteConnection anchorConnection)
{
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.Options);
context.Database.EnsureCreated();
return context;
}
}
@@ -0,0 +1,140 @@
#region ========================================================================= USING =====================================================================================
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.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.MediaContributors;
/// <summary>
/// Contains integration tests for the <see cref="MediaContributorRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorRepositoryTests
{
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
[Fact]
public async Task InsertAsync_WhenContributorWithSameDisplayNameInDifferentCaseExists_ShouldReturnError()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediacontributorrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
MediaContributorRepository sut = new(context);
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Stephen King");
context.MediaContributors.Add(existingContributor);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
// The comparison is case-insensitive, matching the unique index on the display name.
Result<Created> result = await sut.InsertAsync(_mediaContributorEntityFixture.Create(displayName: "stephen king"), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.MediaContributor.MediaContributorAlreadyExists, result.FirstError);
}
[Fact]
public async Task GetByIdsAsync_WhenCalled_ShouldReturnOnlyTheRequestedContributorsAndIgnoreMissingIds()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediacontributorrepo-getbyids-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
MediaContributorRepository sut = new(context);
MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create(displayName: "Stephen King");
MediaContributorEntity thirdContributor = _mediaContributorEntityFixture.Create(displayName: "Ursula K. Le Guin");
context.MediaContributors.AddRange(firstContributor, secondContributor, thirdContributor);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
Result<IReadOnlyList<MediaContributorEntity>> result = await sut.GetByIdsAsync(
[firstContributor.Id, thirdContributor.Id, Guid.NewGuid()], 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);
Assert.DoesNotContain(result.Value, contributor => contributor.Id == secondContributor.Id);
}
[Fact]
public async Task GetByIdsAsync_WhenIdsIsEmpty_ShouldReturnAnEmptyList()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediacontributorrepo-getbyids-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
MediaContributorRepository sut = new(context);
context.MediaContributors.Add(_mediaContributorEntityFixture.Create());
await context.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_WhenMoreThanFiveHundredIdsAreRequested_ShouldReturnEveryContributor()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediacontributorrepo-getbyids-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
MediaContributorRepository sut = new(context);
const int CONTRIBUTOR_COUNT = 501;
List<MediaContributorEntity> contributors = [.. Enumerable.Range(0, CONTRIBUTOR_COUNT).Select(index =>
_mediaContributorEntityFixture.Create(displayName: $"Contributor {index}-{Guid.NewGuid():N}"))];
context.MediaContributors.AddRange(contributors);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// 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));
}
/// <summary>
/// Creates a real SQLite backed context, so that the stored values are read exactly as they were written.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateContext(SqliteConnection anchorConnection)
{
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.Options);
context.Database.EnsureCreated();
return context;
}
}
@@ -0,0 +1,511 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Common.Interceptors;
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 Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
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.IntegrationTests.Core.Repositories.MusicLibrary;
/// <summary>
/// Contains integration tests for the <see cref="MusicArtworkRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicArtworkRepositoryTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly LuminaDbContext _context;
private readonly MusicArtworkRepository _sut;
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MusicArtworkRepositoryTests"/> class.
/// </summary>
public MusicArtworkRepositoryTests()
{
// The repository deletes and updates in bulk, which translates to SQL, so the tests exercise it against a real SQLite database.
_connection = new SqliteConnection("Data Source=:memory:");
_connection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connection).Options);
_context.Database.EnsureCreated();
_sut = new MusicArtworkRepository(_context);
}
[Fact]
public async Task InsertRangeAsync_WhenCalledWithArtwork_ShouldAddThemToContextAndReturnCreated()
{
// Arrange
List<MusicArtworkEntity> artwork = _musicArtworkEntityFixture.CreateMany(3);
// Act
Result<Created> result = await _sut.InsertRangeAsync(artwork, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
await _context.SaveChangesAsync();
Assert.Equal(3, await _context.MusicArtwork.CountAsync());
}
[Fact]
public async Task InsertRangeAsync_WhenCollectionIsEmpty_ShouldReturnCreatedWithoutAddingAnyArtwork()
{
// Act
Result<Created> result = await _sut.InsertRangeAsync([], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
await _context.SaveChangesAsync();
Assert.Empty(await _context.MusicArtwork.ToListAsync());
}
[Fact]
public async Task GetByOwnerAsync_WhenCalled_ShouldReturnOnlyTheArtworkOfTheOwnerOrderedByTypeThenOrdinal()
{
// Arrange
MusicArtworkOwnerType ownerType = MusicArtworkOwnerType.Album;
Guid ownerId = Guid.NewGuid();
MusicArtworkEntity frontSecond = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Front, ordinal: 1);
MusicArtworkEntity frontFirst = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Front, ordinal: 0);
MusicArtworkEntity cover = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Cover, ordinal: 0);
MusicArtworkEntity artworkOfAnotherOwner = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: Guid.NewGuid());
MusicArtworkEntity artworkOfAnotherOwnerType = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: ownerId);
_context.MusicArtwork.AddRange(frontSecond, frontFirst, cover, artworkOfAnotherOwner, artworkOfAnotherOwnerType);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<MusicArtworkEntity>> result = await _sut.GetByOwnerAsync(ownerType, 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 GetByOwnerAsync_WhenTheOwnerHasNoArtwork_ShouldReturnAnEmptyCollection()
{
// Act
Result<IReadOnlyList<MusicArtworkEntity>> result = await _sut.GetByOwnerAsync(MusicArtworkOwnerType.Track, Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task DeleteByOwnerAsync_WhenCalled_ShouldDeleteOnlyTheArtworkOfTheOwner()
{
// Arrange
MusicArtworkOwnerType ownerType = MusicArtworkOwnerType.Album;
Guid ownerId = Guid.NewGuid();
MusicArtworkEntity artworkOfOwner = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId);
MusicArtworkEntity artworkOfAnotherOwner = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: Guid.NewGuid());
MusicArtworkEntity artworkOfAnotherOwnerType = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: ownerId);
_context.MusicArtwork.AddRange(artworkOfOwner, artworkOfAnotherOwner, artworkOfAnotherOwnerType);
await _context.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByOwnerAsync(ownerType, ownerId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
List<MusicArtworkEntity> remainingArtwork = await _context.MusicArtwork.ToListAsync();
Assert.Equal(2, remainingArtwork.Count);
Assert.DoesNotContain(remainingArtwork, artwork => artwork.Id == artworkOfOwner.Id);
Assert.Contains(remainingArtwork, artwork => artwork.Id == artworkOfAnotherOwner.Id);
Assert.Contains(remainingArtwork, artwork => artwork.Id == artworkOfAnotherOwnerType.Id);
}
[Fact]
public async Task DeleteByOwnerAsync_WhenNoArtworkExistsForTheOwner_ShouldReturnDeleted()
{
// Act
Result<Deleted> result = await _sut.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
}
[Fact]
public async Task ResetStatusForLibraryAsync_WhenCalled_ShouldResetTheArtworkOfTheLibraryItemsToPending()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
ArtistEntity artistOfAnotherLibrary = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
_context.Artists.AddRange(artist, artistOfAnotherLibrary);
_context.Albums.Add(album);
_context.Tracks.Add(track);
MusicArtworkEntity artistArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artist.Id, status: ArtworkStatus.Enriched);
MusicArtworkEntity albumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: album.Id, status: ArtworkStatus.Enriched);
MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: track.Id, status: ArtworkStatus.Enriched);
MusicArtworkEntity artworkOfAnotherLibrary = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistOfAnotherLibrary.Id, status: ArtworkStatus.Enriched);
_context.MusicArtwork.AddRange(artistArtwork, albumArtwork, trackArtwork, artworkOfAnotherLibrary);
await _context.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.ResetStatusForLibraryAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
// The bulk update bypasses the change tracker, so the tracked entities are detached before the stored values are read back.
_context.ChangeTracker.Clear();
Assert.Equal(ArtworkStatus.Pending, (await _context.MusicArtwork.FindAsync(artistArtwork.Id))!.Status);
Assert.Equal(ArtworkStatus.Pending, (await _context.MusicArtwork.FindAsync(albumArtwork.Id))!.Status);
Assert.Equal(ArtworkStatus.Pending, (await _context.MusicArtwork.FindAsync(trackArtwork.Id))!.Status);
Assert.Equal(ArtworkStatus.Enriched, (await _context.MusicArtwork.FindAsync(artworkOfAnotherLibrary.Id))!.Status);
}
[Fact]
public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldDeleteOnlyTheArtworkOfTheLibraryItems()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
ArtistEntity artistOfAnotherLibrary = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
AlbumEntity albumOfAnotherLibrary = _albumEntityFixture.Create(
artistId: artistOfAnotherLibrary.Id, libraryId: artistOfAnotherLibrary.LibraryId, includeTracks: false, includeMetadata: false);
TrackEntity trackOfAnotherLibrary = _trackEntityFixture.Create(
albumId: albumOfAnotherLibrary.Id, libraryId: artistOfAnotherLibrary.LibraryId, includeMetadata: false);
_context.Artists.AddRange(artist, artistOfAnotherLibrary);
_context.Albums.AddRange(album, albumOfAnotherLibrary);
_context.Tracks.AddRange(track, trackOfAnotherLibrary);
MusicArtworkEntity artistArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artist.Id);
MusicArtworkEntity albumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: album.Id);
MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: track.Id);
MusicArtworkEntity artworkOfAnotherLibrary = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistOfAnotherLibrary.Id);
_context.MusicArtwork.AddRange(artistArtwork, albumArtwork, trackArtwork, artworkOfAnotherLibrary);
await _context.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
_context.ChangeTracker.Clear();
// Every artwork owned by an artist, album or track of the library is deleted, while the artwork of another library survives.
MusicArtworkEntity remainingArtwork = Assert.Single(await _context.MusicArtwork.ToListAsync());
Assert.Equal(artworkOfAnotherLibrary.Id, remainingArtwork.Id);
}
[Fact]
public async Task DeleteByLibraryIdAsync_WhenTheLibraryHasNoArtwork_ShouldReturnDeleted()
{
// Act
Result<Deleted> result = await _sut.DeleteByLibraryIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
}
[Fact]
public async Task UpsertCoverAsync_WhenNoCoverExists_ShouldInsertANewCoverArtwork()
{
// Arrange
Guid ownerId = Guid.NewGuid();
Guid actingUserId = Guid.NewGuid();
DateTime insertedOnUtc = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-musicartworkrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
// The context is built with the auditing interceptor attached, so the cover insert is stamped exactly like in production.
using LuminaDbContext auditedContext = CreateAuditedContext(anchorConnection, actingUserId, insertedOnUtc);
MusicArtworkRepository sut = new(auditedContext);
// Act
Result<Updated> result = await sut.UpsertCoverAsync(MusicArtworkOwnerType.Album, ownerId, "covers/new.jpg", CancellationToken.None);
await auditedContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
MusicArtworkEntity cover = Assert.Single(await auditedContext.MusicArtwork.ToListAsync());
Assert.Equal(MusicArtworkOwnerType.Album, cover.OwnerType);
Assert.Equal(ownerId, cover.OwnerId);
Assert.Equal(ArtworkType.Cover, cover.ArtworkType);
Assert.Equal(0, cover.Ordinal);
Assert.Equal("covers/new.jpg", cover.FileName);
Assert.Equal(ArtworkStatus.Enriched, cover.Status);
Assert.Equal(insertedOnUtc, cover.CreatedOnUtc);
Assert.Equal(actingUserId, cover.CreatedBy);
Assert.Null(cover.UpdatedOnUtc);
Assert.Null(cover.UpdatedBy);
}
[Fact]
public async Task UpsertCoverAsync_WhenCoverExists_ShouldUpdateItInPlace()
{
// Arrange
Guid ownerId = Guid.NewGuid();
MusicArtworkEntity existingCover = _musicArtworkEntityFixture.Create(
ownerType: MusicArtworkOwnerType.Album, ownerId: ownerId, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "covers/old.jpg",
status: ArtworkStatus.Pending, includeLastUpdateUtc: false);
_context.MusicArtwork.Add(existingCover);
await _context.SaveChangesAsync();
Guid existingCoverId = existingCover.Id;
Guid existingCreatedBy = existingCover.CreatedBy;
DateTime existingCreatedOnUtc = existingCover.CreatedOnUtc;
_context.ChangeTracker.Clear();
// Act
Result<Updated> result = await _sut.UpsertCoverAsync(MusicArtworkOwnerType.Album, ownerId, "covers/new.jpg", CancellationToken.None);
await _context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
// The existing cover is updated in place, so no new row is inserted and the creation audit columns are preserved.
MusicArtworkEntity cover = Assert.Single(await _context.MusicArtwork.ToListAsync());
Assert.Equal(existingCoverId, cover.Id);
Assert.Equal("covers/new.jpg", cover.FileName);
Assert.Equal(ArtworkStatus.Enriched, cover.Status);
Assert.NotNull(cover.LastUpdateUtc);
Assert.Equal(existingCreatedBy, cover.CreatedBy);
Assert.Equal(existingCreatedOnUtc, cover.CreatedOnUtc);
}
[Fact]
public async Task UpsertCoverAsync_WhenTheCoverHasANonZeroOrdinal_ShouldUpdateItInPlaceInsteadOfInsertingASecondCover()
{
// Arrange
Guid ownerId = Guid.NewGuid();
// The callers resolve the existing cover by artwork type only, so a cover stored with an ordinal other than zero must still be the one replaced.
MusicArtworkEntity existingCover = _musicArtworkEntityFixture.Create(
ownerType: MusicArtworkOwnerType.Album, ownerId: ownerId, artworkType: ArtworkType.Cover, ordinal: 3, fileName: "covers/old.jpg",
status: ArtworkStatus.Pending, includeLastUpdateUtc: false);
_context.MusicArtwork.Add(existingCover);
await _context.SaveChangesAsync();
Guid existingCoverId = existingCover.Id;
_context.ChangeTracker.Clear();
// Act
Result<Updated> result = await _sut.UpsertCoverAsync(MusicArtworkOwnerType.Album, ownerId, "covers/new.jpg", CancellationToken.None);
await _context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
MusicArtworkEntity cover = Assert.Single(await _context.MusicArtwork.ToListAsync());
Assert.Equal(existingCoverId, cover.Id);
Assert.Equal(3, cover.Ordinal);
Assert.Equal("covers/new.jpg", cover.FileName);
Assert.Equal(ArtworkStatus.Enriched, cover.Status);
}
[Fact]
public async Task GetByOwnersAsync_WhenCalled_ShouldReturnOnlyTheArtworkOfTheRequestedOwnerTypeAndOwnerIds()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-musicartworkrepo-getbyowners-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
MusicArtworkRepository sut = new(context);
MusicArtworkOwnerType ownerType = MusicArtworkOwnerType.Album;
Guid firstOwnerId = Guid.NewGuid();
Guid secondOwnerId = Guid.NewGuid();
MusicArtworkEntity firstOwnerCover = _musicArtworkEntityFixture.Create(
ownerType: ownerType, ownerId: firstOwnerId, artworkType: ArtworkType.Cover, ordinal: 0);
MusicArtworkEntity firstOwnerFront = _musicArtworkEntityFixture.Create(
ownerType: ownerType, ownerId: firstOwnerId, artworkType: ArtworkType.Front, ordinal: 1);
MusicArtworkEntity secondOwnerCover = _musicArtworkEntityFixture.Create(
ownerType: ownerType, ownerId: secondOwnerId, artworkType: ArtworkType.Cover, ordinal: 0);
MusicArtworkEntity artworkOfAnotherOwner = _musicArtworkEntityFixture.Create(
ownerType: ownerType, ownerId: Guid.NewGuid(), artworkType: ArtworkType.Cover, ordinal: 0);
MusicArtworkEntity artworkOfAnotherOwnerType = _musicArtworkEntityFixture.Create(
ownerType: MusicArtworkOwnerType.Artist, ownerId: firstOwnerId, artworkType: ArtworkType.Cover, ordinal: 0);
context.MusicArtwork.AddRange(firstOwnerCover, firstOwnerFront, secondOwnerCover, artworkOfAnotherOwner, artworkOfAnotherOwnerType);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
Result<IReadOnlyList<MusicArtworkEntity>> result = await sut.GetByOwnersAsync(ownerType, [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_WhenOwnerIdsIsEmpty_ShouldReturnAnEmptyList()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-musicartworkrepo-getbyowners-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
MusicArtworkRepository sut = new(context);
context.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album));
await context.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
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-musicartworkrepo-getbyowners-order-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
MusicArtworkRepository sut = new(context);
MusicArtworkOwnerType ownerType = MusicArtworkOwnerType.Album;
Guid ownerId = Guid.NewGuid();
MusicArtworkEntity frontSecond = _musicArtworkEntityFixture.Create(
ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Front, ordinal: 1);
MusicArtworkEntity frontFirst = _musicArtworkEntityFixture.Create(
ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Front, ordinal: 0);
MusicArtworkEntity cover = _musicArtworkEntityFixture.Create(
ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Cover, ordinal: 0);
context.MusicArtwork.AddRange(frontSecond, frontFirst, cover);
await context.SaveChangesAsync();
// Act
Result<IReadOnlyList<MusicArtworkEntity>> result = await sut.GetByOwnersAsync(ownerType, [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
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-musicartworkrepo-getbyowners-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
MusicArtworkRepository sut = new(context);
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))];
context.MusicArtwork.AddRange(artwork);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
// The lookup is chunked in batches of 500, so the 501st owner proves the second 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));
}
[Fact]
public async Task GetByOwnersAsync_WhenCalled_ShouldReturnDetachedArtwork()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-musicartworkrepo-getbyowners-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
MusicArtworkRepository sut = new(context);
MusicArtworkOwnerType ownerType = MusicArtworkOwnerType.Album;
Guid ownerId = Guid.NewGuid();
MusicArtworkEntity artwork = _musicArtworkEntityFixture.Create(
ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Cover, ordinal: 0);
context.MusicArtwork.Add(artwork);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
Result<IReadOnlyList<MusicArtworkEntity>> firstResult = await sut.GetByOwnersAsync(ownerType, [ownerId], CancellationToken.None);
Result<IReadOnlyList<MusicArtworkEntity>> secondResult = await sut.GetByOwnersAsync(ownerType, [ownerId], CancellationToken.None);
// Assert
Assert.False(firstResult.IsFailure);
Assert.False(secondResult.IsFailure);
// The read is untracked, so the returned rows never leak into the unit of work, and a second read works the same way.
Assert.Empty(context.ChangeTracker.Entries<MusicArtworkEntity>());
MusicArtworkEntity firstReturnedArtwork = Assert.Single(firstResult.Value);
MusicArtworkEntity secondReturnedArtwork = Assert.Single(secondResult.Value);
Assert.Equal(artwork.Id, firstReturnedArtwork.Id);
Assert.Equal(artwork.Id, secondReturnedArtwork.Id);
Assert.Equal(EntityState.Detached, context.Entry(firstReturnedArtwork).State);
Assert.Empty(context.ChangeTracker.Entries<MusicArtworkEntity>());
}
/// <summary>
/// Creates a real SQLite backed context, so that the stored values are read exactly as they were written.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateContext(SqliteConnection anchorConnection)
{
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.Options);
context.Database.EnsureCreated();
return context;
}
/// <summary>
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <param name="userId">The Id of the user reported as the current user.</param>
/// <param name="utcNow">The current UTC time reported by the time provider.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow)
{
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
currentUserService.UserId.Returns(userId);
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
dateTimeProvider.UtcNow.Returns(utcNow);
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
.Options);
context.Database.EnsureCreated();
return context;
}
/// <summary>
/// Disposes the database context and its underlying connection.
/// </summary>
public void Dispose()
{
_context.Dispose();
_connection.Dispose();
}
}
@@ -0,0 +1,183 @@
#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;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.MusicLibrary;
/// <summary>
/// Contains integration tests for the <see cref="MusicLibraryScanItemMetadataRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicLibraryScanItemMetadataRepositoryTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly LuminaDbContext _context;
private readonly MusicLibraryScanItemMetadataRepository _sut;
private readonly MusicLibraryScanItemMetadataEntityFixture _musicLibraryScanItemMetadataEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MusicLibraryScanItemMetadataRepositoryTests"/> class.
/// </summary>
public MusicLibraryScanItemMetadataRepositoryTests()
{
// The repository deletes in bulk, which translates to SQL, so the tests exercise it against a real SQLite database.
_connection = new SqliteConnection("Data Source=:memory:");
_connection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connection).Options);
_context.Database.EnsureCreated();
_sut = new MusicLibraryScanItemMetadataRepository(_context);
}
[Fact]
public async Task InsertRangeAsync_WhenCalledWithItems_ShouldAddThemToContextAndReturnCreated()
{
// Arrange
List<MusicLibraryScanItemMetadataEntity> items = _musicLibraryScanItemMetadataEntityFixture.CreateMany(3);
// Act
Result<Created> result = await _sut.InsertRangeAsync(items, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
await _context.SaveChangesAsync();
Assert.Equal(3, await _context.MusicLibraryScanItemMetadata.CountAsync());
}
[Fact]
public async Task InsertRangeAsync_WhenCollectionIsEmpty_ShouldReturnCreatedWithoutAddingAnyItems()
{
// Act
Result<Created> result = await _sut.InsertRangeAsync([], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
await _context.SaveChangesAsync();
Assert.Empty(await _context.MusicLibraryScanItemMetadata.ToListAsync());
}
[Fact]
public async Task GetByScanIdAsync_WhenCalled_ShouldReturnOnlyTheItemsOfTheScanOrderedByPath()
{
// Arrange
Guid scanId = Guid.NewGuid();
MusicLibraryScanItemMetadataEntity bicycleItem = _musicLibraryScanItemMetadataEntityFixture.Create(libraryScanId: scanId, path: "/music/queen/bicycle-race.flac");
MusicLibraryScanItemMetadataEntity bohemianItem = _musicLibraryScanItemMetadataEntityFixture.Create(libraryScanId: scanId, path: "/music/queen/bohemian-rhapsody.flac");
MusicLibraryScanItemMetadataEntity itemOfAnotherScan = _musicLibraryScanItemMetadataEntityFixture.Create(path: "/music/queen/dont-stop-me-now.flac");
_context.MusicLibraryScanItemMetadata.AddRange(bicycleItem, bohemianItem, itemOfAnotherScan);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>> result = await _sut.GetByScanIdAsync(scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([bicycleItem.Id, bohemianItem.Id], result.Value.Select(item => item.Id));
}
[Fact]
public async Task GetByScanIdAsync_WhenNoItemsExistForTheScan_ShouldReturnAnEmptyCollection()
{
// Act
Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>> result = await _sut.GetByScanIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetByLibraryIdAsync_WhenCalled_ShouldReturnAllTheItemsOfTheLibraryOrderedByPath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
MusicLibraryScanItemMetadataEntity itemOfFirstScan = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: libraryId, libraryScanId: Guid.NewGuid(), path: "/music/queen/bohemian-rhapsody.flac");
MusicLibraryScanItemMetadataEntity itemOfSecondScan = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: libraryId, libraryScanId: Guid.NewGuid(), path: "/music/queen/bicycle-race.flac");
MusicLibraryScanItemMetadataEntity itemOfAnotherLibrary = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: Guid.NewGuid(), path: "/music/queen/love-of-my-life.flac");
_context.MusicLibraryScanItemMetadata.AddRange(itemOfFirstScan, itemOfSecondScan, itemOfAnotherLibrary);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([itemOfSecondScan.Id, itemOfFirstScan.Id], result.Value.Select(item => item.Id));
}
[Fact]
public async Task GetByLibraryIdAsync_WhenNoItemsExistForTheLibrary_ShouldReturnAnEmptyCollection()
{
// Act
Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>> result = await _sut.GetByLibraryIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task DeleteByScanIdAsync_WhenCalled_ShouldDeleteOnlyTheItemsOfTheScan()
{
// Arrange
Guid scanId = Guid.NewGuid();
MusicLibraryScanItemMetadataEntity itemOfScan = _musicLibraryScanItemMetadataEntityFixture.Create(libraryScanId: scanId, path: "/music/queen/bohemian-rhapsody.flac");
MusicLibraryScanItemMetadataEntity itemOfAnotherScan = _musicLibraryScanItemMetadataEntityFixture.Create(path: "/music/queen/love-of-my-life.flac");
_context.MusicLibraryScanItemMetadata.AddRange(itemOfScan, itemOfAnotherScan);
await _context.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByScanIdAsync(scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
MusicLibraryScanItemMetadataEntity remainingItem = Assert.Single(await _context.MusicLibraryScanItemMetadata.ToListAsync());
Assert.Equal(itemOfAnotherScan.Id, remainingItem.Id);
}
[Fact]
public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldDeleteOnlyThatLibrariesStagedMetadata()
{
// Arrange
Guid libraryId = Guid.NewGuid();
MusicLibraryScanItemMetadataEntity itemOfLibrary = _musicLibraryScanItemMetadataEntityFixture.Create(libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac");
MusicLibraryScanItemMetadataEntity itemOfAnotherLibrary = _musicLibraryScanItemMetadataEntityFixture.Create(path: "/music/queen/love-of-my-life.flac");
_context.MusicLibraryScanItemMetadata.AddRange(itemOfLibrary, itemOfAnotherLibrary);
await _context.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
MusicLibraryScanItemMetadataEntity remainingItem = Assert.Single(await _context.MusicLibraryScanItemMetadata.ToListAsync());
Assert.Equal(itemOfAnotherLibrary.Id, remainingItem.Id);
}
/// <summary>
/// Disposes the database context and its underlying connection.
/// </summary>
public void Dispose()
{
_context.Dispose();
_connection.Dispose();
}
}
@@ -0,0 +1,235 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Core.Repositories.MusicLibrary.Specifications;
using Lumina.DataAccess.Core.UoW;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.MusicLibrary.Specifications;
/// <summary>
/// Contains integration tests for the <see cref="ArtistAlphaFilterSpecification"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtistAlphaFilterSpecificationTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly LuminaDbContext _context;
private readonly ArtistEntityFixture _artistEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ArtistAlphaFilterSpecificationTests"/> class.
/// </summary>
public ArtistAlphaFilterSpecificationTests()
{
// The specification translates to the SQLite glob() function, so it can only be exercised against a real SQLite database.
_connection = new SqliteConnection("Data Source=:memory:");
_connection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connection).Options);
_context.Database.EnsureCreated();
}
[Fact]
public void ToExpression_WhenAlphaKeyIsNull_ShouldMatchEveryArtist()
{
// Arrange
List<ArtistEntity> artists = SeedArtists("Alpha", "Beta", "1984");
ArtistAlphaFilterSpecification specification = new(null, false);
// Act
List<ArtistEntity> result = [.. _context.Artists.Where(specification.ToExpression())];
// Assert
Assert.Equal(artists.Count, result.Count);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsALowercaseLetter_ShouldMatchOnlyArtistsWhoseNameStartsWithIt()
{
// Arrange
SeedArtists("Foo Fighters", "Helloween", "The Beatles");
ArtistAlphaFilterSpecification specification = new("f", false);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
Assert.Equal(["Foo Fighters"], result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsAnUppercaseLetter_ShouldMatchArtistsWhoseNameStartsWithItsLowercase()
{
// Arrange
SeedArtists("Foo Fighters", "Helloween");
ArtistAlphaFilterSpecification specification = new("F", false);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
Assert.Equal(["Foo Fighters"], result);
}
[Fact]
public void ToExpression_WhenNoNameStartsWithTheAlphaKey_ShouldNotMatchAnyArtist()
{
// Arrange
SeedArtists("Foo Fighters", "Helloween");
ArtistAlphaFilterSpecification specification = new("z", false);
// Act
List<ArtistEntity> result = [.. _context.Artists.Where(specification.ToExpression())];
// Assert
Assert.Empty(result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsTheNumberKey_ShouldMatchOnlyArtistsWhoseNameStartsWithADigit()
{
// Arrange
SeedArtists("1984", "Alpha", "Beta");
ArtistAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.NUMBER, false);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
Assert.Equal(["1984"], result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsTheSymbolKey_ShouldMatchOnlyArtistsWhoseNameStartsWithASymbol()
{
// Arrange
SeedArtists("!Important", "1984", "Alpha");
ArtistAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.SYMBOL, false);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
Assert.Equal(["!Important"], result);
}
[Fact]
public void ToExpression_WhenIgnoringThePrefixAndNameStartsWithThe_ShouldMatchOnTheStrippedName()
{
// Arrange
SeedArtists("The Beatles", "Adele");
ArtistAlphaFilterSpecification specification = new("b", true);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
Assert.Equal(["The Beatles"], result);
}
[Fact]
public void ToExpression_WhenNotIgnoringThePrefixAndNameStartsWithThe_ShouldNotMatchOnTheStrippedName()
{
// Arrange
SeedArtists("The Beatles", "Adele");
ArtistAlphaFilterSpecification specification = new("b", false);
// Act
List<ArtistEntity> result = [.. _context.Artists.Where(specification.ToExpression())];
// Assert
Assert.Empty(result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsTheNumberKeyAndNameStartsWithASymbol_ShouldNotMatchIt()
{
// Arrange
SeedArtists("!Voyager", "1984", "Alpha");
ArtistAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.NUMBER, false);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
// Only the artist whose name starts with a digit matches; a symbol and a letter do not.
Assert.Equal(["1984"], result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsTheSymbolKeyAndNameIsEmpty_ShouldMatchIt()
{
// Arrange
SeedArtists(string.Empty);
ArtistAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.SYMBOL, false);
// Act
List<ArtistEntity> result = [.. _context.Artists.Where(specification.ToExpression())];
// Assert
// An empty effective name is neither a letter nor a digit, so it is categorized as a symbol.
Assert.Single(result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsALetterAndNameIsEmpty_ShouldNotMatchAnyArtist()
{
// Arrange
SeedArtists(string.Empty);
ArtistAlphaFilterSpecification specification = new("a", false);
// Act
List<ArtistEntity> result = [.. _context.Artists.Where(specification.ToExpression())];
// Assert
Assert.Empty(result);
}
[Theory]
[InlineData("a", "Alpha")] // The first letter of the alphabet.
[InlineData("b", "Bravo")] // A letter in the middle of the alphabet.
[InlineData("c", "Charlie")] // Another letter in the middle of the alphabet.
public void ToExpression_WhenAlphaKeyIsALetter_ShouldMatchOnlyTheNamesStartingWithIt(string alphaKey, string matchingName)
{
// Arrange
SeedArtists("Alpha", "Bravo", "Charlie");
ArtistAlphaFilterSpecification specification = new(alphaKey, false);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
Assert.Equal([matchingName], result);
}
/// <summary>
/// Seeds artists with the provided names.
/// </summary>
/// <param name="names">The names of the artists to seed.</param>
/// <returns>The seeded <see cref="ArtistEntity"/> instances.</returns>
private List<ArtistEntity> SeedArtists(params string[] names)
{
List<ArtistEntity> entities = [];
foreach (string name in names)
entities.Add(_artistEntityFixture.Create(name: name, includeAlbums: false, includeContributors: false));
_context.Artists.AddRange(entities);
_context.SaveChanges();
return entities;
}
/// <summary>
/// Disposes the database context and its underlying connection.
/// </summary>
public void Dispose()
{
_context.Dispose();
_connection.Dispose();
}
}
@@ -0,0 +1,144 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.DataAccess.Common.Interceptors;
using Lumina.DataAccess.Core.Repositories.Scheduling;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Scheduling;
/// <summary>
/// Contains integration tests for the <see cref="ScheduledJobExecutionRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionRepositoryTests
{
private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new();
[Fact]
public async Task DeleteOlderThanAsync_WhenExecutionsStartedBeforeTheCutoff_ShouldDeleteOnlyThem()
{
// Arrange
// The deletion uses ExecuteDeleteAsync, which is not supported by the in-memory provider, so a real SQLite database is used.
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobexecutionrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ScheduledJobExecutionRepository sut = new(context);
DateTime cutoffUtc = DateTime.UtcNow.AddMonths(-1);
ScheduledJobExecutionEntity olderExecution = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: cutoffUtc.AddDays(-30));
ScheduledJobExecutionEntity recentExecution = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: cutoffUtc.AddDays(1));
context.ScheduledJobExecutions.AddRange(olderExecution, recentExecution);
await context.SaveChangesAsync();
// Act
Result<Success> result = await sut.DeleteOlderThanAsync(cutoffUtc, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
int remainingCount = await context.ScheduledJobExecutions.CountAsync();
Assert.Equal(1, remainingCount);
Assert.Null(await context.ScheduledJobExecutions.FirstOrDefaultAsync(execution => execution.Id == olderExecution.Id));
Assert.NotNull(await context.ScheduledJobExecutions.FirstOrDefaultAsync(execution => execution.Id == recentExecution.Id));
}
[Fact]
public async Task DeleteOlderThanAsync_WhenNoExecutionStartedBeforeTheCutoff_ShouldNotDeleteAnything()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobexecutionrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ScheduledJobExecutionRepository sut = new(context);
DateTime cutoffUtc = DateTime.UtcNow.AddMonths(-1);
ScheduledJobExecutionEntity recentExecution = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: cutoffUtc.AddDays(1));
context.ScheduledJobExecutions.Add(recentExecution);
await context.SaveChangesAsync();
// Act
Result<Success> result = await sut.DeleteOlderThanAsync(cutoffUtc, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, await context.ScheduledJobExecutions.CountAsync());
}
[Fact]
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheCreationColumnsAndStampTheModificationColumns()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobexecutionrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
Guid actingUserId = Guid.NewGuid();
currentUserService.UserId.Returns(actingUserId);
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
DateTime insertTimeUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
dateTimeProvider.UtcNow.Returns(insertTimeUtc);
// The context is built with the auditing interceptor attached, so an interceptor regression is caught instead of being masked by its absence.
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
.Options);
context.Database.EnsureCreated();
ScheduledJobExecutionRepository sut = new(context);
ScheduledJobExecutionEntity storedExecution = _scheduledJobExecutionEntityFixture.Create(isCycleRun: false);
context.ScheduledJobExecutions.Add(storedExecution);
await context.SaveChangesAsync();
// The interceptor stamps the creation columns on insert.
Assert.Equal(insertTimeUtc, storedExecution.CreatedOnUtc);
Assert.Equal(actingUserId, storedExecution.CreatedBy);
DateTime updateTimeUtc = insertTimeUtc.AddDays(1);
dateTimeProvider.UtcNow.Returns(updateTimeUtc);
ScheduledJobExecutionEntity updatedExecution = _scheduledJobExecutionEntityFixture.Create(
id: storedExecution.Id,
scheduledJobId: storedExecution.ScheduledJobId,
taskType: storedExecution.TaskType,
isCycleRun: true,
wasCycleActive: storedExecution.WasCycleActive,
startedOnUtc: storedExecution.StartedOnUtc,
completedOnUtc: DateTime.UtcNow);
// The incoming entity carries hostile audit values that must never win over the ones owned by the persistence medium.
updatedExecution.CreatedOnUtc = insertTimeUtc.AddYears(-10);
updatedExecution.CreatedBy = Guid.NewGuid();
updatedExecution.UpdatedOnUtc = insertTimeUtc.AddYears(-5);
updatedExecution.UpdatedBy = Guid.NewGuid();
// Act
Result<Updated> result = await sut.UpdateAsync(updatedExecution, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
ScheduledJobExecutionEntity reloadedExecution = await context.ScheduledJobExecutions.AsNoTracking().FirstAsync(execution => execution.Id == storedExecution.Id);
Assert.True(reloadedExecution.IsCycleRun);
// The interceptor owns the modification columns and stamped them with the acting user and time, not with the incoming values.
Assert.Equal(updateTimeUtc, reloadedExecution.UpdatedOnUtc);
Assert.Equal(actingUserId, reloadedExecution.UpdatedBy);
// The creation columns are still the ones stamped on insert.
Assert.Equal(insertTimeUtc, reloadedExecution.CreatedOnUtc);
Assert.Equal(actingUserId, reloadedExecution.CreatedBy);
}
}
@@ -0,0 +1,76 @@
#region ========================================================================= USING =====================================================================================
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 Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Scheduling;
/// <summary>
/// Contains integration tests for the <see cref="ScheduledJobRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobRepositoryTests
{
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
[Fact]
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ScheduledJobRepository sut = new(context);
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
Guid storedCreatedBy = Guid.NewGuid();
ScheduledJobEntity storedJob = _scheduledJobEntityFixture.Create(name: "Original Job");
storedJob.CreatedOnUtc = storedCreatedOnUtc;
storedJob.CreatedBy = storedCreatedBy;
context.ScheduledJobs.Add(storedJob);
await context.SaveChangesAsync();
ScheduledJobEntity updatedJob = _scheduledJobEntityFixture.Create(
id: storedJob.Id,
name: "Updated Job",
taskType: storedJob.TaskType,
scheduleType: storedJob.ScheduleType,
intervalMinutes: storedJob.IntervalMinutes,
hour: storedJob.Hour,
minute: storedJob.Minute,
status: storedJob.Status,
ownerUserId: storedJob.OwnerUserId,
lastStartedOnUtc: storedJob.LastStartedOnUtc,
lastCompletedOnUtc: storedJob.LastCompletedOnUtc);
updatedJob.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
updatedJob.CreatedBy = Guid.NewGuid();
updatedJob.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5);
updatedJob.UpdatedBy = Guid.NewGuid();
// Act
Result<Updated> result = await sut.UpdateAsync(updatedJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
ScheduledJobEntity reloadedJob = await context.ScheduledJobs.AsNoTracking().FirstAsync(job => job.Id == storedJob.Id);
Assert.Equal("Updated Job", reloadedJob.Name);
Assert.Equal(storedCreatedOnUtc, reloadedJob.CreatedOnUtc);
Assert.Equal(storedCreatedBy, reloadedJob.CreatedBy);
Assert.Null(reloadedJob.UpdatedOnUtc);
Assert.Null(reloadedJob.UpdatedBy);
}
}
@@ -0,0 +1,72 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.DataAccess.Core.Repositories.Themes;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Themes;
/// <summary>
/// Contains integration tests for the <see cref="ThemeRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeRepositoryTests
{
private readonly ThemeEntityFixture _themeEntityFixture = new();
[Fact]
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-themerepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ThemeRepository sut = new(context);
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
Guid storedCreatedBy = Guid.NewGuid();
ThemeEntity storedTheme = _themeEntityFixture.Create(createdOnUtc: storedCreatedOnUtc, createdBy: storedCreatedBy);
context.Themes.Add(storedTheme);
await context.SaveChangesAsync();
ThemeEntity updatedTheme = _themeEntityFixture.Create(
id: storedTheme.Id,
themeId: storedTheme.ThemeId,
name: "Updated Theme",
description: storedTheme.Description,
author: storedTheme.Author,
version: storedTheme.Version,
installSource: storedTheme.InstallSource,
createdOnUtc: DateTime.UtcNow.AddYears(-10),
createdBy: Guid.NewGuid(),
includeUpdatedOnUtc: true,
updatedOnUtc: DateTime.UtcNow.AddYears(-5),
includeUpdatedBy: true,
updatedBy: Guid.NewGuid());
// Act
Result<Updated> result = await sut.UpdateAsync(updatedTheme, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
ThemeEntity reloadedTheme = await context.Themes.AsNoTracking().FirstAsync(theme => theme.Id == storedTheme.Id);
Assert.Equal("Updated Theme", reloadedTheme.Name);
Assert.Equal(storedCreatedOnUtc, reloadedTheme.CreatedOnUtc);
Assert.Equal(storedCreatedBy, reloadedTheme.CreatedBy);
Assert.Null(reloadedTheme.UpdatedOnUtc);
Assert.Null(reloadedTheme.UpdatedBy);
}
}
@@ -0,0 +1,104 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
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.Primitives;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Users;
/// <summary>
/// Contains integration tests for the <see cref="UserRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserRepositoryTests
{
private readonly UserEntityFixture _userEntityFixture = new();
private readonly PermissionEntityFixture _permissionEntityFixture = new();
private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
[Fact]
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-userrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
UserRepository sut = new(context);
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
Guid storedCreatedBy = Guid.NewGuid();
UserEntity storedUser = _userEntityFixture.Create(username: "audit-user", password: "Password123");
storedUser.CreatedOnUtc = storedCreatedOnUtc;
storedUser.CreatedBy = storedCreatedBy;
context.Users.Add(storedUser);
await context.SaveChangesAsync();
UserEntity updatedUser = _userEntityFixture.Create(id: storedUser.Id, username: "audit-user", password: "NewPassword123");
updatedUser.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
updatedUser.CreatedBy = Guid.NewGuid();
updatedUser.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5);
updatedUser.UpdatedBy = Guid.NewGuid();
// Act
Result<Updated> result = await sut.UpdateAsync(updatedUser, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
UserEntity reloadedUser = await context.Users.AsNoTracking().FirstAsync(user => user.Id == storedUser.Id);
Assert.Equal("NewPassword123", reloadedUser.Password);
Assert.Equal(storedCreatedOnUtc, reloadedUser.CreatedOnUtc);
Assert.Equal(storedCreatedBy, reloadedUser.CreatedBy);
Assert.Null(reloadedUser.UpdatedOnUtc);
Assert.Null(reloadedUser.UpdatedBy);
}
[Fact]
public async Task UpdateAsync_WhenNothingChanged_ShouldNotDuplicateThePermissions()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-userrepo-permissions-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
UserRepository sut = new(context);
PermissionEntity firstPermission = _permissionEntityFixture.Create();
PermissionEntity secondPermission = _permissionEntityFixture.Create();
UserEntity storedUser = _userEntityFixture.Create(username: $"perm-user-{Guid.NewGuid():N}", password: "Password123");
context.Permissions.AddRange(firstPermission, secondPermission);
context.Users.Add(storedUser);
await context.SaveChangesAsync();
storedUser.UserPermissions.Add(_userPermissionEntityFixture.Create(storedUser, firstPermission));
storedUser.UserPermissions.Add(_userPermissionEntityFixture.Create(storedUser, secondPermission));
await context.SaveChangesAsync();
// Detach the seeded user, so that the update must load it through its include chain instead of returning the already populated seeded instance.
context.ChangeTracker.Clear();
UserEntity incoming = await context.Users.AsNoTracking().Include(candidate => candidate.UserPermissions).FirstAsync(candidate => candidate.Id == storedUser.Id);
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
UserEntity? reloadedUser = await context.Users.AsNoTracking().Include(candidate => candidate.UserPermissions).FirstOrDefaultAsync(candidate => candidate.Id == storedUser.Id);
Assert.NotNull(reloadedUser);
Assert.Equal(2, reloadedUser!.UserPermissions.Count);
}
}
@@ -0,0 +1,120 @@
#region ========================================================================= USING =====================================================================================
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.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Users;
/// <summary>
/// Contains integration tests for the <see cref="UserSettingsRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserSettingsRepositoryTests
{
private readonly UserEntityFixture _userEntityFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
[Fact]
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-usersettingsrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
UserSettingsRepository sut = new(context);
UserEntity storedUser = _userEntityFixture.Create(username: "settings-user", password: "Password123");
context.Users.Add(storedUser);
await context.SaveChangesAsync();
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
Guid storedCreatedBy = Guid.NewGuid();
UserSettingsEntity storedSettings = _userSettingsEntityFixture.Create(userId: storedUser.Id, itemsPerPage: 10);
storedSettings.CreatedOnUtc = storedCreatedOnUtc;
storedSettings.CreatedBy = storedCreatedBy;
context.UserSettings.Add(storedSettings);
await context.SaveChangesAsync();
UserSettingsEntity updatedSettings = _userSettingsEntityFixture.Create(id: storedSettings.Id, userId: storedUser.Id, itemsPerPage: 25);
updatedSettings.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
updatedSettings.CreatedBy = Guid.NewGuid();
updatedSettings.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5);
updatedSettings.UpdatedBy = Guid.NewGuid();
// Act
Result<Updated> result = await sut.UpdateAsync(updatedSettings, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
UserSettingsEntity reloadedSettings = await context.UserSettings.AsNoTracking().FirstAsync(settings => settings.Id == storedSettings.Id);
Assert.Equal(25, reloadedSettings.ItemsPerPage);
Assert.Equal(storedCreatedOnUtc, reloadedSettings.CreatedOnUtc);
Assert.Equal(storedCreatedBy, reloadedSettings.CreatedBy);
Assert.Null(reloadedSettings.UpdatedOnUtc);
Assert.Null(reloadedSettings.UpdatedBy);
}
[Fact]
public async Task InsertAsync_WhenVuMeterSettingsAreProvided_ShouldPersistEveryValue()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-usersettingsvu-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
UserSettingsRepository sut = new(context);
UserEntity storedUser = _userEntityFixture.Create(username: "vu-meter-settings-user", password: "Password123");
context.Users.Add(storedUser);
await context.SaveChangesAsync();
UserSettingsEntity settingsToStore = _userSettingsEntityFixture.Create(
userId: storedUser.Id,
vuMeterOrientation: VuMeterOrientation.Horizontal,
vuMeterSegmentCount: 20,
vuMeterSegmentGap: 4,
vuMeterMediumThreshold: 0.35,
vuMeterHighThreshold: 0.9,
vuMeterShowPeak: false,
vuMeterPeakHoldDurationInMilliseconds: 1200,
vuMeterReleasePerSecond: 7.5,
vuMeterPeakReleasePerSecond: 0.25);
settingsToStore.CreatedOnUtc = DateTime.UtcNow;
settingsToStore.CreatedBy = storedUser.Id;
// Act
Result<Created> insertResult = await sut.InsertAsync(settingsToStore, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(insertResult.IsFailure);
Assert.Equal(Result.Created, insertResult.Value);
context.ChangeTracker.Clear();
UserSettingsEntity reloadedSettings = await context.UserSettings.AsNoTracking().FirstAsync(settings => settings.Id == settingsToStore.Id);
Assert.Equal(VuMeterOrientation.Horizontal, reloadedSettings.VuMeterOrientation);
Assert.Equal(20, reloadedSettings.VuMeterSegmentCount);
Assert.Equal(4, reloadedSettings.VuMeterSegmentGap);
Assert.Equal(0.35, reloadedSettings.VuMeterMediumThreshold);
Assert.Equal(0.9, reloadedSettings.VuMeterHighThreshold);
Assert.False(reloadedSettings.VuMeterShowPeak);
Assert.Equal(1200, reloadedSettings.VuMeterPeakHoldDurationInMilliseconds);
Assert.Equal(7.5, reloadedSettings.VuMeterReleasePerSecond);
Assert.Equal(0.25, reloadedSettings.VuMeterPeakReleasePerSecond);
}
}