Relocates real-resource tests into integration projects and improves data access unit tests

This commit is contained in:
BinaryAlley committed 2026-09-02 09:49:58 -07:00
1 parent 551259ad81
commit 042c5e4729
56 files changed
+5642 -4136

No files matched your search

@@ -0,0 +1,81 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Common.Dapper;
using NSubstitute;
using System;
using System.Data;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Dapper;
/// <summary>
/// Contains unit tests for the <see cref="SqliteGuidTypeHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SqliteGuidTypeHandlerTests
{
private readonly SqliteGuidTypeHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="SqliteGuidTypeHandlerTests"/> class.
/// </summary>
public SqliteGuidTypeHandlerTests()
{
_sut = new SqliteGuidTypeHandler();
}
[Fact]
public void SetValue_WhenCalled_ShouldStoreTheGuidAsItsTextRepresentation()
{
// Arrange
IDbDataParameter parameter = Substitute.For<IDbDataParameter>();
Guid guid = Guid.NewGuid();
// Act
_sut.SetValue(parameter, guid);
// Assert
Assert.Equal(guid.ToString(), (string?)parameter.Value);
}
[Fact]
public void Parse_WhenValueIsGuid_ShouldReturnTheSameGuid()
{
// Arrange
Guid guid = Guid.NewGuid();
object value = guid;
// Act
Guid parsed = _sut.Parse(value);
// Assert
Assert.Equal(guid, parsed);
}
[Fact]
public void Parse_WhenValueIsGuidText_ShouldReturnTheParsedGuid()
{
// Arrange
Guid guid = Guid.NewGuid();
object value = guid.ToString();
// Act
Guid parsed = _sut.Parse(value);
// Assert
Assert.Equal(guid, parsed);
}
[Fact]
public void Parse_WhenValueIsNotValidGuidText_ShouldThrowFormatException()
{
// Arrange
object value = "not-a-guid";
// Act
Action act = () => _sut.Parse(value);
// Assert
Assert.Throws<FormatException>(act);
}
}
@@ -18,7 +18,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
@@ -73,7 +72,7 @@ public class BookRepositoryTests
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
// check if the book was added to the context's ChangeTracker
// Check if the book was added to the context's ChangeTracker.
EntityEntry<BookEntity>? addedBook = _mockContext.ChangeTracker.Entries<BookEntity>()
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id);
Assert.NotNull(addedBook);
@@ -94,7 +93,7 @@ public class BookRepositoryTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError);
Assert.Single(_mockContext.ChangeTracker.Entries<BookEntity>()); // only the existing book should be in the context
Assert.Single(_mockContext.ChangeTracker.Entries<BookEntity>()); // Only the existing book should be in the context.
}
[Fact]
@@ -595,116 +594,6 @@ public class BookRepositoryTests
Assert.Equal(1, result.Value);
}
[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();
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
Guid libraryId = Guid.NewGuid();
BookEntity changedBook = _bookEntityFixture.Create();
changedBook.LibraryId = libraryId;
changedBook.Path = "/books/changed.epub";
changedBook.MetadataStatus = MetadataStatus.Enriched;
changedBook.BookArtwork = [_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.BookArtwork = [_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.BookArtwork).FirstOrDefaultAsync(book => book.Id == changedBook.Id);
Assert.NotNull(resetBook);
Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus);
Assert.Equal(ArtworkStatus.Pending, resetBook.BookArtwork.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 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();
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
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();
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create();
book.LibraryId = libraryId;
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.BookArtwork = [_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 GetAuthorsDisplayNamesByBookIdsAsync_WhenCalled_ShouldReturnTheAuthorDisplayNames()
{
@@ -730,7 +619,7 @@ public class BookRepositoryTests
// Assert
Assert.False(result.IsFailure);
// only the author contributor of the first book is returned; the book with no author is not included
// Only the author contributor of the first book is returned; the book with no author is not included.
Assert.Single(result.Value);
Assert.Equal("Frank Herbert", result.Value[firstBook.Id]);
}
@@ -764,4 +653,258 @@ public class BookRepositoryTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
}
[Fact]
public async Task GetByIdAsync_WhenBookExists_ShouldReturnTheBook()
{
// Arrange
BookEntity book = _bookEntityFixture.Create();
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
Result<BookEntity?> result = await _sut.GetByIdAsync(book.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(book.Id, result.Value!.Id);
}
[Fact]
public async Task GetByIdAsync_WhenBookDoesNotExist_ShouldReturnNull()
{
// Act
Result<BookEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByIdAsync_WhenBookExists_ShouldIncludeRelatedEntities()
{
// Arrange
BookEntity book = _bookEntityFixture.Create();
book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")];
book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")];
book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)];
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
Result<BookEntity?> result = await _sut.GetByIdAsync(book.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
BookEntity retrievedBook = result.Value!;
Assert.Equal(2, retrievedBook.Tags.Count);
Assert.Equal(2, retrievedBook.Genres.Count);
Assert.Equal(2, retrievedBook.ISBNs.Count);
Assert.Single(retrievedBook.BookArtwork);
}
[Fact]
public async Task GetBooksNeedingMetadataCountAsync_WhenCalled_ShouldCountOnlyBooksWhoseMetadataIsNotEnriched()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity pendingBook = _bookEntityFixture.Create();
pendingBook.LibraryId = libraryId;
pendingBook.MetadataStatus = MetadataStatus.Pending;
BookEntity enrichedBook = _bookEntityFixture.Create();
enrichedBook.LibraryId = libraryId;
enrichedBook.MetadataStatus = MetadataStatus.Enriched;
BookEntity failedBook = _bookEntityFixture.Create();
failedBook.LibraryId = libraryId;
failedBook.MetadataStatus = MetadataStatus.Failed;
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Pending;
_mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetBooksNeedingMetadataCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value);
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByLanguageCodeAscending_ShouldReturnBooksInAscendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity frenchBook = _bookEntityFixture.Create(title: "French Book");
frenchBook.LibraryId = libraryId;
frenchBook.LanguageCode = "fr";
BookEntity englishBook = _bookEntityFixture.Create(title: "English Book");
englishBook.LibraryId = libraryId;
englishBook.LanguageCode = "en";
_mockContext.Books.AddRange(frenchBook, englishBook);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "languageCode", SortOrder.Ascending, filter, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(["English Book", "French Book"], result.Value.Data.Select(book => book.Title));
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByLanguageCodeDescending_ShouldReturnBooksInDescendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity englishBook = _bookEntityFixture.Create(title: "English Book");
englishBook.LibraryId = libraryId;
englishBook.LanguageCode = "en";
BookEntity frenchBook = _bookEntityFixture.Create(title: "French Book");
frenchBook.LibraryId = libraryId;
frenchBook.LanguageCode = "fr";
_mockContext.Books.AddRange(englishBook, frenchBook);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "languageCode", SortOrder.Descending, filter, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(["French Book", "English Book"], result.Value.Data.Select(book => book.Title));
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByFormatAscending_ShouldReturnBooksInAscendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity paperbackBook = _bookEntityFixture.Create(title: "Paperback Book");
paperbackBook.LibraryId = libraryId;
paperbackBook.Format = BookFormat.Paperback;
BookEntity hardcoverBook = _bookEntityFixture.Create(title: "Hardcover Book");
hardcoverBook.LibraryId = libraryId;
hardcoverBook.Format = BookFormat.Hardcover;
_mockContext.Books.AddRange(paperbackBook, hardcoverBook);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "format", SortOrder.Ascending, filter, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(["Hardcover Book", "Paperback Book"], result.Value.Data.Select(book => book.Title));
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByFormatDescending_ShouldReturnBooksInDescendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity hardcoverBook = _bookEntityFixture.Create(title: "Hardcover Book");
hardcoverBook.LibraryId = libraryId;
hardcoverBook.Format = BookFormat.Hardcover;
BookEntity paperbackBook = _bookEntityFixture.Create(title: "Paperback Book");
paperbackBook.LibraryId = libraryId;
paperbackBook.Format = BookFormat.Paperback;
_mockContext.Books.AddRange(hardcoverBook, paperbackBook);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "format", SortOrder.Descending, filter, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(["Paperback Book", "Hardcover Book"], result.Value.Data.Select(book => book.Title));
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByMetadataProviderAscending_ShouldReturnBooksInAscendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity openLibraryBook = _bookEntityFixture.Create(title: "OpenLibrary Book");
openLibraryBook.LibraryId = libraryId;
openLibraryBook.MetadataProvider = "OpenLibrary";
BookEntity calibreBook = _bookEntityFixture.Create(title: "Calibre Book");
calibreBook.LibraryId = libraryId;
calibreBook.MetadataProvider = "Calibre";
_mockContext.Books.AddRange(openLibraryBook, calibreBook);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "metadataProvider", SortOrder.Ascending, filter, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(["Calibre Book", "OpenLibrary Book"], result.Value.Data.Select(book => book.Title));
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByMetadataProviderDescending_ShouldReturnBooksInDescendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity calibreBook = _bookEntityFixture.Create(title: "Calibre Book");
calibreBook.LibraryId = libraryId;
calibreBook.MetadataProvider = "Calibre";
BookEntity openLibraryBook = _bookEntityFixture.Create(title: "OpenLibrary Book");
openLibraryBook.LibraryId = libraryId;
openLibraryBook.MetadataProvider = "OpenLibrary";
_mockContext.Books.AddRange(calibreBook, openLibraryBook);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "metadataProvider", SortOrder.Descending, filter, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(["OpenLibrary Book", "Calibre Book"], result.Value.Data.Select(book => book.Title));
}
[Fact]
public async Task GetPaginatedAsync_WhenIgnoringTheTitlePrefixForSorting_ShouldSortByTitleStrippedOfItsPrefix()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity beneathBook = _bookEntityFixture.Create(title: "Beneath the Surface", includeMetadata: false);
beneathBook.LibraryId = libraryId;
BookEntity artOfWarBook = _bookEntityFixture.Create(title: "The Art of War", includeMetadata: false);
artOfWarBook.LibraryId = libraryId;
_mockContext.Books.AddRange(beneathBook, artOfWarBook);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, shouldIgnoreThePrefixForAlphaPicker: true);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
// Without stripping the prefix, "The Art of War" would be sorted after "Beneath the Surface", since its sort key would start with "the" instead of "art".
Assert.Equal(["The Art of War", "Beneath the Surface"], result.Value.Data.Select(book => book.Title));
}
}
@@ -1,198 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.Repositories.Books.Specifications;
using Lumina.DataAccess.Core.UoW;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Specifications;
/// <summary>
/// Contains unit tests for the <see cref="BookAlphaFilterSpecification"/> class.
/// </summary>
/// <remarks>
/// The specification builds an expression that uses the SQLite GLOB function, which can only be evaluated by the Entity Framework SQLite provider,
/// so the tests exercise the expression against a real SQLite database instead of evaluating it in memory.
/// </remarks>
[ExcludeFromCodeCoverage]
public class BookAlphaFilterSpecificationTests : IDisposable
{
private readonly string _connectionString;
private readonly SqliteConnection _anchorConnection;
private readonly LuminaDbContext _context;
private readonly BookEntityFixture _bookEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookAlphaFilterSpecificationTests"/> class.
/// </summary>
public BookAlphaFilterSpecificationTests()
{
_connectionString = $"Data Source=luminadataccess-alphaspec-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared";
_anchorConnection = new SqliteConnection(_connectionString);
_anchorConnection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connectionString).Options);
_context.Database.EnsureCreated();
}
[Fact]
public async Task ToExpression_WhenFilterAlphaKeyIsNull_ShouldMatchAllBooks()
{
// Arrange
List<BookEntity> books = await SeedBooksAsync(
_bookEntityFixture.Create(title: "The Fellowship of the Ring", includeMetadata: false),
_bookEntityFixture.Create(title: "1984", includeMetadata: false),
_bookEntityFixture.Create(title: "@home", includeMetadata: false));
BookAlphaFilterSpecification specification = new(null, false);
// Act
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
// Assert
Assert.Equal(3, matchingBooks.Count);
}
[Fact]
public async Task ToExpression_WhenFilterAlphaKeyIsALetter_ShouldMatchTitlesStartingWithThatLetter()
{
// Arrange
List<BookEntity> books = await SeedBooksAsync(
_bookEntityFixture.Create(title: "The Fellowship of the Ring", includeMetadata: false),
_bookEntityFixture.Create(title: "1984", includeMetadata: false),
_bookEntityFixture.Create(title: "Zoo", includeMetadata: false));
BookAlphaFilterSpecification specification = new("T", false);
// Act
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
// Assert
BookEntity matchedBook = Assert.Single(matchingBooks);
Assert.Equal(books[0].Id, matchedBook.Id);
}
[Fact]
public async Task ToExpression_WhenFilterAlphaKeyIsALowercaseLetter_ShouldMatchTitlesStartingWithThatLetter()
{
// Arrange
await SeedBooksAsync(
_bookEntityFixture.Create(title: "Zoo", includeMetadata: false),
_bookEntityFixture.Create(title: "moby dick", includeMetadata: false));
BookAlphaFilterSpecification specification = new("Z", false);
// Act
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
// Assert
BookEntity matchedBook = Assert.Single(matchingBooks);
Assert.Equal("Zoo", matchedBook.Title);
}
[Fact]
public async Task ToExpression_WhenFilterAlphaKeyIsNumber_ShouldMatchTitlesStartingWithADigit()
{
// Arrange
List<BookEntity> books = await SeedBooksAsync(
_bookEntityFixture.Create(title: "1984", includeMetadata: false),
_bookEntityFixture.Create(title: "The Fellowship of the Ring", includeMetadata: false));
BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.NUMBER, false);
// Act
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
// Assert
BookEntity matchedBook = Assert.Single(matchingBooks);
Assert.Equal(books[0].Id, matchedBook.Id);
}
[Fact]
public async Task ToExpression_WhenFilterAlphaKeyIsSymbol_ShouldMatchTitlesStartingWithANonAlphanumericCharacter()
{
// Arrange
List<BookEntity> books = await SeedBooksAsync(
_bookEntityFixture.Create(title: "@home", includeMetadata: false),
_bookEntityFixture.Create(title: "1984", includeMetadata: false),
_bookEntityFixture.Create(title: "Zoo", includeMetadata: false));
BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.SYMBOL, false);
// Act
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
// Assert
BookEntity matchedBook = Assert.Single(matchingBooks);
Assert.Equal(books[0].Id, matchedBook.Id);
}
[Fact]
public async Task ToExpression_WhenIgnoreThePrefixIsTrue_ShouldStripTheLeadingThePrefix()
{
// Arrange
List<BookEntity> books = await SeedBooksAsync(
_bookEntityFixture.Create(title: "The Fellowship of the Ring", includeMetadata: false),
_bookEntityFixture.Create(title: "To Kill a Mockingbird", includeMetadata: false));
BookAlphaFilterSpecification specification = new("T", true);
// Act
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
// Assert
BookEntity matchedBook = Assert.Single(matchingBooks);
Assert.Equal(books[1].Id, matchedBook.Id);
}
[Fact]
public async Task ToExpression_WhenIgnoreThePrefixIsFalse_ShouldNotStripTheLeadingThePrefix()
{
// Arrange
await SeedBooksAsync(
_bookEntityFixture.Create(title: "The Fellowship of the Ring", includeMetadata: false),
_bookEntityFixture.Create(title: "To Kill a Mockingbird", includeMetadata: false));
BookAlphaFilterSpecification specification = new("T", false);
// Act
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
// Assert
Assert.Equal(2, matchingBooks.Count);
}
[Fact]
public async Task ToExpression_WhenTitleIsEmpty_ShouldFallBackToOriginalTitle()
{
// Arrange
await SeedBooksAsync(_bookEntityFixture.Create(title: string.Empty, originalTitle: "The Real Title", includeMetadata: false));
BookAlphaFilterSpecification specification = new("T", false);
// Act
List<BookEntity> matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync();
// Assert
BookEntity matchedBook = Assert.Single(matchingBooks);
Assert.Equal("The Real Title", matchedBook.OriginalTitle);
}
/// <summary>
/// Persists the provided books to the database.
/// </summary>
/// <param name="books">The books to persist.</param>
/// <returns>The persisted books.</returns>
private async Task<List<BookEntity>> SeedBooksAsync(params BookEntity[] books)
{
_context.Books.AddRange(books);
await _context.SaveChangesAsync();
return [.. books];
}
/// <inheritdoc/>
public void Dispose()
{
_context.Dispose();
_anchorConnection.Dispose();
}
}
@@ -1,175 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Common.Dapper;
using Lumina.DataAccess.Core.Repositories.Libraries;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries;
/// <summary>
/// Contains unit tests for the <see cref="DirectoryScanFingerprintRepository"/> class.
/// </summary>
/// <remarks>
/// The repository executes parameterized raw SQL on a dedicated database connection, so the tests exercise it against a real SQLite database
/// instead of the mocked in-memory context used by the Entity Framework based repositories.
/// </remarks>
[ExcludeFromCodeCoverage]
public class DirectoryScanFingerprintRepositoryTests : IDisposable
{
private readonly string _connectionString;
private readonly SqliteConnection _anchorConnection;
private readonly LuminaDbContext _context;
private readonly DirectoryScanFingerprintRepository _sut;
private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryScanFingerprintRepositoryTests"/> class.
/// </summary>
public DirectoryScanFingerprintRepositoryTests()
{
DapperTypeHandlers.Register();
_connectionString = $"Data Source=luminadataccess-fingerprint-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared";
_anchorConnection = new SqliteConnection(_connectionString);
_anchorConnection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connectionString).Options);
_context.Database.EnsureCreated();
_sut = new DirectoryScanFingerprintRepository(_context);
}
[Fact]
public async Task GetMappedByLibraryIdAsync_WhenCalled_ShouldReturnFingerprintsOfTheLibraryMappedByPath()
{
// Arrange
(Guid libraryId, _) = await SeedLibraryGraphAsync();
UserEntity otherUser = _userEntityFixture.Create();
_context.Users.Add(otherUser);
Guid otherLibraryId = Guid.NewGuid();
LibraryEntity otherLibrary = _libraryEntityFixture.Create(id: otherLibraryId, userId: otherUser.Id);
_context.Libraries.Add(otherLibrary);
DirectoryScanFingerprintEntity firstFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1", lastWriteTimeUtc: DateTime.UtcNow.AddDays(-1));
DirectoryScanFingerprintEntity secondFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir2", lastWriteTimeUtc: DateTime.UtcNow.AddDays(-2));
DirectoryScanFingerprintEntity fingerprintOfOtherLibrary = _directoryScanFingerprintEntityFixture.Create(libraryId: otherLibraryId, path: "/dir3");
_context.DirectoryScanFingerprints.AddRange(firstFingerprint, secondFingerprint, fingerprintOfOtherLibrary);
await _context.SaveChangesAsync();
// Act
Result<Dictionary<string, DirectoryScanFingerprintEntity>> result = await _sut.GetMappedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.True(result.Value.ContainsKey("/dir1"));
Assert.True(result.Value.ContainsKey("/dir2"));
Assert.False(result.Value.ContainsKey("/dir3"));
Assert.Equal(firstFingerprint.Id, result.Value["/dir1"].Id);
Assert.Equal(secondFingerprint.Id, result.Value["/dir2"].Id);
}
[Fact]
public async Task GetMappedByLibraryIdAsync_WhenNoFingerprintsExist_ShouldReturnEmptyDictionary()
{
// Arrange
(Guid libraryId, _) = await SeedLibraryGraphAsync();
// Act
Result<Dictionary<string, DirectoryScanFingerprintEntity>> result = await _sut.GetMappedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task UpsertRangeAsync_WhenCalledWithNewFingerprints_ShouldInsertThemAndReturnUpdated()
{
// Arrange
(Guid libraryId, _) = await SeedLibraryGraphAsync();
List<DirectoryScanFingerprintEntity> fingerprints =
[
_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId),
_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId)
];
// Act
Result<Updated> result = await _sut.UpsertRangeAsync(fingerprints, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
Assert.Equal(2, await _context.DirectoryScanFingerprints.CountAsync());
}
[Fact]
public async Task UpsertRangeAsync_WhenCalledWithExistingFingerprints_ShouldUpdateTheirLastWriteTime()
{
// Arrange
(Guid libraryId, _) = await SeedLibraryGraphAsync();
DirectoryScanFingerprintEntity existingFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1", lastWriteTimeUtc: DateTime.UtcNow.AddDays(-1));
_context.DirectoryScanFingerprints.Add(existingFingerprint);
await _context.SaveChangesAsync();
DateTime newLastWriteTimeUtc = DateTime.UtcNow.AddDays(1);
DirectoryScanFingerprintEntity updatedFingerprint = _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();
}
}
@@ -1,246 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.Repositories.Libraries;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries;
/// <summary>
/// Contains unit tests for the <see cref="LibraryScanSnapshotRepository"/> class.
/// </summary>
/// <remarks>
/// The repository executes parameterized raw SQL on a dedicated database connection, so the tests exercise it against a real SQLite database
/// instead of the mocked in-memory context used by the Entity Framework based repositories.
/// </remarks>
[ExcludeFromCodeCoverage]
public class LibraryScanSnapshotRepositoryTests : IDisposable
{
private readonly string _connectionString;
private readonly SqliteConnection _anchorConnection;
private readonly LuminaDbContext _context;
private readonly LibraryScanSnapshotRepository _sut;
private readonly LibraryScanSnapshotEntityFixture _libraryScanSnapshotEntityFixture = new();
private readonly LibraryScanStagingResultsEntityFixture _libraryScanStagingResultsEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanSnapshotRepositoryTests"/> class.
/// </summary>
public LibraryScanSnapshotRepositoryTests()
{
_connectionString = $"Data Source=luminadataccess-snapshot-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared";
_anchorConnection = new SqliteConnection(_connectionString);
_anchorConnection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connectionString).Options);
_context.Database.EnsureCreated();
_sut = new LibraryScanSnapshotRepository(_context);
}
[Fact]
public async Task GetDeletedPathsAsync_WhenSnapshotPathsAreMissingFromStaging_ShouldReturnThosePaths()
{
// Arrange
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity keptSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub");
LibraryScanSnapshotEntity deletedSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/delete.epub");
_context.LibraryScanSnapshots.AddRange(keptSnapshot, deletedSnapshot);
LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/keep.epub");
_context.LibraryScanStagingResults.Add(staging);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<string>> result = await _sut.GetDeletedPathsAsync(library.Id, scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
string deletedPath = Assert.Single(result.Value);
Assert.Equal("/books/delete.epub", deletedPath);
}
[Fact]
public async Task GetDeletedPathsAsync_WhenAllSnapshotPathsArePresentInStaging_ShouldReturnEmptyList()
{
// Arrange
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub");
_context.LibraryScanSnapshots.Add(snapshot);
LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/keep.epub");
_context.LibraryScanStagingResults.Add(staging);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<string>> result = await _sut.GetDeletedPathsAsync(library.Id, scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetDeletedPathsAsync_WhenStagingOfAnotherScanMatches_ShouldStillReturnThePaths()
{
// Arrange
(UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanEntity otherScan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Completed);
_context.LibraryScans.Add(otherScan);
LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub");
_context.LibraryScanSnapshots.Add(snapshot);
LibraryScanStagingResultsEntity stagingOfOtherScan = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: otherScan.Id, path: "/books/a.epub");
_context.LibraryScanStagingResults.Add(stagingOfOtherScan);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<string>> result = await _sut.GetDeletedPathsAsync(library.Id, scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
string deletedPath = Assert.Single(result.Value);
Assert.Equal("/books/a.epub", deletedPath);
}
[Fact]
public async Task GetPathsAsync_WhenCalled_ShouldReturnAllSnapshotPathsOfTheLibrary()
{
// Arrange
(_, LibraryEntity library, _) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity firstSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub");
LibraryScanSnapshotEntity secondSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/b.epub");
_context.LibraryScanSnapshots.AddRange(firstSnapshot, secondSnapshot);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<string>> result = await _sut.GetPathsAsync(library.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Contains("/books/a.epub", result.Value);
Assert.Contains("/books/b.epub", result.Value);
}
[Fact]
public async Task GetPathsAsync_WhenNoSnapshotsExist_ShouldReturnEmptyList()
{
// Arrange
(_, LibraryEntity library, _) = await SeedScanGraphAsync();
// Act
Result<IReadOnlyList<string>> result = await _sut.GetPathsAsync(library.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task ApplySnapshotSwapAsync_WhenCalled_ShouldAuditDeletedChangedAndNewItemsAndUpdateSnapshot()
{
// Arrange
(UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity keptSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub", contentHash: 111, fileSize: 100, ticks: 1000);
LibraryScanSnapshotEntity deletedSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/delete.epub", contentHash: 222, fileSize: 200, ticks: 2000);
_context.LibraryScanSnapshots.AddRange(keptSnapshot, deletedSnapshot);
LibraryScanStagingResultsEntity unchangedStaging = _libraryScanStagingResultsEntityFixture.Create(
libraryScanId: scanId, path: "/books/keep.epub", size: 100, ticks: 1000, contentHash: 999, needsRehash: false, isNew: false);
LibraryScanStagingResultsEntity newStaging = _libraryScanStagingResultsEntityFixture.Create(
libraryScanId: scanId, path: "/books/new.epub", size: 300, ticks: 3000, contentHash: 300, needsRehash: true, isNew: true);
LibraryScanStagingResultsEntity modifiedStaging = _libraryScanStagingResultsEntityFixture.Create(
libraryScanId: scanId, path: "/books/modified.epub", size: 400, ticks: 4000, contentHash: 400, needsRehash: true, isNew: false);
_context.LibraryScanStagingResults.AddRange(unchangedStaging, newStaging, modifiedStaging);
await _context.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.ApplySnapshotSwapAsync(library.Id, scanId, user.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
// audit entries: deleted, new and modified items
List<LibraryScanResultEntity> scanResults = await _context.LibraryScanResults.AsNoTracking()
.Where(scanResult => scanResult.LibraryScanId == scanId)
.ToListAsync();
Assert.Equal(3, scanResults.Count);
Assert.Contains(scanResults, scanResult => scanResult.Path == "/books/delete.epub" && scanResult.Status == LibraryScanFileStatus.Deleted);
Assert.Contains(scanResults, scanResult => scanResult.Path == "/books/new.epub" && scanResult.Status == LibraryScanFileStatus.New);
Assert.Contains(scanResults, scanResult => scanResult.Path == "/books/modified.epub" && scanResult.Status == LibraryScanFileStatus.Modified);
Assert.DoesNotContain(scanResults, scanResult => scanResult.Path == "/books/keep.epub");
// the snapshot now contains the kept, new and modified items and no longer contains the deleted one
List<LibraryScanSnapshotEntity> snapshots = await _context.LibraryScanSnapshots.AsNoTracking()
.Where(snapshot => snapshot.LibraryId == library.Id)
.ToListAsync();
Assert.Equal(3, snapshots.Count);
Assert.Contains(snapshots, snapshot => snapshot.Path == "/books/keep.epub" && snapshot.ContentHash == 111);
Assert.Contains(snapshots, snapshot => snapshot.Path == "/books/new.epub" && snapshot.ContentHash == 300);
Assert.Contains(snapshots, snapshot => snapshot.Path == "/books/modified.epub" && snapshot.ContentHash == 400);
Assert.DoesNotContain(snapshots, snapshot => snapshot.Path == "/books/delete.epub");
// the staging results of the scan have been cleared
Assert.False(await _context.LibraryScanStagingResults.AsNoTracking().AnyAsync(staging => staging.LibraryScanId == scanId));
}
[Fact]
public async Task ApplySnapshotSwapAsync_WhenNoStagingNeedsRehash_ShouldOnlyClearStagingAndAuditDeletedItems()
{
// Arrange
(UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity keptSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub", contentHash: 111, fileSize: 100, ticks: 1000);
_context.LibraryScanSnapshots.Add(keptSnapshot);
LibraryScanStagingResultsEntity unchangedStaging = _libraryScanStagingResultsEntityFixture.Create(
libraryScanId: scanId, path: "/books/keep.epub", size: 100, ticks: 1000, needsRehash: false, isNew: false);
_context.LibraryScanStagingResults.Add(unchangedStaging);
await _context.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.ApplySnapshotSwapAsync(library.Id, scanId, user.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
Assert.False(await _context.LibraryScanResults.AsNoTracking().AnyAsync());
Assert.False(await _context.LibraryScanStagingResults.AsNoTracking().AnyAsync(staging => staging.LibraryScanId == scanId));
}
/// <summary>
/// Seeds the user, media library and media library scan required by the foreign keys of the snapshot and staging tables.
/// </summary>
/// <returns>The seeded user, media library and scan Id.</returns>
private async Task<(UserEntity User, LibraryEntity Library, Guid ScanId)> SeedScanGraphAsync()
{
UserEntity user = _userEntityFixture.Create();
_context.Users.Add(user);
LibraryEntity library = _libraryEntityFixture.Create(userId: user.Id);
_context.Libraries.Add(library);
LibraryScanEntity scan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Running);
_context.LibraryScans.Add(scan);
await _context.SaveChangesAsync();
return (user, library, scan.Id);
}
/// <inheritdoc/>
public void Dispose()
{
_context.Dispose();
_anchorConnection.Dispose();
}
}
@@ -1,300 +0,0 @@
#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.UnitTests.Core.Repositories.Libraries;
/// <summary>
/// Contains unit tests for the <see cref="LibraryScanStagingResultsRepository"/> class.
/// </summary>
/// <remarks>
/// The repository executes parameterized raw SQL on a dedicated database connection, so the tests exercise it against a real SQLite database
/// instead of the mocked in-memory context used by the Entity Framework based repositories.
/// </remarks>
[ExcludeFromCodeCoverage]
public class LibraryScanStagingResultsRepositoryTests : IDisposable
{
private readonly string _connectionString;
private readonly SqliteConnection _anchorConnection;
private readonly LuminaDbContext _context;
private readonly LibraryScanStagingResultsRepository _sut;
private readonly LibraryScanStagingResultsEntityFixture _libraryScanStagingResultsEntityFixture = new();
private readonly LibraryScanSnapshotEntityFixture _libraryScanSnapshotEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
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 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();
}
}
@@ -1,14 +1,12 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.DataAccess.Core.Repositories.MediaContributors;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -50,7 +48,7 @@ public class MediaContributorRepositoryTests
// Assert
Assert.False(result.IsFailure);
// the comparison is case-insensitive, so the existing contributor is returned and no new one is created
// The comparison is case-insensitive, so the existing contributor is returned and no new one is created.
Assert.Equal(existingContributor.Id, result.Value.Id);
Assert.Equal("Stephen King", result.Value.DisplayName);
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>());
@@ -112,4 +110,22 @@ public class MediaContributorRepositoryTests
Assert.Contains(result.Value, contributor => contributor.Id == firstContributor.Id);
Assert.Contains(result.Value, contributor => contributor.Id == thirdContributor.Id);
}
[Fact]
public async Task InsertAsync_WhenCalled_ShouldAddContributorToContextAndReturnCreated()
{
// Arrange
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
// Act
Result<Created> result = await _sut.InsertAsync(contributor, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
EntityEntry<MediaContributorEntity>? addedContributor = _mockContext.ChangeTracker.Entries<MediaContributorEntity>()
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == contributor.Id);
Assert.NotNull(addedContributor);
}
}
@@ -6,7 +6,10 @@ using Lumina.DataAccess.Core.Repositories.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
@@ -76,7 +79,7 @@ public class PluginRepositoryTests
PluginEntity updatedPlugin = _pluginFixture.Create(plugin.Id);
updatedPlugin.Name = "Updated Name";
updatedPlugin.SettingsJson = null; // the stored settings must be preserved
updatedPlugin.SettingsJson = null; // The stored settings must be preserved.
// Act
Result<Updated> result = await _sut.UpsertAsync(updatedPlugin, CancellationToken.None);
@@ -116,4 +119,71 @@ public class PluginRepositoryTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginNotFound, result.FirstError);
}
[Fact]
public async Task GetAllAsync_WhenPluginsExist_ShouldReturnAllPlugins()
{
// Arrange
List<PluginEntity> plugins = _pluginFixture.CreateMany(2);
_mockContext.Plugins.AddRange(plugins);
await _mockContext.SaveChangesAsync();
// Act
Result<IEnumerable<PluginEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(2, result.Value.Count());
Assert.Contains(result.Value, plugin => plugin.Id == plugins[0].Id);
Assert.Contains(result.Value, plugin => plugin.Id == plugins[1].Id);
}
[Fact]
public async Task GetAllAsync_WhenNoPluginsExist_ShouldReturnEmptyList()
{
// Act
Result<IEnumerable<PluginEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Empty(result.Value);
}
[Fact]
public async Task DeleteByIdAsync_WhenPluginExists_ShouldRemovePluginAndReturnDeleted()
{
// Arrange
PluginEntity existingPlugin = _pluginFixture.Create();
_mockContext.Plugins.Add(existingPlugin);
await _mockContext.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByIdAsync(existingPlugin.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
EntityEntry<PluginEntity>? deletedEntry = _mockContext.ChangeTracker.Entries<PluginEntity>()
.FirstOrDefault(entityEntry => entityEntry.Entity.Id == existingPlugin.Id);
Assert.NotNull(deletedEntry);
Assert.Equal(EntityState.Deleted, deletedEntry!.State);
}
[Fact]
public async Task DeleteByIdAsync_WhenPluginDoesNotExist_ShouldReturnError()
{
// Arrange
Guid nonExistentId = Guid.NewGuid();
// Act
Result<Deleted> result = await _sut.DeleteByIdAsync(nonExistentId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginNotFound, result.FirstError);
}
}
@@ -0,0 +1,237 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
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.Errors;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeRepository"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly ThemeRepository _sut;
private readonly ThemeEntityFixture _themeEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ThemeRepositoryTests"/> class.
/// </summary>
public ThemeRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new ThemeRepository(_mockContext);
}
[Fact]
public async Task InsertAsync_WhenThemeDoesNotExist_ShouldAddThemeToContextAndReturnCreated()
{
// Arrange
ThemeEntity theme = _themeEntityFixture.Create();
// Act
Result<Created> result = await _sut.InsertAsync(theme, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
EntityEntry<ThemeEntity>? addedTheme = _mockContext.ChangeTracker.Entries<ThemeEntity>()
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == theme.Id);
Assert.NotNull(addedTheme);
Assert.Equal(theme.ThemeId, addedTheme.Entity.ThemeId);
}
[Fact]
public async Task InsertAsync_WhenThemeAlreadyExists_ShouldReturnError()
{
// Arrange
ThemeEntity theme = _themeEntityFixture.Create();
_mockContext.Themes.Add(theme);
await _mockContext.SaveChangesAsync();
// Act
Result<Created> result = await _sut.InsertAsync(theme, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
Assert.Single(_mockContext.ChangeTracker.Entries<ThemeEntity>());
}
[Fact]
public async Task GetAllAsync_WhenCalled_ShouldReturnAllThemes()
{
// Arrange
List<ThemeEntity> themes = _themeEntityFixture.CreateMany();
_mockContext.Themes.AddRange(themes);
await _mockContext.SaveChangesAsync();
// Act
Result<IEnumerable<ThemeEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(3, result.Value.Count());
Assert.Equal(themes, result.Value);
}
[Fact]
public async Task GetAllAsync_WhenNoThemesExist_ShouldReturnEmptyList()
{
// Act
Result<IEnumerable<ThemeEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetByThemeIdAsync_WhenThemeExists_ShouldReturnTheme()
{
// Arrange
ThemeEntity theme = _themeEntityFixture.Create(themeId: "my-theme");
_mockContext.Themes.Add(theme);
await _mockContext.SaveChangesAsync();
// Act
Result<ThemeEntity?> result = await _sut.GetByThemeIdAsync(theme.ThemeId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(theme, result.Value);
}
[Fact]
public async Task GetByThemeIdAsync_WhenThemeDoesNotExist_ShouldReturnNull()
{
// Act
Result<ThemeEntity?> result = await _sut.GetByThemeIdAsync("nonexistent-theme", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task UpdateAsync_WhenThemeExists_ShouldUpdateThemeAndReturnUpdated()
{
// Arrange
ThemeEntity existingTheme = _themeEntityFixture.Create(name: "Existing Theme");
_mockContext.Themes.Add(existingTheme);
await _mockContext.SaveChangesAsync();
ThemeEntity updatedTheme = _themeEntityFixture.Create(id: existingTheme.Id, themeId: existingTheme.ThemeId, name: "Updated Theme", includeIsCurrent: true, isCurrent: true);
updatedTheme.CreatedOnUtc = existingTheme.CreatedOnUtc;
updatedTheme.CreatedBy = existingTheme.CreatedBy;
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedTheme, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
ThemeEntity? modifiedTheme = await _mockContext.Themes.FirstOrDefaultAsync(theme => theme.Id == existingTheme.Id);
Assert.NotNull(modifiedTheme);
Assert.Equal("Updated Theme", modifiedTheme.Name);
Assert.True(modifiedTheme.IsCurrent);
}
[Fact]
public async Task UpdateAsync_WhenThemeDoesNotExist_ShouldReturnError()
{
// Arrange
ThemeEntity theme = _themeEntityFixture.Create();
// Act
Result<Updated> result = await _sut.UpdateAsync(theme, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
}
[Fact]
public async Task DeleteByIdAsync_WhenThemeExists_ShouldRemoveThemeFromContextAndReturnDeleted()
{
// Arrange
ThemeEntity theme = _themeEntityFixture.Create();
_mockContext.Themes.Add(theme);
await _mockContext.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByIdAsync(theme.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
EntityEntry<ThemeEntity>? deletedTheme = _mockContext.ChangeTracker.Entries<ThemeEntity>()
.FirstOrDefault(entry => entry.State == EntityState.Deleted && entry.Entity.Id == theme.Id);
Assert.NotNull(deletedTheme);
}
[Fact]
public async Task DeleteByIdAsync_WhenThemeDoesNotExist_ShouldReturnError()
{
// Act
Result<Deleted> result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
}
[Fact]
public async Task GetCurrentAsync_WhenCurrentThemeExists_ShouldReturnCurrentTheme()
{
// Arrange
ThemeEntity currentTheme = _themeEntityFixture.Create(includeIsCurrent: true, isCurrent: true);
ThemeEntity nonCurrentTheme = _themeEntityFixture.Create(includeIsCurrent: true, isCurrent: false);
_mockContext.Themes.AddRange(currentTheme, nonCurrentTheme);
await _mockContext.SaveChangesAsync();
// Act
Result<ThemeEntity?> result = await _sut.GetCurrentAsync(CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(currentTheme, result.Value);
}
[Fact]
public async Task GetCurrentAsync_WhenNoCurrentThemeExists_ShouldReturnNull()
{
// Arrange
ThemeEntity nonCurrentTheme = _themeEntityFixture.Create(includeIsCurrent: true, isCurrent: false);
_mockContext.Themes.Add(nonCurrentTheme);
await _mockContext.SaveChangesAsync();
// Act
Result<ThemeEntity?> result = await _sut.GetCurrentAsync(CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
}
@@ -1,108 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.UoW;
/// <summary>
/// Contains unit tests for the <see cref="LuminaDbContext"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LuminaDbContextTests : IDisposable
{
private readonly string _connectionString;
private readonly SqliteConnection _anchorConnection;
private readonly LuminaDbContext _context;
private readonly BookEntityFixture _bookEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LuminaDbContextTests"/> class.
/// </summary>
public LuminaDbContextTests()
{
_connectionString = $"Data Source=luminadataccess-dbcontext-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared";
_anchorConnection = new SqliteConnection(_connectionString);
_anchorConnection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connectionString).Options);
}
[Fact]
public void OnModelCreating_WhenCalled_ShouldApplyAllEntityConfigurationsFromTheAssembly()
{
// Arrange
IModel model = _context.Model;
// Act
string[] tableNames = [.. model.GetEntityTypes().Select(entityType => entityType.GetTableName()).OfType<string>().OrderBy(name => name)];
// Assert
// The count assertion fails when a table is added or removed, reminding to update the assertions below.
Assert.Equal(29, tableNames.Length);
Assert.Contains("Books", tableNames);
Assert.Contains("Users", tableNames);
Assert.Contains("UserSettings", tableNames);
Assert.Contains("Roles", tableNames);
Assert.Contains("Permissions", tableNames);
Assert.Contains("UserRoles", tableNames);
Assert.Contains("UserPermissions", tableNames);
Assert.Contains("RolePermissions", tableNames);
Assert.Contains("Libraries", tableNames);
Assert.Contains("LibraryScans", tableNames);
Assert.Contains("LibraryScanResults", tableNames);
Assert.Contains("LibraryScanSnapshots", tableNames);
Assert.Contains("LibraryScanStagingResults", tableNames);
Assert.Contains("DirectoryScanFingerprints", tableNames);
Assert.Contains("Plugins", tableNames);
Assert.Contains("LibraryMetadataProviderConfigurations", tableNames);
Assert.Contains("LibraryArtworkProviderConfigurations", tableNames);
Assert.Contains("LibraryBookReaderConfigurations", tableNames);
Assert.Contains("Tags", tableNames);
Assert.Contains("Genres", tableNames);
Assert.Contains("LibraryContentLocations", tableNames);
Assert.Contains("BookTags", tableNames);
Assert.Contains("BookGenres", tableNames);
Assert.Contains("BookRatings", tableNames);
Assert.Contains("BookISBNs", tableNames);
Assert.Contains("Themes", tableNames);
Assert.Contains("MediaContributors", tableNames);
Assert.Contains("BookContributors", tableNames);
Assert.Contains("BookArtwork", tableNames);
}
[Fact]
public async Task SaveChangesAsync_WhenAddingBook_ShouldPersistItToTheDatabase()
{
// Arrange
_context.Database.EnsureCreated();
BookEntity book = _bookEntityFixture.Create(path: "/books/test.epub", title: "Test Book", includeMetadata: false);
book.MetadataStatus = MetadataStatus.Pending;
book.CreatedOnUtc = DateTime.UtcNow;
book.CreatedBy = Guid.NewGuid();
_context.Books.Add(book);
// Act
await _context.SaveChangesAsync();
// Assert
BookEntity? retrievedBook = await _context.Books.FindAsync(book.Id);
Assert.NotNull(retrievedBook);
Assert.Equal("Test Book", retrievedBook!.Title);
}
/// <inheritdoc/>
public void Dispose()
{
_context.Dispose();
_anchorConnection.Dispose();
}
}
@@ -14,6 +14,7 @@ using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -54,14 +55,19 @@ public class UnitOfWorkTests
yield return new object[] { nameof(IUnitOfWork.RoleRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.RoleRepository) };
yield return new object[] { nameof(IUnitOfWork.UserRoleRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.UserRoleRepository) };
yield return new object[] { nameof(IUnitOfWork.BookRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.BookRepository) };
yield return new object[] { nameof(IUnitOfWork.MediaContributorRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.MediaContributorRepository) };
yield return new object[] { nameof(IUnitOfWork.DirectoryScanFingerprintRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.DirectoryScanFingerprintRepository) };
yield return new object[] { nameof(IUnitOfWork.LibraryRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryRepository) };
yield return new object[] { nameof(IUnitOfWork.LibraryScanRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryScanRepository) };
yield return new object[] { nameof(IUnitOfWork.LibraryScanSnapshotRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryScanSnapshotRepository) };
yield return new object[] { nameof(IUnitOfWork.LibraryScanStagingResultsRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryScanStagingResultsRepository) };
yield return new object[] { nameof(IUnitOfWork.LibraryMetadataProviderConfigurationRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryMetadataProviderConfigurationRepository) };
yield return new object[] { nameof(IUnitOfWork.ArtworkProviderConfigurationRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.ArtworkProviderConfigurationRepository) };
yield return new object[] { nameof(IUnitOfWork.LibraryBookReaderConfigurationRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryBookReaderConfigurationRepository) };
yield return new object[] { nameof(IUnitOfWork.PluginRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.PluginRepository) };
yield return new object[] { nameof(IUnitOfWork.ThemeRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.ThemeRepository) };
yield return new object[] { nameof(IUnitOfWork.UserRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.UserRepository) };
yield return new object[] { nameof(IUnitOfWork.UserSettingsRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.UserSettingsRepository) };
}
[Theory]