mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 11:11:10 +00:00
Hardens test assertions and adds missing test coverage.
This commit is contained in:
1 parent
6b86fd5805
commit
1189bbaf36
489 files changed
+39982
-512
No files matched your search
+198
@@ -0,0 +1,198 @@
|
||||
#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"),
|
||||
_bookEntityFixture.Create(title: "1984"),
|
||||
_bookEntityFixture.Create(title: "@home"));
|
||||
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"),
|
||||
_bookEntityFixture.Create(title: "1984"),
|
||||
_bookEntityFixture.Create(title: "Zoo"));
|
||||
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"),
|
||||
_bookEntityFixture.Create(title: "moby dick"));
|
||||
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"),
|
||||
_bookEntityFixture.Create(title: "The Fellowship of the Ring"));
|
||||
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"),
|
||||
_bookEntityFixture.Create(title: "1984"),
|
||||
_bookEntityFixture.Create(title: "Zoo"));
|
||||
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"),
|
||||
_bookEntityFixture.Create(title: "To Kill a Mockingbird"));
|
||||
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"),
|
||||
_bookEntityFixture.Create(title: "To Kill a Mockingbird"));
|
||||
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"));
|
||||
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();
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.Books.Specifications;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Specifications;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookSearchSpecification"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookSearchSpecificationTests
|
||||
{
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenTitleContainsSearchTerm_ShouldMatchBook()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.Title = "The Fellowship of the Ring";
|
||||
book.OriginalTitle = null;
|
||||
BookSearchSpecification specification = new("Fellowship");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(book);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenOriginalTitleContainsSearchTerm_ShouldMatchBook()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.Title = "A Random Title";
|
||||
book.OriginalTitle = "Lord of the Rings: The Fellowship";
|
||||
BookSearchSpecification specification = new("Fellowship");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(book);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenOriginalTitleIsNull_ShouldMatchOnlyOnTitle()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.Title = "The Fellowship of the Ring";
|
||||
book.OriginalTitle = null;
|
||||
BookSearchSpecification specification = new("Ring");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(book);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenNeitherTitleNorOriginalTitleContainsSearchTerm_ShouldNotMatchBook()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.Title = "The Fellowship of the Ring";
|
||||
book.OriginalTitle = "The Two Towers";
|
||||
BookSearchSpecification specification = new("Hobbit");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(book);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenSearchTermIsNotPresent_ShouldFilterOutNonMatchingBooks()
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> books = _bookEntityFixture.CreateMany(3);
|
||||
books[0].Title = "The Fellowship of the Ring";
|
||||
books[1].Title = "The Two Towers";
|
||||
books[2].Title = "The Return of the King";
|
||||
BookSearchSpecification specification = new("Fellowship");
|
||||
|
||||
// Act
|
||||
IEnumerable<BookEntity> matchingBooks = books.AsQueryable().Where(specification.ToExpression());
|
||||
|
||||
// Assert
|
||||
BookEntity matchedBook = Assert.Single(matchingBooks);
|
||||
Assert.Equal(books[0].Title, matchedBook.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenTitleMatchesInDifferentCase_ShouldNotMatchCaseInsensitively()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.Title = "The Fellowship of the Ring";
|
||||
book.OriginalTitle = null;
|
||||
BookSearchSpecification specification = new("fellowship");
|
||||
|
||||
// Act
|
||||
bool result = specification.IsSatisfiedBy(book);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
#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 = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
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();
|
||||
}
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly LibraryRepository _sut;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new LibraryRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenLibraryDoesNotExist_ShouldAddLibraryToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(library, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<LibraryEntity>? addedLibrary = _mockContext.ChangeTracker.Entries<LibraryEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == library.Id);
|
||||
Assert.NotNull(addedLibrary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenLibraryAlreadyExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create();
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(library, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryAlreadyExists, result.FirstError);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<LibraryEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenLibraryExists_ShouldReturnLibraryWithContentLocations()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create();
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<LibraryEntity?> result = await _sut.GetByIdAsync(library.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(library.Id, result.Value!.Id);
|
||||
Assert.Equal(library.ContentLocations.Count, result.Value.ContentLocations.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenLibraryDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<LibraryEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllEnabledAsync_WhenCalled_ShouldReturnOnlyEnabledLibraries()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity enabledLibrary = _libraryEntityFixture.Create(isEnabled: true);
|
||||
LibraryEntity disabledLibrary = _libraryEntityFixture.Create(isEnabled: false);
|
||||
_mockContext.Libraries.AddRange(enabledLibrary, disabledLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<LibraryEntity>> result = await _sut.GetAllEnabledAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryEntity retrievedLibrary = Assert.Single(result.Value);
|
||||
Assert.Equal(enabledLibrary.Id, retrievedLibrary.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllEnabledAndUnlockedAsync_WhenCalled_ShouldReturnOnlyEnabledAndUnlockedLibraries()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity enabledUnlockedLibrary = _libraryEntityFixture.Create(isEnabled: true, isLocked: false);
|
||||
LibraryEntity enabledLockedLibrary = _libraryEntityFixture.Create(isEnabled: true, isLocked: true);
|
||||
LibraryEntity disabledUnlockedLibrary = _libraryEntityFixture.Create(isEnabled: false, isLocked: false);
|
||||
_mockContext.Libraries.AddRange(enabledUnlockedLibrary, enabledLockedLibrary, disabledUnlockedLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<LibraryEntity>> result = await _sut.GetAllEnabledAndUnlockedAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryEntity retrievedLibrary = Assert.Single(result.Value);
|
||||
Assert.Equal(enabledUnlockedLibrary.Id, retrievedLibrary.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenCalled_ShouldReturnAllLibraries()
|
||||
{
|
||||
// Arrange
|
||||
List<LibraryEntity> libraries = _libraryEntityFixture.CreateMany(3);
|
||||
_mockContext.Libraries.AddRange(libraries);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<LibraryEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count());
|
||||
Assert.Equal(libraries, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenLibraryExists_ShouldUpdateScalarPropertiesAndContentLocations()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: ["/old/path"]);
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryEntity updatedLibrary = new()
|
||||
{
|
||||
Id = library.Id,
|
||||
UserId = library.UserId,
|
||||
Title = "Updated Title",
|
||||
LibraryType = library.LibraryType,
|
||||
ContentLocations = [new LibraryContentLocationEntity { Path = "/new/path" }],
|
||||
CreatedOnUtc = library.CreatedOnUtc,
|
||||
CreatedBy = library.CreatedBy,
|
||||
UpdatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = library.UserId
|
||||
};
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
LibraryEntity? retrievedLibrary = await _mockContext.Libraries.FindAsync(library.Id);
|
||||
Assert.NotNull(retrievedLibrary);
|
||||
Assert.Equal("Updated Title", retrievedLibrary!.Title);
|
||||
Assert.Single(retrievedLibrary.ContentLocations);
|
||||
Assert.Equal("/new/path", retrievedLibrary.ContentLocations.First().Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenLibraryDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(library, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenLibraryExists_ShouldRemoveItFromContextAndReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create();
|
||||
_mockContext.Libraries.Add(library);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(library.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
|
||||
EntityEntry<LibraryEntity>? deletedLibrary = _mockContext.ChangeTracker.Entries<LibraryEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Deleted && entityEntry.Entity.Id == library.Id);
|
||||
Assert.NotNull(deletedLibrary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenLibraryDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScanRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly LibraryScanRepository _sut;
|
||||
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryScanRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new LibraryScanRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenLibraryScanDoesNotExist_ShouldAddScanToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(libraryScan, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<LibraryScanEntity>? addedScan = _mockContext.ChangeTracker.Entries<LibraryScanEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == libraryScan.Id);
|
||||
Assert.NotNull(addedScan);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenLibraryScanAlreadyExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create();
|
||||
_mockContext.LibraryScans.Add(libraryScan);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(libraryScan, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.LibraryScanAlreadyExists, result.FirstError);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<LibraryScanEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenLibraryScanExists_ShouldReturnScanWithLibraryAndUser()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create();
|
||||
_mockContext.LibraryScans.Add(libraryScan);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<LibraryScanEntity?> result = await _sut.GetByIdAsync(libraryScan.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(libraryScan.Id, result.Value!.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenLibraryScanDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<LibraryScanEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPastMonthScansByLibraryIdAsync_WhenCalled_ShouldReturnOnlyRecentScansOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create();
|
||||
LibraryScanEntity recentScan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, createdOnUtc: DateTime.UtcNow.AddDays(-1));
|
||||
LibraryScanEntity oldScan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, createdOnUtc: DateTime.UtcNow.AddMonths(-2));
|
||||
LibraryScanEntity scanOfAnotherLibrary = _libraryScanEntityFixture.Create(createdOnUtc: DateTime.UtcNow.AddDays(-1));
|
||||
_mockContext.LibraryScans.AddRange(recentScan, oldScan, scanOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<LibraryScanEntity>> result = await _sut.GetPastMonthScansByLibraryIdAsync(library.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryScanEntity retrievedScan = Assert.Single(result.Value);
|
||||
Assert.Equal(recentScan.Id, retrievedScan.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRunningScansAsync_WhenCalled_ShouldReturnOnlyRunningScans()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Running);
|
||||
LibraryScanEntity completedScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Completed);
|
||||
LibraryScanEntity pendingScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Pending);
|
||||
_mockContext.LibraryScans.AddRange(runningScan, completedScan, pendingScan);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<LibraryScanEntity>> result = await _sut.GetRunningScansAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryScanEntity retrievedScan = Assert.Single(result.Value);
|
||||
Assert.Equal(runningScan.Id, retrievedScan.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenLibraryScanExists_ShouldUpdateItsScalarProperties()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create();
|
||||
_mockContext.LibraryScans.Add(libraryScan);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryScanEntity updatedScan = new()
|
||||
{
|
||||
Id = libraryScan.Id,
|
||||
LibraryId = libraryScan.LibraryId,
|
||||
UserId = libraryScan.UserId,
|
||||
Status = LibraryScanJobStatus.Completed,
|
||||
Library = libraryScan.Library,
|
||||
User = libraryScan.User,
|
||||
CreatedOnUtc = libraryScan.CreatedOnUtc,
|
||||
CreatedBy = libraryScan.CreatedBy,
|
||||
UpdatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = libraryScan.UserId
|
||||
};
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(updatedScan, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
LibraryScanEntity? retrievedScan = await _mockContext.LibraryScans.FindAsync(libraryScan.Id);
|
||||
Assert.NotNull(retrievedScan);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, retrievedScan!.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenLibraryScanDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(libraryScan, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.LibraryScanNotFound, result.FirstError);
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScanResultRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanResultRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly LibraryScanResultRepository _sut;
|
||||
private readonly LibraryScanResultEntityFixture _libraryScanResultEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanResultRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryScanResultRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new LibraryScanResultRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenCalled_ShouldAddScanResultToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScanResultEntity libraryScanResult = _libraryScanResultEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(libraryScanResult, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<LibraryScanResultEntity>? addedScanResult = _mockContext.ChangeTracker.Entries<LibraryScanResultEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == libraryScanResult.Id);
|
||||
Assert.NotNull(addedScanResult);
|
||||
}
|
||||
}
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
#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();
|
||||
}
|
||||
}
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
#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.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();
|
||||
|
||||
/// <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 =
|
||||
[
|
||||
new HashedFileSystemFileDto { Path = "/books/a.epub", Size = 10, Ticks = 100, CurrentHash = 999, OldHash = 0 },
|
||||
new HashedFileSystemFileDto { 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,108 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.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.Collections.Generic;
|
||||
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;
|
||||
|
||||
/// <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(23, 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("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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveChangesAsync_WhenAddingBook_ShouldPersistItToTheDatabase()
|
||||
{
|
||||
// Arrange
|
||||
_context.Database.EnsureCreated();
|
||||
BookEntity book = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = Guid.NewGuid(),
|
||||
Path = "/books/test.epub",
|
||||
Title = "Test Book",
|
||||
MetadataStatus = MetadataStatus.Pending,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedBy = null
|
||||
};
|
||||
_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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user