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]
@@ -255,30 +255,17 @@ public class FileProviderServiceTests
public void GetFileAsync_WhenUserHasAccess_ShouldReturnFileContents()
{
// Arrange
string tempFilePath = Path.GetTempFileName();
try
{
byte[] expectedContents = [1, 2, 3, 4, 5];
File.WriteAllBytes(tempFilePath, expectedContents);
FileSystemPathId path = _fileSystemPathIdFixture.Create();
byte[] expectedContents = [1, 2, 3, 4, 5];
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true);
_mockFileSystem.File.ReadAllBytes(path.Path).Returns(expectedContents);
FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true);
// Act
Result<byte[]> result = _sut.GetFileAsync(path);
// We need to update the _fileSystem mock to use the real file system for this method
_mockFileSystem.File.ReadAllBytes(tempFilePath).Returns(x => File.ReadAllBytes(x.Arg<string>()));
// Act
Result<byte[]> result = _sut.GetFileAsync(path);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedContents, result.Value);
}
finally
{
// clean up
File.Delete(tempFilePath);
}
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedContents, result.Value);
}
[Fact]
@@ -300,52 +287,34 @@ public class FileProviderServiceTests
public void GetFileAsync_WhenFileIsEmpty_ShouldReturnEmptyByteArray()
{
// Arrange
string tempFilePath = Path.GetTempFileName();
try
{
FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true);
FileSystemPathId path = _fileSystemPathIdFixture.Create();
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true);
_mockFileSystem.File.ReadAllBytes(path.Path).Returns([]);
// Act
Result<byte[]> result = _sut.GetFileAsync(path);
// Act
Result<byte[]> result = _sut.GetFileAsync(path);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
finally
{
// clean up
File.Delete(tempFilePath);
}
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public void GetLastWriteTime_WhenUserHasAccess_ShouldReturnLastWriteTime()
{
// Arrange
string tempFilePath = Path.GetTempFileName();
try
{
File.WriteAllText(tempFilePath, "Test content");
FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath);
DateTime expectedDateTime = File.GetLastWriteTime(tempFilePath);
FileSystemPathId path = _fileSystemPathIdFixture.Create();
DateTime expectedDateTime = new(2024, 1, 2, 3, 4, 5);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
_mockFileSystem.File.GetLastWriteTime(path.Path).Returns(expectedDateTime);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
_mockFileSystem.File.GetLastWriteTime(path.Path).Returns(expectedDateTime);
// Act
Result<Optional<DateTime>> result = _sut.GetLastWriteTime(path);
// Act
Result<Optional<DateTime>> result = _sut.GetLastWriteTime(path);
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value.HasValue);
Assert.Equal(expectedDateTime, result.Value.Value, TimeSpan.FromSeconds(1));
}
finally
{
File.Delete(tempFilePath);
}
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value.HasValue);
Assert.Equal(expectedDateTime, result.Value.Value, TimeSpan.FromSeconds(1));
}
[Fact]
@@ -367,28 +336,18 @@ public class FileProviderServiceTests
public void GetCreationTime_WhenUserHasAccess_ShouldReturnCreationTime()
{
// Arrange
string tempFilePath = Path.GetTempFileName();
try
{
File.WriteAllText(tempFilePath, "Test content");
FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath);
DateTime expectedDateTime = File.GetCreationTime(tempFilePath);
FileSystemPathId path = _fileSystemPathIdFixture.Create();
DateTime expectedDateTime = new(2024, 1, 2, 3, 4, 5);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
_mockFileSystem.File.GetCreationTime(path.Path).Returns(expectedDateTime);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
_mockFileSystem.File.GetCreationTime(path.Path).Returns(expectedDateTime);
// Act
Result<Optional<DateTime>> result = _sut.GetCreationTime(path);
// Act
Result<Optional<DateTime>> result = _sut.GetCreationTime(path);
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value.HasValue);
Assert.Equal(expectedDateTime, result.Value.Value, TimeSpan.FromSeconds(1));
}
finally
{
File.Delete(tempFilePath);
}
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value.HasValue);
Assert.Equal(expectedDateTime, result.Value.Value, TimeSpan.FromSeconds(1));
}
[Fact]
@@ -410,29 +369,20 @@ public class FileProviderServiceTests
public void GetSize_WhenUserHasAccess_ShouldReturnFileSize()
{
// Arrange
string tempFilePath = Path.GetTempFileName();
try
{
string content = "Test content";
File.WriteAllText(tempFilePath, content);
FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath);
long expectedSize = new FileInfo(tempFilePath).Length;
FileSystemPathId path = _fileSystemPathIdFixture.Create();
long expectedSize = 42;
IFileInfo mockFileInfo = Substitute.For<IFileInfo>();
mockFileInfo.Length.Returns(expectedSize);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
_mockFileSystem.FileInfo.New(path.Path).Returns(mockFileInfo);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
_mockFileSystem.FileInfo.New(path.Path).Returns(new FileInfoWrapper(_mockFileSystem, new FileInfo(tempFilePath)));
// Act
Result<long?> result = _sut.GetSize(path);
// Act
Result<long?> result = _sut.GetSize(path);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(expectedSize, result.Value);
}
finally
{
File.Delete(tempFilePath);
}
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(expectedSize, result.Value);
}
[Fact]
@@ -601,7 +551,7 @@ public class FileProviderServiceTests
_mockFileSystem.Path.Combine(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1)));
// Simulate the behavior of CreateUniqueFilePath
// Simulate the behavior of CreateUniqueFilePath.
int copyNumber = 1;
_mockFileSystem.File.Exists(Arg.Any<string>())
.Returns(x =>
@@ -920,11 +870,11 @@ public class FileProviderServiceTests
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
_mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath);
// Mock successful creation of parent directory FileSystemPathId
// Mock successful creation of parent directory FileSystemPathId.
FileSystemPathId parentDirectoryPathId = _fileSystemPathIdFixture.Create(parentPath);
_mockFileSystem.Path.GetDirectoryName(path.Path).Returns(parentPath);
// Mock permissions: executable for the file, but not writable for the parent directory
// Mock permissions: executable for the file, but not writable for the parent directory.
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute).Returns(true);
_mockFileSystemPermissionsService.CanAccessPath(Arg.Is<FileSystemPathId>(x => x.Path == parentPath), FileAccessMode.Write).Returns(false);
@@ -2,17 +2,16 @@
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
using Microsoft.Extensions.DependencyInjection;
@@ -20,8 +19,6 @@ using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -40,14 +37,11 @@ public class BooksFileSystemDiscoveryJobTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
private readonly IDirectoryScanFingerprintRepository _mockDirectoryScanFingerprintRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly BooksFileSystemDiscoveryJob _sut;
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
@@ -66,10 +60,8 @@ public class BooksFileSystemDiscoveryJobTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockDirectoryScanFingerprintRepository = Substitute.For<IDirectoryScanFingerprintRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
_mockUnitOfWork.DirectoryScanFingerprintRepository.Returns(_mockDirectoryScanFingerprintRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
@@ -88,47 +80,6 @@ public class BooksFileSystemDiscoveryJobTests
};
}
[Fact]
public async Task ExecuteAsync_WhenContentLocationContainsBookFiles_ShouldDiscoverAndStageThemAndComplete()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
temporaryLibraryDirectory.CreateFile("book1.pdf", "book content");
temporaryLibraryDirectory.CreateFile("notes.log", "not a book");
string subdirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("sub");
File.WriteAllText(Path.Combine(subdirectoryPath, "book2.epub"), "another book content");
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: false);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
_mockDirectoryScanFingerprintRepository.UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
IReadOnlyList<LibraryScanStagingResultsEntity>? actualEntities = _mockStagingResultsRepository.ReceivedCalls()
.Where(call => call.GetMethodInfo().Name == nameof(ILibraryScanStagingResultsRepository.InsertRangeAsync))
.Select(call => call.GetArguments().FirstOrDefault() as IReadOnlyList<LibraryScanStagingResultsEntity>)
.FirstOrDefault();
Assert.True(actualEntities is not null, $"InsertRangeAsync was not called. Received: {string.Join(", ", _mockStagingResultsRepository.ReceivedCalls().Select(call => call.GetMethodInfo().Name))}");
Assert.Equal(
["book1.pdf", "book2.epub"],
actualEntities!.Select(entity => Path.GetFileName(entity.Path)).OrderBy(name => name, StringComparer.Ordinal));
await _mockDirectoryScanFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
@@ -178,227 +129,4 @@ public class BooksFileSystemDiscoveryJobTests
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenFastSkipIsEnabledAndDirectoryDidNotChange_ShouldSkipTheDirectoryAndUpsertOnlyChangedFingerprints()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
string unchangedDirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("unchanged");
File.WriteAllText(Path.Combine(unchangedDirectoryPath, "skip.pdf"), "unchanged book content");
string changedDirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("changed");
File.WriteAllText(Path.Combine(changedDirectoryPath, "book.pdf"), "changed book content");
DirectoryInfo unchangedDirectory = new(unchangedDirectoryPath);
string unchangedDirectoryFullName = unchangedDirectory.FullName;
DateTime unchangedDirectoryLastWriteTimeUtc = unchangedDirectory.LastWriteTimeUtc;
DirectoryInfo changedDirectory = new(changedDirectoryPath);
string changedDirectoryFullName = changedDirectory.FullName;
DirectoryInfo rootDirectory = new(temporaryLibraryDirectory.Path);
string rootDirectoryFullName = rootDirectory.FullName;
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>
{
[unchangedDirectoryFullName] = _directoryScanFingerprintEntityFixture.Create(
libraryId: _libraryId.Value,
path: unchangedDirectoryFullName,
lastWriteTimeUtc: unchangedDirectoryLastWriteTimeUtc)
}));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
_mockDirectoryScanFingerprintRepository.UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities =>
entities.Count == 1 && Path.GetFileName(entities.Single().Path) == "book.pdf"),
Arg.Any<CancellationToken>());
await _mockDirectoryScanFingerprintRepository.Received(1).UpsertRangeAsync(
Arg.Is<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(entities =>
entities.Count == 2
&& entities.Any(entity => entity.Path == rootDirectoryFullName)
&& entities.Any(entity => entity.Path == changedDirectoryFullName)
&& entities.All(entity => entity.Path != unchangedDirectoryFullName)
&& entities.All(entity => entity.LibraryId == _libraryId.Value)),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLoadingDirectoryScanFingerprintsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to load the directory scan fingerprints"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenUpsertingDirectoryScanFingerprintsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
temporaryLibraryDirectory.CreateSubdirectory("changed");
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>()));
_mockDirectoryScanFingerprintRepository.UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to upsert the directory scan fingerprints"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenInsertingStagingResultsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
temporaryLibraryDirectory.CreateFile("book.pdf", "book content");
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: false);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to insert the staging results"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDirectoryScanFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenJobHasLinkedChildren_ShouldExecuteEachChildAndComplete()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
temporaryLibraryDirectory.CreateFile("book1.pdf", "book content");
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: false);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
mockChild.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
.Returns(Task.CompletedTask);
_sut.AddChild(mockChild);
object input = new();
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), input, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await mockChild.Received(1).ExecuteAsync(Arg.Any<Guid>(), Arg.Is<object>(executedInput => executedInput == input), Arg.Any<CancellationToken>());
}
/// <summary>
/// Test helper managing a temporary library directory, deleted when the test finishes.
/// </summary>
private sealed class TemporaryLibraryDirectory : IDisposable
{
private bool _disposed;
public TemporaryLibraryDirectory()
{
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-books-discovery-{Guid.NewGuid()}");
Directory.CreateDirectory(Path);
}
public string Path { get; }
public void CreateFile(string fileName, string content)
{
File.WriteAllText(System.IO.Path.Combine(Path, fileName), content);
}
public string CreateSubdirectory(string name)
{
string subdirectoryPath = System.IO.Path.Combine(Path, name);
Directory.CreateDirectory(subdirectoryPath);
return subdirectoryPath;
}
public void Dispose()
{
if (!_disposed)
{
try
{
Directory.Delete(Path, recursive: true);
}
catch (IOException)
{
// best effort cleanup of the temporary library directory
}
_disposed = true;
}
}
}
}
@@ -8,16 +8,13 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Infrastructure.Fixtures.Common.Setup;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -31,8 +28,6 @@ namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrar
[ExcludeFromCodeCoverage]
public class BookArtworkServiceTests
{
private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024;
private readonly IEnvironmentContext _mockEnvironmentContext;
private readonly IFileTypeService _mockFileTypeService;
private readonly IFileProviderService _mockFileProviderService;
@@ -45,7 +40,6 @@ public class BookArtworkServiceTests
private readonly PathSegmentFixture _pathSegmentFixture = new();
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
private readonly StubHttpMessageHandler _stubHttpMessageHandler = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookArtworkServiceTests"/> class.
@@ -64,7 +58,6 @@ public class BookArtworkServiceTests
_mockPathService.PathSeparator.Returns('\\');
_mockHttpClientFactory = Substitute.For<IHttpClientFactory>();
_mockHttpClientFactory.CreateClient().Returns(new HttpClient(_stubHttpMessageHandler));
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books");
_mockMediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
@@ -73,91 +66,6 @@ public class BookArtworkServiceTests
_sut = new BookArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkExists_ShouldCopyItAndReturnARelativePath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
FileSystemPathId copiedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(copiedFileId));
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpeg");
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath);
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value);
_mockFileProviderService.Received(1).CopyFile(
Arg.Is<FileSystemPathId>(pathId => pathId.Path == sourcePath),
Arg.Any<FileSystemPathId>(),
true);
_mockFileProviderService.Received(1).RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg");
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenAuthorNameIsMissing_ShouldUseUnknownForTheDirectorySegment()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName: "Unknown", bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName: " ", bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockPathService.Received(1).SanitizeSegment("Unknown");
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound()
{
@@ -174,90 +82,6 @@ public class BookArtworkServiceTests
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkIsALink_ShouldReturnInvalidPath()
{
// Arrange
string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-junction-target-{Guid.NewGuid():N}");
Directory.CreateDirectory(targetDirectory);
string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-junction-link-{Guid.NewGuid():N}");
if (!TryCreateJunction(linkPath, targetDirectory))
{
Directory.Delete(targetDirectory, true);
return; // the environment does not support creating reparse points
}
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
// Windows removes a junction with Directory.Delete, while Unix-like platforms unlink the symbolic link with File.Delete
if (OperatingSystem.IsWindows())
Directory.Delete(linkPath, true);
else
File.Delete(linkPath);
Directory.Delete(targetDirectory, true);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkExceedsMaxSize_ShouldReturnFileTooLarge()
{
// Arrange
string sourcePath = CreateTempImageFile(smallImageBytes: (int)MAX_ARTWORK_SIZE_BYTES + 1);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkIsNotAnImage_ShouldReturnCoverFileMustBeAnImage()
{
// Arrange
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.None));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.CoverFileMustBeAnImage, result.FirstError);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound()
{
@@ -269,130 +93,6 @@ public class BookArtworkServiceTests
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRemoteUrlIsProvided_ShouldDownloadAndStoreTheArtwork()
{
// Arrange
byte[] imageBytes = new byte[1024];
_stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, imageBytes);
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.Received(1).CopyFile(
Arg.Is<FileSystemPathId>(pathId => pathId.Path.StartsWith(Path.GetTempPath())),
Arg.Any<FileSystemPathId>(),
true);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRemoteDownloadReturnsAnErrorStatus_ShouldReturnFileNotFound()
{
// Arrange
_stubHttpMessageHandler.SetResponse(HttpStatusCode.NotFound, []);
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRemoteDownloadExceedsMaxSize_ShouldReturnFileTooLarge()
{
// Arrange
_stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[MAX_ARTWORK_SIZE_BYTES + 1]);
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenArtworkHasBothLocalPathAndRemoteUrl_ShouldUseTheLocalFileWithoutDeletingIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.True(File.Exists(sourcePath));
_mockFileProviderService.Received(1).CopyFile(
Arg.Is<FileSystemPathId>(pathId => pathId.Path == sourcePath),
Arg.Any<FileSystemPathId>(),
true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRemoteDownloadIsCancelled_ShouldRethrowCancellation()
{
// Arrange
CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
async Task Act()
{
await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), cancellationTokenSource.Token);
}
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenFileExistenceCheckFails_ShouldReturnTheError()
{
@@ -409,223 +109,6 @@ public class BookArtworkServiceTests
Assert.Equal("FileSystem.Error", result.FirstError.Code);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenImageTypeDetectionFails_ShouldReturnTheError()
{
// Arrange
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("FileSystem.Error", "Failed to detect the image type"));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenCreatingTheArtworkDirectoryFails_ShouldReturnTheError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
.Returns(Error.Failure("Directory.Error", "Failed to create the artwork directory"));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Directory.Error", result.FirstError.Code);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenDirectoryExistenceCheckFails_ShouldReturnTheError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
.Returns(Error.Failure("Directory.Error", "Failed to check the artwork directory"));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Directory.Error", result.FirstError.Code);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenCopyingTheArtworkFails_ShouldReturnTheError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Error.Failure("FileSystem.Error", "Failed to copy the artwork"));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
_mockFileProviderService.DidNotReceive().RenameFile(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRenamingTheCopiedArtworkFails_ShouldReturnTheError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork"));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenAuthorNameCannotBeSanitized_ShouldReturnInvalidPath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media");
string booksPath = Path.Combine(mediaRoot, "books");
_mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot));
_mockPathService.CombinePath(mediaRoot, "books").Returns(Result.From(booksPath));
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.Arg<string>();
return name == $"{libraryName}-{libraryId}"
? Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false))
: Errors.FileSystemManagement.InvalidPath;
});
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public void DeleteBookArtwork_WhenListingTheCoverFilesFails_ShouldReturnSuccessAndDeleteNothing()
{
@@ -712,7 +195,7 @@ public class BookArtworkServiceTests
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
// every directory except the artwork directory itself already exists, so that only the final directory is created
// Every directory except the artwork directory itself already exists, so that only the final directory is created.
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
.Returns(callInfo => Result.From(!string.Equals(callInfo.Arg<FileSystemPathId>().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase)));
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
@@ -741,57 +224,4 @@ public class BookArtworkServiceTests
authorName,
$"{bookTitle}-{bookId}");
}
/// <summary>
/// Creates a temporary image file with the given size and returns its path.
/// </summary>
/// <param name="smallImageBytes">The size of the temporary image file, in bytes.</param>
/// <returns>The file system path of the created temporary image file.</returns>
private static string CreateTempImageFile(int smallImageBytes)
{
string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-source-{Guid.NewGuid():N}.jpg");
File.WriteAllBytes(sourcePath, new byte[smallImageBytes]);
return sourcePath;
}
/// <summary>
/// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms.
/// </summary>
/// <param name="linkPath">The file system path of the link to create.</param>
/// <param name="targetDirectory">The file system path of the directory the link points to.</param>
/// <returns><see langword="true"/> when the link was created, <see langword="false"/> otherwise.</returns>
private static bool TryCreateJunction(string linkPath, string targetDirectory)
{
try
{
System.Diagnostics.ProcessStartInfo startInfo = OperatingSystem.IsWindows()
? new()
{
FileName = "cmd.exe",
Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"",
CreateNoWindow = true,
UseShellExecute = false
}
: new()
{
FileName = "ln",
CreateNoWindow = true,
UseShellExecute = false
};
if (!OperatingSystem.IsWindows())
{
startInfo.ArgumentList.Add("-s");
startInfo.ArgumentList.Add(targetDirectory);
startInfo.ArgumentList.Add(linkPath);
}
System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo)!;
process.WaitForExit(5000);
return process.ExitCode == 0;
}
catch (Exception)
{
return false;
}
}
}
@@ -3,11 +3,8 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Reading;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -19,10 +16,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -33,7 +27,7 @@ namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrar
/// Contains unit tests for the <see cref="BookReadingService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookReadingServiceTests : IDisposable
public class BookReadingServiceTests
{
private readonly IPluginManager _mockPluginManager;
private readonly IPlugin _mockPlugin;
@@ -42,14 +36,11 @@ public class BookReadingServiceTests : IDisposable
private readonly ILibraryBookReaderConfigurationRepository _mockConfigurationRepository;
private readonly IServiceProvider _serviceProvider;
private readonly BookReadingService _sut;
private readonly TestBookReaderEnablementCache _enablementCache = new();
private readonly BookReaderEnablementCache _enablementCache = new();
private readonly Guid _pluginId = Guid.NewGuid();
private readonly Guid _bookId = Guid.NewGuid();
private readonly Guid _libraryId = Guid.NewGuid();
private readonly string _bookPath;
private readonly ReadingDocumentDtoFixture _readingDocumentDtoFixture = new();
private readonly ReadingSpineItemDtoFixture _readingSpineItemDtoFixture = new();
private readonly ReadingResourceInfoDtoFixture _readingResourceInfoDtoFixture = new();
private readonly LibraryBookReaderConfigurationEntityFixture _configurationEntityFixture = new();
/// <summary>
@@ -79,136 +70,12 @@ public class BookReadingServiceTests : IDisposable
_serviceProvider = services.BuildServiceProvider();
IServiceScopeFactory serviceScopeFactory = _serviceProvider.GetRequiredService<IServiceScopeFactory>();
_bookPath = Path.Combine(Path.GetTempPath(), $"lumina-test-book-{Guid.NewGuid():N}.epub");
File.WriteAllText(_bookPath, "test epub content");
// The resolution and enablement guards under test stop before the book file is probed, so no real file is needed.
_bookPath = $"lumina-test-book-{Guid.NewGuid():N}.epub";
_sut = new BookReadingService(_serviceProvider, _mockPluginManager, _enablementCache, serviceScopeFactory, Substitute.For<ILogger<BookReadingService>>());
}
[Fact]
public async Task GetManifestAsync_WhenBookIsNotCached_ShouldExtractAndReturnTheManifest()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(document.Title, result.Value.Title);
Assert.Equal(document.Author, result.Value.Author);
await _mockReader.Received(1).OpenAsync(_bookPath, Arg.Any<string>(), Arg.Any<bool>(), cancellationToken);
}
[Fact]
public async Task GetManifestAsync_WhenFileIsUnchanged_ShouldReuseTheCachedDocument()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
Result<ReadingManifestResponse> secondResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
// Assert
Assert.False(secondResult.IsFailure);
await _mockReader.Received(1).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenFileChanged_ShouldReExtractTheBook()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
File.WriteAllText(_bookPath, "modified epub content, longer than before");
Result<ReadingManifestResponse> secondResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
// Assert
Assert.False(secondResult.IsFailure);
await _mockReader.Received(2).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenRenderingPreferenceDiffers_ShouldExtractTheBookTwice()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
Result<ReadingManifestResponse> secondResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: true, cancellationToken);
// Assert
Assert.False(secondResult.IsFailure);
await _mockReader.Received(2).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockReader.Received(1).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), false, Arg.Any<CancellationToken>());
await _mockReader.Received(1).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), true, Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenBothRenderingPreferencesAreExtracted_ShouldKeepTheirWorkingDirectoriesSeparate()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: true, cancellationToken);
// The text extraction must survive the image extraction of the same book, and still be served from the cache.
Result<ReadingManifestResponse> thirdResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
// Assert
Assert.False(thirdResult.IsFailure);
string textWorkingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text");
string imageWorkingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "images");
Assert.True(File.Exists(Path.Combine(textWorkingDirectory, "sections", "0.html")));
Assert.True(File.Exists(Path.Combine(imageWorkingDirectory, "sections", "0.html")));
await _mockReader.Received(2).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenConcurrentRequests_ShouldShareASingleExtraction()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
TaskCompletionSource<bool> extractionStarted = new();
TaskCompletionSource<bool> allowExtractionToFinish = new();
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
extractionStarted.SetResult(true);
await allowExtractionToFinish.Task;
return document;
}));
// Act
Task<Result<ReadingManifestResponse>> firstTask = _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
await extractionStarted.Task;
Task<Result<ReadingManifestResponse>> secondTask = _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
allowExtractionToFinish.SetResult(true);
Result<ReadingManifestResponse> firstResult = await firstTask;
Result<ReadingManifestResponse> secondResult = await secondTask;
// Assert
Assert.False(firstResult.IsFailure);
Assert.False(secondResult.IsFailure);
await _mockReader.Received(1).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError()
{
@@ -241,284 +108,34 @@ public class BookReadingServiceTests : IDisposable
}
[Fact]
public async Task GetSectionAsync_WhenSectionExists_ShouldReturnSanitizedContent()
public async Task GetManifestAsync_WhenConfigurationsReadFails_ShouldReturnError()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("section-1", result.Value.LocationRef);
Assert.Contains("Chapter 1", result.Value.ContentHtml, StringComparison.Ordinal);
}
[Fact]
public async Task GetSectionAsync_WhenSectionDoesNotExist_ShouldReturnSectionNotFoundError()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "missing-section", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.SectionNotFound, result.FirstError);
}
[Fact]
public async Task GetSectionAsync_WhenSectionFileDoesNotExist_ShouldReturnSectionNotFoundError()
{
// Arrange
ReadingDocumentDto document = _readingDocumentDtoFixture.Create(
title: "Test Book",
tableOfContents: [],
spine:
[
_readingSpineItemDtoFixture.Create(locationRef: "section-1", title: "Chapter 1", relativeSectionFilePath: "sections/missing.html")
],
resources: new Dictionary<string, ReadingResourceInfoDto>()
);
StubOpenAsyncToExtract(document);
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.SectionNotFound, result.FirstError);
}
[Fact]
public async Task GetSectionAsync_WhenSectionPathEscapesTheWorkingDirectory_ShouldReturnSectionNotFoundError()
{
// Arrange
ReadingDocumentDto document = _readingDocumentDtoFixture.Create(
title: "Test Book",
tableOfContents: [],
spine:
[
_readingSpineItemDtoFixture.Create(locationRef: "section-1", title: "Chapter 1", relativeSectionFilePath: "../../escape.html")
],
resources: new Dictionary<string, ReadingResourceInfoDto>()
);
StubOpenAsyncToExtract(document);
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.SectionNotFound, result.FirstError);
}
[Fact]
public async Task GetResourceAsync_WhenResourceDoesNotExistInTheDocument_ShouldReturnResourceNotFoundError()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "missing-key", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.ResourceNotFound, result.FirstError);
await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetResourceAsync_WhenResourcePathEscapesTheWorkingDirectory_ShouldReturnResourceNotFoundError()
{
// Arrange
ReadingDocumentDto document = _readingDocumentDtoFixture.Create(
title: "Test Book",
tableOfContents: [],
spine: [],
resources: new Dictionary<string, ReadingResourceInfoDto>
{
["escaping"] = _readingResourceInfoDtoFixture.Create(relativeFilePath: "../../escape.png", mimeType: "image/png")
}
);
StubOpenAsyncToExtract(document);
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "escaping", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.ResourceNotFound, result.FirstError);
await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetResourceAsync_WhenResourceFileAlreadyExists_ShouldServeItFromDiskWithoutCallingTheReader()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
string workingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text");
string resourceFilePath = Path.Combine(workingDirectory, "resources", "cover.png");
Directory.CreateDirectory(Path.GetDirectoryName(resourceFilePath)!);
File.WriteAllBytes(resourceFilePath, [1, 2, 3]);
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(new byte[] { 1, 2, 3 }, result.Value.Data);
Assert.Equal("image/png", result.Value.MimeType);
await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetResourceAsync_WhenResourceFileDoesNotExist_ShouldProduceItAndCacheItToDisk()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
byte[] producedResource = [4, 5, 6];
_mockReader.GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), "cover", Arg.Any<CancellationToken>()).Returns(producedResource);
// Act
Result<ReadingResourceDataDto> firstResult = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
Result<ReadingResourceDataDto> secondResult = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.False(firstResult.IsFailure);
Assert.Equal(new byte[] { 4, 5, 6 }, firstResult.Value.Data);
Assert.Equal("image/png", firstResult.Value.MimeType);
Assert.False(secondResult.IsFailure);
Assert.Equal(new byte[] { 4, 5, 6 }, secondResult.Value.Data);
Assert.Equal("image/png", secondResult.Value.MimeType);
await _mockReader.Received(1).GetResourceAsync(_bookPath, Arg.Any<string>(), "cover", Arg.Any<CancellationToken>());
string cachedFilePath = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text", "resources", "cover.png");
Assert.True(File.Exists(cachedFilePath));
Assert.Equal(new byte[] { 4, 5, 6 }, File.ReadAllBytes(cachedFilePath));
}
[Fact]
public async Task GetResourceAsync_WhenReaderIsDisabledForTheLibrary_ShouldReturnReaderDisabledError()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
// The resource already exists on disk, from an earlier extraction, but the enablement is read on every request, so it must not be served.
string workingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text");
string resourceFilePath = Path.Combine(workingDirectory, "resources", "cover.png");
Directory.CreateDirectory(Path.GetDirectoryName(resourceFilePath)!);
File.WriteAllBytes(resourceFilePath, [1, 2, 3]);
.Returns(Error.Failure("Reading.Error", "Failed to read the configuration"));
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.ReaderDisabled, result.FirstError);
await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
Assert.Equal("Reading.Error", result.FirstError.Code);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetResourceAsync_WhenEnablementCacheSaysDisabledAndResourceFileAlreadyExists_ShouldNotServeTheResource()
public async Task GetSectionAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
// The reader was disabled after the book was extracted, so the enablement cache already knows it; the request must be cut
// off before the already extracted resource on disk is considered, and without consulting the database again.
_enablementCache.Set(_libraryId, _pluginId, isEnabled: false);
string workingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text");
string resourceFilePath = Path.Combine(workingDirectory, "resources", "cover.png");
Directory.CreateDirectory(Path.GetDirectoryName(resourceFilePath)!);
File.WriteAllBytes(resourceFilePath, [1, 2, 3]);
_mockPluginManager.GetPlugins().Returns([]);
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.ReaderDisabled, result.FirstError);
await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetResourceAsync_WhenReaderThrowsWhileProducingTheResource_ShouldReturnResourceProductionFailedError()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
_mockReader.GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), "cover", Arg.Any<CancellationToken>())
.Returns(Task.FromException<byte[]>(new InvalidOperationException("The page renderer failed")));
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Reading.ResourceProductionFailed", result.FirstError.Code);
await _mockReader.Received(1).GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), "cover", Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetResourceAsync_WhenReaderProductionIsCancelled_ShouldPropagateTheCancellation()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
_mockReader.GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), "cover", Arg.Any<CancellationToken>())
.Returns(Task.FromException<byte[]>(new OperationCanceledException()));
// Act
Task<Result<ReadingResourceDataDto>> operationTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
[Fact]
public async Task GetSectionAsync_WhenStylesArePreserved_ShouldKeepTheStyleAttributeInTheContent()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtractStyledContent(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: true, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Contains("style", result.Value.ContentHtml, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetSectionAsync_WhenStylesAreNotPreserved_ShouldStripTheStyleAttributeFromTheContent()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtractStyledContent(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.DoesNotContain("style", result.Value.ContentHtml, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("color:red", result.Value.ContentHtml, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Chapter 1", result.Value.ContentHtml, StringComparison.Ordinal);
Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
@@ -567,325 +184,4 @@ public class BookReadingServiceTests : IDisposable
Assert.False(result.Value.IsAvailable);
Assert.Equal(nameof(Errors.Reading.ReaderDisabled), result.Value.ErrorCode);
}
[Fact]
public async Task GetManifestAsync_WhenReaderOpenThrowsFileNotFoundException_ShouldReturnBookFileNotFoundError()
{
// Arrange
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<ReadingDocumentDto>(new FileNotFoundException("book missing")));
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.BookFileNotFound, result.FirstError);
}
[Fact]
public async Task GetManifestAsync_WhenReaderOpenThrowsDirectoryNotFoundException_ShouldReturnBookFileNotFoundError()
{
// Arrange
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<ReadingDocumentDto>(new DirectoryNotFoundException("directory missing")));
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.BookFileNotFound, result.FirstError);
}
[Fact]
public async Task GetManifestAsync_WhenReaderOpenThrowsOtherException_ShouldReturnExtractionFailedError()
{
// Arrange
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<ReadingDocumentDto>(new InvalidDataException("broken book")));
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Reading.ExtractionFailed", result.FirstError.Code);
}
[Fact]
public async Task GetManifestAsync_WhenReaderOpenIsCancelled_ShouldPropagateTheCancellation()
{
// Arrange
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<ReadingDocumentDto>(new OperationCanceledException()));
// Act
Task<Result<ReadingManifestResponse>> operationTask = _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
[Fact]
public async Task GetManifestAsync_WhenBookFileIsDeletedAfterExtraction_ShouldReExtractAndFail()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<ReadingDocumentDto>(new FileNotFoundException("book missing")));
File.Delete(_bookPath);
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.BookFileNotFound, result.FirstError);
await _mockReader.Received(2).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenConfigurationsReadFails_ShouldReturnError()
{
// Arrange
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Reading.Error", "Failed to read the configuration"));
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Reading.Error", result.FirstError.Code);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenReaderMatchesExtensionCaseInsensitively_ShouldResolveIt()
{
// Arrange
string uppercaseExtensionPath = Path.Combine(Path.GetTempPath(), $"lumina-test-book-{Guid.NewGuid():N}.EPUB");
File.WriteAllText(uppercaseExtensionPath, "test epub content");
try
{
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, uppercaseExtensionPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
}
finally
{
File.Delete(uppercaseExtensionPath);
}
}
[Fact]
public async Task GetManifestAsync_WhenReaderSupportsTheLibraryTypeButNotTheExtension_ShouldReturnNoReaderAvailableError()
{
// Arrange
string unsupportedExtensionPath = Path.Combine(Path.GetTempPath(), $"lumina-test-book-{Guid.NewGuid():N}.txt");
File.WriteAllText(unsupportedExtensionPath, "test content");
try
{
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, unsupportedExtensionPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
finally
{
File.Delete(unsupportedExtensionPath);
}
}
[Fact]
public async Task GetSectionAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError()
{
// Arrange
_mockPluginManager.GetPlugins().Returns([]);
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenAReaderDeclaresABlankExtension_ShouldSkipItAndStillResolveTheFormat()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
IBookReader blankExtensionReader = Substitute.For<IBookReader>();
blankExtensionReader.SupportedExtensions.Returns([" "]);
blankExtensionReader.SupportedLibraryTypes.Returns([LibraryType.EBook]);
ServiceCollection services = new();
services.AddKeyedSingleton(_pluginId, blankExtensionReader);
services.AddKeyedSingleton(_pluginId, _mockReader);
services.AddSingleton(_mockUnitOfWork);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
IServiceScopeFactory serviceScopeFactory = serviceProvider.GetRequiredService<IServiceScopeFactory>();
BookReadingService sut = new(serviceProvider, _mockPluginManager, _enablementCache, serviceScopeFactory, Substitute.For<ILogger<BookReadingService>>());
// Act
Result<ReadingManifestResponse> result = await sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(document.Title, result.Value.Title);
}
}
[Fact]
public async Task GetResourceAsync_WhenTwoRequestsMissTheSameResourceConcurrently_ShouldProduceItOnceAndBothServeIt()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
byte[] producedResource = [7, 8, 9];
TaskCompletionSource<bool> productionStarted = new();
TaskCompletionSource<bool> allowProductionToFinish = new();
_mockReader.GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), "cover", Arg.Any<CancellationToken>())
.Returns(async callInfo =>
{
productionStarted.SetResult(true);
await allowProductionToFinish.Task;
return producedResource;
});
// Act
Task<Result<ReadingResourceDataDto>> firstTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
await productionStarted.Task;
Task<Result<ReadingResourceDataDto>> secondTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
allowProductionToFinish.SetResult(true);
Result<ReadingResourceDataDto> firstResult = await firstTask;
Result<ReadingResourceDataDto> secondResult = await secondTask;
// Assert
Assert.False(firstResult.IsFailure);
Assert.False(secondResult.IsFailure);
Assert.Equal(new byte[] { 7, 8, 9 }, firstResult.Value.Data);
Assert.Equal(new byte[] { 7, 8, 9 }, secondResult.Value.Data);
await _mockReader.Received(1).GetResourceAsync(_bookPath, Arg.Any<string>(), "cover", Arg.Any<CancellationToken>());
}
/// <summary>
/// Creates a reading document whose spine and resources are extractable into the working directory.
/// </summary>
/// <returns>The created reading document.</returns>
private ReadingDocumentDto CreateExtractableDocument()
{
return _readingDocumentDtoFixture.Create(
title: "Test Book",
author: "Test Author",
tableOfContents: [],
spine:
[
_readingSpineItemDtoFixture.Create(locationRef: "section-1", title: "Chapter 1", relativeSectionFilePath: "sections/0.html")
],
resources: new Dictionary<string, ReadingResourceInfoDto>
{
["cover"] = _readingResourceInfoDtoFixture.Create(relativeFilePath: "resources/cover.png", mimeType: "image/png")
},
hasTextContent: true
);
}
/// <summary>
/// Stubs the reader's OpenAsync to create the extractable files of the document into the working directory.
/// </summary>
/// <param name="document">The document returned by the extraction.</param>
private void StubOpenAsyncToExtract(ReadingDocumentDto document)
{
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
string workingDirectory = callInfo.ArgAt<string>(1);
Directory.CreateDirectory(Path.Combine(workingDirectory, "sections"));
File.WriteAllText(Path.Combine(workingDirectory, "sections", "0.html"), "<section><h1>Chapter 1</h1><p>Some text.</p></section>");
return Task.FromResult(document);
});
}
/// <summary>
/// Stubs the reader's OpenAsync to create a section whose content carries a style attribute, so that the sanitization
/// preference of the service is observable.
/// </summary>
/// <param name="document">The document returned by the extraction.</param>
private void StubOpenAsyncToExtractStyledContent(ReadingDocumentDto document)
{
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
string workingDirectory = callInfo.ArgAt<string>(1);
Directory.CreateDirectory(Path.Combine(workingDirectory, "sections"));
File.WriteAllText(Path.Combine(workingDirectory, "sections", "0.html"), "<section><h1>Chapter 1</h1><p style=\"color:red\">Some text.</p></section>");
return Task.FromResult(document);
});
}
/// <inheritdoc/>
public void Dispose()
{
if (Directory.Exists(ReadingCachePaths.GetRootDirectory()))
Directory.Delete(ReadingCachePaths.GetRootDirectory(), recursive: true);
if (File.Exists(_bookPath))
File.Delete(_bookPath);
(_serviceProvider as IDisposable)?.Dispose();
}
/// <summary>
/// In-memory test double for the <see cref="IBookReaderEnablementCache"/> used by the service under test.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed class TestBookReaderEnablementCache : IBookReaderEnablementCache
{
private readonly Dictionary<(Guid LibraryId, Guid PluginId), bool> _enablements = [];
/// <inheritdoc/>
public bool? Get(Guid libraryId, Guid pluginId)
{
return _enablements.TryGetValue((libraryId, pluginId), out bool isEnabled) ? isEnabled : null;
}
/// <inheritdoc/>
public void Set(Guid libraryId, Guid pluginId, bool isEnabled)
{
_enablements[(libraryId, pluginId)] = isEnabled;
}
/// <inheritdoc/>
public void Invalidate(Guid libraryId, Guid pluginId)
{
_enablements.Remove((libraryId, pluginId));
}
/// <inheritdoc/>
public void InvalidateLibrary(Guid libraryId)
{
foreach (Guid cachedPluginId in _enablements.Keys.Where(cachedPair => cachedPair.LibraryId == libraryId).Select(cachedPair => cachedPair.PluginId).ToList())
_enablements.Remove((libraryId, cachedPluginId));
}
/// <inheritdoc/>
public void InvalidatePlugin(Guid pluginId)
{
foreach (Guid cachedLibraryId in _enablements.Keys.Where(cachedPair => cachedPair.PluginId == pluginId).Select(cachedPair => cachedPair.LibraryId).ToList())
_enablements.Remove((cachedLibraryId, pluginId));
}
}
}
@@ -8,11 +8,8 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -23,9 +20,8 @@ namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
/// Contains unit tests for the <see cref="PluginInstaller"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PluginInstallerTests : IDisposable
public class PluginInstallerTests
{
private readonly string _pluginsDirectory;
private readonly PluginInstaller _sut;
private readonly PluginsSettingsDtoFixture _pluginsSettingsDtoFixture = new();
@@ -34,79 +30,12 @@ public class PluginInstallerTests : IDisposable
/// </summary>
public PluginInstallerTests()
{
_pluginsDirectory = Path.Combine(AppContext.BaseDirectory, $".test-plugins-{Guid.NewGuid():N}");
ILogger<PluginInstaller> mockLogger = Substitute.For<ILogger<PluginInstaller>>();
IOptions<PluginsSettingsDto> mockOptions = Substitute.For<IOptions<PluginsSettingsDto>>();
mockOptions.Value.Returns(_pluginsSettingsDtoFixture.Create(directory: Path.GetFileName(_pluginsDirectory)));
mockOptions.Value.Returns(_pluginsSettingsDtoFixture.Create(directory: $".test-plugins-{Guid.NewGuid():N}"));
_sut = new PluginInstaller(mockOptions, mockLogger);
}
[Fact]
public async Task InstallAsync_WhenUploadingSingleAssembly_ShouldCopyAssemblyToPluginsDirectory()
{
// Arrange
string assemblyName = "Lumina.TestPlugin.dll";
await using FileStream stream = File.OpenRead(Path.Combine(AppContext.BaseDirectory, assemblyName));
// Act
Result<Success> result = await _sut.InstallAsync(stream, assemblyName, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.True(File.Exists(Path.Combine(_pluginsDirectory, assemblyName)));
}
[Fact]
public async Task InstallAsync_WhenUploadingZipWithAssemblies_ShouldExtractAssembliesFlattenedToPluginsDirectory()
{
// Arrange
await using MemoryStream zipStream = new();
CreateZipArchive(zipStream, [("nested/plugin/Lumina.TestPlugin.dll", ReadTestAssembly()), ("readme.txt", Encoding.UTF8.GetBytes("not an assembly"))]);
zipStream.Position = 0;
// Act
Result<Success> result = await _sut.InstallAsync(zipStream, "plugin.zip", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.True(File.Exists(Path.Combine(_pluginsDirectory, "Lumina.TestPlugin.dll")));
Assert.False(File.Exists(Path.Combine(_pluginsDirectory, "readme.txt")));
}
[Fact]
public async Task InstallAsync_WhenUploadingZipWithBackslashTraversalEntry_ShouldFlattenItInsidePluginsDirectory()
{
// Arrange
await using MemoryStream zipStream = new();
// a backslash is not a directory separator on non-Windows platforms, so it must be neutralized explicitly
CreateZipArchive(zipStream, [(@"..\evil.dll", ReadTestAssembly())]);
zipStream.Position = 0;
// Act
Result<Success> result = await _sut.InstallAsync(zipStream, "plugin.zip", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.True(File.Exists(Path.Combine(_pluginsDirectory, "evil.dll")));
Assert.False(File.Exists(Path.Combine(AppContext.BaseDirectory, "evil.dll")));
}
[Fact]
public async Task InstallAsync_WhenUploadingSingleAssemblyWithTraversalFileName_ShouldFlattenItInsidePluginsDirectory()
{
// Arrange
const string TRAVERSAL_FILE_NAME = "traversal-test-plugin.dll";
await using FileStream stream = File.OpenRead(Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll"));
// Act
Result<Success> result = await _sut.InstallAsync(stream, $@"..\{TRAVERSAL_FILE_NAME}", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.True(File.Exists(Path.Combine(_pluginsDirectory, TRAVERSAL_FILE_NAME)));
Assert.False(File.Exists(Path.Combine(AppContext.BaseDirectory, TRAVERSAL_FILE_NAME)));
}
[Fact]
public async Task InstallAsync_WhenUploadingUnsupportedFileType_ShouldReturnError()
{
@@ -119,23 +48,6 @@ public class PluginInstallerTests : IDisposable
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.UnsupportedPluginFileType, result.FirstError);
Assert.False(Directory.Exists(_pluginsDirectory));
}
[Fact]
public async Task InstallAsync_WhenUploadingZipWithoutAssemblies_ShouldReturnError()
{
// Arrange
await using MemoryStream zipStream = new();
CreateZipArchive(zipStream, [("readme.txt", Encoding.UTF8.GetBytes("not an assembly"))]);
zipStream.Position = 0;
// Act
Result<Success> result = await _sut.InstallAsync(zipStream, "plugin.zip", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginArchiveContainsNoAssemblies, result.FirstError);
}
[Fact]
@@ -151,38 +63,4 @@ public class PluginInstallerTests : IDisposable
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginArchiveNotReadable, result.FirstError);
}
/// <summary>
/// Deletes the temporary plugins directory created by the tests.
/// </summary>
public void Dispose()
{
if (Directory.Exists(_pluginsDirectory))
Directory.Delete(_pluginsDirectory, recursive: true);
}
/// <summary>
/// Creates an in-memory ZIP archive containing the provided entries.
/// </summary>
/// <param name="zipStream">The stream to write the archive into.</param>
/// <param name="entries">The entries to add, as pairs of entry name and content.</param>
private static void CreateZipArchive(MemoryStream zipStream, IEnumerable<(string Name, byte[] Content)> entries)
{
using ZipArchive zipArchive = new(zipStream, ZipArchiveMode.Create, leaveOpen: true);
foreach ((string name, byte[] content) in entries)
{
ZipArchiveEntry entry = zipArchive.CreateEntry(name);
using Stream entryStream = entry.Open();
entryStream.Write(content);
}
}
/// <summary>
/// Reads the bytes of the <c>Lumina.TestPlugin.dll</c> assembly from the test output directory.
/// </summary>
/// <returns>The assembly bytes.</returns>
private static byte[] ReadTestAssembly()
{
return File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll"));
}
}
@@ -1,106 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.Plugins;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="PluginLoadContext"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PluginLoadContextTests
{
[Fact]
public void LoadFromAssemblyName_WhenAssemblyIsResolvableFromDefaultContext_ShouldReturnTheSharedAssembly()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context");
// Act
Assembly result = sut.LoadFromAssemblyName(typeof(object).Assembly.GetName());
// Assert
Assert.NotNull(result);
Assert.Equal(typeof(object).Assembly.GetName().Name, result.GetName().Name);
}
[Fact]
public void Load_WhenAssemblyExistsOnlyInPluginDirectory_ShouldLoadItFromThePluginDirectory()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
string destinationPath = temporaryPluginDirectory.CopyDll(Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll"), "PluginLocalDependency.dll");
PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context");
MethodInfo loadMethod = typeof(PluginLoadContext).GetMethod("Load", BindingFlags.Instance | BindingFlags.NonPublic)!;
// Act
Assembly? result = (Assembly?)loadMethod.Invoke(sut, [new AssemblyName("PluginLocalDependency")]);
// Assert
Assert.NotNull(result);
Assert.Equal("Lumina.TestPlugin", result!.GetName().Name);
Assert.Equal(destinationPath, result.Location);
}
[Fact]
public void LoadFromAssemblyName_WhenAssemblyIsNotFoundAnywhere_ShouldThrowFileNotFoundException()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context");
// Act
Action act = () => sut.LoadFromAssemblyName(new AssemblyName($"Definitely.Not.Resolvable.{Guid.NewGuid()}"));
// Assert
Assert.Throws<FileNotFoundException>(act);
}
/// <summary>
/// Test helper managing a temporary plugins directory, deleted when the test finishes.
/// </summary>
private sealed class TemporaryPluginDirectory : IDisposable
{
private bool _disposed;
public TemporaryPluginDirectory()
{
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-plugin-load-context-{Guid.NewGuid()}");
Directory.CreateDirectory(Path);
}
public string Path { get; }
public string CopyDll(string sourceDllPath, string destinationFileName)
{
string destinationPath = System.IO.Path.Combine(Path, destinationFileName);
File.Copy(sourceDllPath, destinationPath);
return destinationPath;
}
public void Dispose()
{
if (!_disposed)
{
try
{
Directory.Delete(Path, recursive: true);
}
catch (IOException)
{
// best effort cleanup of the temporary plugins directory
}
catch (UnauthorizedAccessException)
{
// the plugin assemblies are still locked by their load contexts, best effort cleanup only
}
_disposed = true;
}
}
}
}
@@ -1,279 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Models.DTO.Plugins;
using Lumina.Infrastructure.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="PluginLoader"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PluginLoaderTests
{
[Fact]
public void LoadPlugins_WhenDirectoryDoesNotExist_ShouldReturnNoPluginsAndNoErrors()
{
// Arrange
string nonExistentDirectory = Path.Combine(Path.GetTempPath(), $"lumina-plugins-{Guid.NewGuid()}");
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(nonExistentDirectory, services);
// Assert
Assert.Empty(result.Plugins);
Assert.Empty(result.Errors);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsInvalidAssembly_ShouldRecordError()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
temporaryPluginDirectory.CreateFile("invalid.dll", "this is not a valid assembly");
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
Assert.Empty(result.Plugins);
PluginLoadErrorDto error = Assert.Single(result.Errors);
Assert.Equal("invalid", error.AssemblyName);
Assert.Contains("invalid.dll", error.ErrorMessage);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsNativeLibrary_ShouldSkipItSilently()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
// A native library (like pdfium.dll) is a valid PE image starting with the DOS signature, but it is not a managed assembly.
temporaryPluginDirectory.CreateFile("native.dll", "MZ\u0001\u0000\u0000\u0000garbage native library content");
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
Assert.Empty(result.Plugins);
Assert.Empty(result.Errors);
Assert.Empty(result.LoadContexts);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsAssemblyWithoutPluginDescriptors_ShouldReturnNoPluginsAndNoErrors()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
temporaryPluginDirectory.CopyDll(typeof(IPlugin).Assembly.Location);
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
Assert.Empty(result.Plugins);
Assert.Empty(result.Errors);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsValidPluginAssembly_ShouldLoadPluginAndRegisterItsServices()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath());
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
IPlugin loadedPlugin = Assert.Single(result.Plugins);
Assert.Empty(result.Errors);
Assert.Equal(Guid.Parse("7B5A3E5D-9B7F-4A1E-8D9C-2F3A4B5C6D7E"), loadedPlugin.Id);
Assert.Equal("Test Plugin", loadedPlugin.Name);
Assert.Contains(services, descriptor => descriptor.ImplementationInstance as string == "plugin-services-registered");
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsValidPluginAssembly_ShouldRetainTheLoadContextOfThePlugin()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath());
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
Assert.Single(result.Plugins);
// A collectible load context is only kept alive by a direct reference to the context object itself, so the context of every loaded plugin is retained
// for the lifetime of the host, keeping the plugin assemblies from being unloaded by the garbage collector.
Assert.Single(result.LoadContexts);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsManagedDependencyAssemblyAlongsideAPlugin_ShouldSkipTheDependencyAndLoadOnlyThePlugin()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath());
// A plugin ships its managed dependencies into the plugins directory (like PdfPig.dll and SkiaSharp.dll next to the PDF plugin). A managed dependency is a valid
// assembly that does not reference the plugin contracts, so it is not a plugin and must be skipped without reflecting over its types, which would otherwise surface
// spurious load errors for a file that is not a plugin.
temporaryPluginDirectory.CopyDll(GetDependencyAssemblyPath());
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
IPlugin loadedPlugin = Assert.Single(result.Plugins);
Assert.Equal(Guid.Parse("7B5A3E5D-9B7F-4A1E-8D9C-2F3A4B5C6D7E"), loadedPlugin.Id);
Assert.Equal("Test Plugin", loadedPlugin.Name);
Assert.Empty(result.Errors);
Assert.Single(result.LoadContexts);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsFileShorterThanDosSignature_ShouldRecordInvalidAssemblyError()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
// A single-character file is not long enough to carry the two-byte DOS signature "MZ", so it is not a PE image.
temporaryPluginDirectory.CreateFile("tiny.dll", "M");
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
Assert.Empty(result.Plugins);
PluginLoadErrorDto error = Assert.Single(result.Errors);
Assert.Equal("tiny", error.AssemblyName);
Assert.Contains("tiny.dll", error.ErrorMessage);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsFileWithWrongDosSignature_ShouldRecordInvalidAssemblyError()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
// The file starts with the wrong DOS signature, so it is not a PE image at all.
temporaryPluginDirectory.CreateFile("notpe.dll", "XY\u0000\u0000\u0000some content that is not a PE image");
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
Assert.Empty(result.Plugins);
PluginLoadErrorDto error = Assert.Single(result.Errors);
Assert.Equal("notpe", error.AssemblyName);
Assert.Contains("notpe.dll", error.ErrorMessage);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsLockedNativeLibrary_ShouldNotThrowAndRecordError()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
string nativePath = temporaryPluginDirectory.CreateFileReturningPath("locked.dll", "MZ\u0000\u0000\u0000locked native library content");
using FileStream lockStream = new(nativePath, FileMode.Open, FileAccess.Read, FileShare.None);
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
Assert.Empty(result.Plugins);
// The file cannot be read to verify its PE signature, so it is reported as not loadable rather than crashing the loader.
PluginLoadErrorDto error = Assert.Single(result.Errors);
Assert.Equal("locked", error.AssemblyName);
}
/// <summary>
/// Gets the path of the <c>Lumina.TestPlugin</c> assembly from the test output directory.
/// The assembly is referenced by the test project but no type from it is used, so it is not loaded
/// into the default load context, which is what makes the plugin loading pipeline testable.
/// </summary>
/// <returns>The path of the test plugin assembly.</returns>
private static string GetTestPluginAssemblyPath()
{
return Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll");
}
/// <summary>
/// Gets the path of a managed dependency assembly from the test output directory, standing in for the managed dependencies
/// a plugin ships next to itself (like PdfPig.dll and SkiaSharp.dll next to the PDF plugin). The <c>Microsoft.AspNetCore.SignalR.Core</c>
/// assembly is used because it does not reference the plugin contracts assembly, and reflecting over its types inside a plugin load
/// context throws, which reproduces the spurious load errors the loader used to record for dependency assemblies.
/// </summary>
/// <returns>The path of the managed dependency assembly.</returns>
private static string GetDependencyAssemblyPath()
{
return Path.Combine(AppContext.BaseDirectory, "Microsoft.AspNetCore.SignalR.Core.dll");
}
/// <summary>
/// Test helper managing a temporary plugins directory, deleted when the test finishes.
/// </summary>
private sealed class TemporaryPluginDirectory : IDisposable
{
private bool _disposed;
public TemporaryPluginDirectory()
{
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-plugin-loader-{Guid.NewGuid()}");
Directory.CreateDirectory(Path);
}
public string Path { get; }
public void CreateFile(string fileName, string content)
{
File.WriteAllText(System.IO.Path.Combine(Path, fileName), content);
}
public string CreateFileReturningPath(string fileName, string content)
{
string filePath = System.IO.Path.Combine(Path, fileName);
File.WriteAllText(filePath, content);
return filePath;
}
public void CopyDll(string sourceDllPath)
{
File.Copy(sourceDllPath, System.IO.Path.Combine(Path, System.IO.Path.GetFileName(sourceDllPath)));
}
public void Dispose()
{
if (!_disposed)
{
try
{
Directory.Delete(Path, recursive: true);
}
catch (IOException)
{
// best effort cleanup of the temporary plugins directory
}
catch (UnauthorizedAccessException)
{
// the plugin assemblies are still locked by their load contexts, best effort cleanup only
}
_disposed = true;
}
}
}
}
@@ -1,231 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
using Lumina.Infrastructure.Core.Security;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Hashing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Security;
/// <summary>
/// Contains unit tests for the <see cref="FileHashService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileHashServiceTests
{
private readonly FileHashService _sut = new();
private readonly HashedFileSystemFileDtoFixture _hashedFileSystemFileDtoFixture = new();
[Fact]
public async Task HashFilesAsync_WhenCalledWithFiles_ShouldInvokeCallbackAndComputeHashes()
{
// Arrange
using TemporaryTestDirectory temporaryTestDirectory = new();
string filePath1 = temporaryTestDirectory.CreateFile("book1.pdf", "content of the first book");
string filePath2 = temporaryTestDirectory.CreateFile("book2.pdf", "content of the second book");
List<HashedFileSystemFileDto> inputFiles =
[
_hashedFileSystemFileDtoFixture.Create(path: filePath1, size: new FileInfo(filePath1).Length, currentHash: 0, oldHash: 0, ticks: 0),
_hashedFileSystemFileDtoFixture.Create(path: filePath2, size: new FileInfo(filePath2).Length, currentHash: 0, oldHash: 0, ticks: 0)
];
int callbackInvocationCount = 0;
// Act
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(
inputFiles,
() =>
{
callbackInvocationCount++;
return Task.CompletedTask;
},
CancellationToken.None);
// Assert
Assert.Equal(2, result.Count);
Assert.Equal(2, callbackInvocationCount);
Assert.All(result, file => Assert.NotEqual(0UL, file.CurrentHash));
// the hashing is parallelized, so the results are not guaranteed to be in the input order
Assert.Equal(
inputFiles.Select(file => file.Path).OrderBy(path => path, StringComparer.Ordinal),
result.Select(file => file.Path).OrderBy(path => path, StringComparer.Ordinal));
}
[Fact]
public async Task HashFilesAsync_WhenFileIsEmpty_ShouldUseEmptyFileHash()
{
// Arrange
using TemporaryTestDirectory temporaryTestDirectory = new();
string filePath = temporaryTestDirectory.CreateFile("empty.pdf", string.Empty);
List<HashedFileSystemFileDto> inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
// Act
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None);
// Assert
HashedFileSystemFileDto hashedFile = Assert.Single(result);
Assert.Equal(filePath, hashedFile.Path);
Assert.Equal(BitConverter.ToUInt64(new XxHash64().GetCurrentHash()), hashedFile.CurrentHash);
}
[Fact]
public async Task HashFilesAsync_WhenFileContentChanges_ShouldProduceDifferentHashes()
{
// Arrange
using TemporaryTestDirectory temporaryTestDirectory = new();
string filePath = temporaryTestDirectory.CreateFile("book.pdf", "original content");
List<HashedFileSystemFileDto> firstInputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
// Act
List<HashedFileSystemFileDto> firstResult = await _sut.HashFilesAsync(firstInputFiles, () => Task.CompletedTask, CancellationToken.None);
await File.WriteAllTextAsync(filePath, "changed content");
List<HashedFileSystemFileDto> secondInputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
List<HashedFileSystemFileDto> secondResult = await _sut.HashFilesAsync(secondInputFiles, () => Task.CompletedTask, CancellationToken.None);
// Assert
Assert.NotEqual(firstResult[0].CurrentHash, secondResult[0].CurrentHash);
}
[Fact]
public async Task HashFilesAsync_WhenFileDoesNotExist_ShouldSkipFileAndNotThrow()
{
// Arrange
string nonExistentFilePath = Path.Combine(Path.GetTempPath(), "does-not-exist.pdf");
List<HashedFileSystemFileDto> inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: nonExistentFilePath, size: 100, currentHash: 0, oldHash: 0, ticks: 0)];
// Act
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None);
// Assert
Assert.Empty(result);
}
[Fact]
public async Task HashFilesAsync_WhenOneFileIsMissing_ShouldHashTheExistingFilesOnly()
{
// Arrange
using TemporaryTestDirectory temporaryTestDirectory = new();
string existingFilePath = temporaryTestDirectory.CreateFile("book.pdf", "content");
List<HashedFileSystemFileDto> inputFiles =
[
_hashedFileSystemFileDtoFixture.Create(path: existingFilePath, size: new FileInfo(existingFilePath).Length, currentHash: 0, oldHash: 0, ticks: 0),
_hashedFileSystemFileDtoFixture.Create(path: Path.Combine(temporaryTestDirectory.Path, "missing.pdf"), size: 100, currentHash: 0, oldHash: 0, ticks: 0)
];
// Act
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None);
// Assert
HashedFileSystemFileDto hashedFile = Assert.Single(result);
Assert.Equal(existingFilePath, hashedFile.Path);
Assert.NotEqual(0UL, hashedFile.CurrentHash);
}
[Fact]
public async Task HashFilesAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
using TemporaryTestDirectory temporaryTestDirectory = new();
string filePath = temporaryTestDirectory.CreateFile("book.pdf", "content");
List<HashedFileSystemFileDto> inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task<List<HashedFileSystemFileDto>> operation = _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, cancellationTokenSource.Token);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
}
[Fact]
public void ComputeFileHash_WhenFileIsEmpty_ShouldReturnEmptyFileHash()
{
// Arrange
using TemporaryTestDirectory temporaryTestDirectory = new();
string filePath = temporaryTestDirectory.CreateFile("empty.pdf", string.Empty);
// Act
ulong hash = _sut.ComputeFileHash(filePath);
// Assert
Assert.Equal(BitConverter.ToUInt64(new XxHash64().GetCurrentHash()), hash);
}
[Fact]
public void ComputeFileHash_WhenFileHasContent_ShouldReturnNonZeroHash()
{
// Arrange
using TemporaryTestDirectory temporaryTestDirectory = new();
string filePath = temporaryTestDirectory.CreateFile("book.pdf", "content of the book");
// Act
ulong hash = _sut.ComputeFileHash(filePath);
// Assert
Assert.NotEqual(0UL, hash);
}
[Fact]
public async Task HashFilesAsync_WhenFileIsLargerThanTheSamplingThreshold_ShouldSampleTheWholeFile()
{
// Arrange
using TemporaryTestDirectory temporaryTestDirectory = new();
string filePath = Path.Combine(temporaryTestDirectory.Path, "large.pdf");
File.WriteAllBytes(filePath, new byte[500_000]);
List<HashedFileSystemFileDto> inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
// Act
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None);
// Assert
HashedFileSystemFileDto hashedFile = Assert.Single(result);
Assert.Equal(filePath, hashedFile.Path);
Assert.NotEqual(0UL, hashedFile.CurrentHash);
}
/// <summary>
/// Test helper managing a temporary directory, deleted when the test finishes.
/// </summary>
private sealed class TemporaryTestDirectory : IDisposable
{
private bool _disposed;
public TemporaryTestDirectory()
{
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-file-hash-tests-{Guid.NewGuid()}");
Directory.CreateDirectory(Path);
}
public string Path { get; }
public string CreateFile(string fileName, string content)
{
string filePath = System.IO.Path.Combine(Path, fileName);
File.WriteAllText(filePath, content);
return filePath;
}
public void Dispose()
{
if (!_disposed)
{
try
{
Directory.Delete(Path, recursive: true);
}
catch (IOException)
{
// best effort cleanup of the temporary test directory
}
_disposed = true;
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -6,10 +6,8 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Calibre.Core;
using Lumina.Plugins.Calibre.Fixtures.Core.Metadata;
using Lumina.Plugins.Contracts.Core.Metadata;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -58,149 +56,6 @@ public class CalibreArtworkProviderTests
Assert.False(result);
}
[Fact]
public async Task GetArtworkAsync_WhenCoverHrefIsABareFileName_ShouldReturnTheLocalCoverPath()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
WriteOpf(bookDirectory, coverHref: "cover.jpg");
File.WriteAllText(Path.Combine(bookDirectory, "cover.jpg"), "image-bytes");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath);
Assert.Null(result.RemoteUrl);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetArtworkAsync_WhenCoverHrefIsAnAbsolutePath_ShouldReturnNull()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
WriteOpf(bookDirectory, coverHref: @"C:\Windows\System32\drivers\etc\hosts");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Theory]
[InlineData("../cover.jpg")] // parent directory escape
[InlineData("sub/cover.jpg")] // path with a separator
[InlineData("sub\\cover.jpg")] // path with a backslash separator
public async Task GetArtworkAsync_WhenCoverHrefContainsPathTraversalOrSeparators_ShouldReturnNull(string coverHref)
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
WriteOpf(bookDirectory, coverHref);
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetArtworkAsync_WhenCoverFileIsMissing_ShouldReturnNull()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
WriteOpf(bookDirectory, coverHref: "cover.jpg");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetArtworkAsync_WhenOpfFileDoesNotExist_ShouldReturnNull()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetArtworkAsync_WhenOpfHasNoCoverReference_ShouldReturnNull()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), """<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>Test</dc:title></metadata></package>""");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetArtworkAsync_WhenLookupIsNotABookLookup_ShouldReturnNull()
{
@@ -227,26 +82,4 @@ public class CalibreArtworkProviderTests
// Assert
Assert.Null(result);
}
/// <summary>
/// Writes an OPF file that references the given cover into the book directory.
/// </summary>
/// <param name="bookDirectory">The file system path of the directory the OPF file is written into.</param>
/// <param name="coverHref">The href of the cover the OPF file references.</param>
private static void WriteOpf(string bookDirectory, string coverHref)
{
string opf = $$"""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>Test</dc:title></metadata><guide><reference type="cover" href="{{coverHref}}"/></guide></package>""";
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opf);
}
/// <summary>
/// Creates a unique temporary directory for the book.
/// </summary>
/// <returns>The file system path of the created temporary directory.</returns>
private static string CreateTempDirectory()
{
string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-artwork-{Guid.NewGuid():N}");
Directory.CreateDirectory(directoryPath);
return directoryPath;
}
}
@@ -3,10 +3,8 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Calibre.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -22,8 +20,6 @@ public class CalibreBookMetadataProviderTests
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
private readonly CalibreBookMetadataProvider _sut = new();
private const string OPF_DOCUMENT = """<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf" version="2.0"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf"><dc:title>Test Book Title</dc:title><dc:creator opf:role="aut">Test Author</dc:creator></metadata></package>""";
[Fact]
public void Name_WhenCalled_ShouldReturnTheProviderDisplayName()
{
@@ -56,52 +52,6 @@ public class CalibreBookMetadataProviderTests
Assert.False(result);
}
[Fact]
public async Task GetMetadataAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnTheMappedMetadata()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT);
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Equal("Test Book Title", result!.Title);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetMetadataAsync_WhenOpfFileDoesNotExist_ShouldReturnNull()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetMetadataAsync_WhenLookupPathIsEmpty_ShouldReturnNull()
{
@@ -114,61 +64,4 @@ public class CalibreBookMetadataProviderTests
// Assert
Assert.Null(result);
}
[Fact]
public async Task GetSearchResultsAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnASingleMetadataCandidate()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT);
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
IReadOnlyList<BookMetadataDto> result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None);
// Assert
BookMetadataDto metadata = Assert.IsType<BookMetadataDto>(Assert.Single(result));
Assert.Equal("Test Book Title", metadata.Title);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetSearchResultsAsync_WhenOpfFileDoesNotExist_ShouldReturnAnEmptyList()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
// Act
IReadOnlyList<BookMetadataDto> result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None);
// Assert
Assert.Empty(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
/// <summary>
/// Creates a unique temporary directory for the book.
/// </summary>
/// <returns>The file system path of the created temporary directory.</returns>
private static string CreateTempDirectory()
{
string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-metadata-{Guid.NewGuid():N}");
Directory.CreateDirectory(directoryPath);
return directoryPath;
}
}
@@ -1,212 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
using Lumina.Plugins.Calibre.Core.Opf;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
#endregion
namespace Lumina.Plugins.Calibre.UnitTests.Core.Opf;
/// <summary>
/// Contains unit tests for the <see cref="OpfReader"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class OpfReaderTests
{
[Fact]
public void Read_WhenOpfFileContainsAllSupportedFields_ShouldParseThemAll()
{
// Arrange
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="uuid_id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf"><dc:title>Test Book Title</dc:title><dc:creator opf:role="aut">Test Author</dc:creator><dc:creator opf:role="oth">Second Creator</dc:creator><dc:contributor opf:role="bkp">calibre (3.48.0) [https://calibre-ebook.com]</dc:contributor><dc:contributor opf:role="trl">Test Translator</dc:contributor><dc:description>&lt;p&gt;A test description with &lt;b&gt;markup&lt;/b&gt;.&lt;/p&gt;</dc:description><dc:publisher>Test Publisher</dc:publisher><dc:date>2015-06-15</dc:date><dc:language>en</dc:language><dc:identifier opf:scheme="ISBN">978-0-306-40615-7</dc:identifier><dc:identifier opf:scheme="goodreads">123456</dc:identifier><dc:identifier opf:scheme="ASIN">B00TEST1</dc:identifier><dc:identifier opf:scheme="LCCN">test-lccn</dc:identifier><dc:identifier opf:scheme="oclc">ocm12345678</dc:identifier><dc:identifier opf:scheme="openlibrary">OL100M</dc:identifier><dc:identifier opf:scheme="google">google-id</dc:identifier><dc:subject>Science fiction</dc:subject><dc:subject>Space opera</dc:subject><meta name="calibre:series" content="The Series"/><meta name="calibre:series_index" content="2.5"/><meta name="calibre:rating" content="8"/></metadata><guide><reference type="cover" href="cover.jpg"/><reference type="toc" href="toc.xhtml"/></guide></package>""");
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Equal("Test Book Title", result.Title);
Assert.Equal("<p>A test description with <b>markup</b>.</p>", result.Description);
Assert.Equal("Test Publisher", result.Publisher);
Assert.Equal(2015, result.PublishDate!.Value.Year);
Assert.Equal(6, result.PublishDate.Value.Month);
Assert.Equal(15, result.PublishDate.Value.Day);
Assert.Equal("en", result.LanguageCode);
Assert.Equal("The Series", result.Series);
Assert.Equal(2.5, result.SeriesIndex);
Assert.Equal(8, result.Rating);
Assert.Equal("cover.jpg", result.CoverHref);
Assert.Equal(2, result.Creators.Count);
Assert.Equal("Test Author", result.Creators[0].Name);
Assert.Equal("aut", result.Creators[0].Role);
Assert.Equal(2, result.Contributors.Count);
Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", result.Contributors[0].Name);
Assert.Equal("bkp", result.Contributors[0].Role);
Assert.Equal(7, result.Identifiers.Count);
Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "ISBN" && identifier.Value == "978-0-306-40615-7");
Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "goodreads" && identifier.Value == "123456");
Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "ASIN" && identifier.Value == "B00TEST1");
Assert.Equal(2, result.Subjects.Count);
Assert.Equal("Science fiction", result.Subjects[0]);
Assert.Equal("Space opera", result.Subjects[1]);
}
finally
{
File.Delete(opfFilePath);
}
}
[Fact]
public void Read_WhenOpfFileDoesNotExist_ShouldReturnEmptyDocument()
{
// Act
OpfDocumentDto result = OpfReader.Read(Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.opf"));
// Assert
Assert.Null(result.Title);
Assert.Empty(result.Identifiers);
Assert.Empty(result.Creators);
Assert.Empty(result.Subjects);
}
[Fact]
public void Read_WhenMetadataContainsWhitespaceOnlyValues_ShouldSkipThem()
{
// Arrange
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title> </dc:title><dc:creator opf:role="aut"> </dc:creator><dc:subject></dc:subject></metadata></package>""");
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Null(result.Title);
Assert.Empty(result.Creators);
Assert.Empty(result.Subjects);
}
finally
{
File.Delete(opfFilePath);
}
}
[Fact]
public void Read_WhenMetadataElementIsMissing_ShouldReturnEmptyDocument()
{
// Arrange
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"></package>""");
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Null(result.Title);
Assert.Empty(result.Identifiers);
}
finally
{
File.Delete(opfFilePath);
}
}
[Fact]
public void Read_WhenOpfFileDeclaresADoctypeWithEntities_ShouldNotExpandThem()
{
// Arrange
// the DTD is prohibited, so the document must not be parsed and the entity must not be expanded into the title
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><!DOCTYPE package [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>&xxe;</dc:title></metadata></package>""");
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Null(result.Title);
}
finally
{
File.Delete(opfFilePath);
}
}
[Fact]
public void Read_WhenOpfFileContainsBillionLaughsStyleEntityExpansion_ShouldNotExpandThem()
{
// Arrange
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"><!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">]><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>&lol3;</dc:title></metadata></package>""");
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Null(result.Title);
}
finally
{
File.Delete(opfFilePath);
}
}
[Fact]
public void Read_WhenOpfFileIsOversized_ShouldReturnEmptyDocument()
{
// Arrange
string opfFilePath = Path.Combine(Path.GetTempPath(), $"oversized-{Guid.NewGuid():N}.opf");
string oversizedContent = $"""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>{new string('a', (5 * 1024 * 1024) + 100)}</dc:title></metadata></package>""";
File.WriteAllText(opfFilePath, oversizedContent);
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Null(result.Title);
Assert.Empty(result.Identifiers);
}
finally
{
File.Delete(opfFilePath);
}
}
[Fact]
public void Read_WhenOpfFileIsMalformedXml_ShouldReturnEmptyDocument()
{
// Arrange
string opfFilePath = CreateOpfFile("""<package xmlns="http://www.idpf.org/2007/opf"><metadata><dc:title>Unclosed""");
try
{
// Act
OpfDocumentDto result = OpfReader.Read(opfFilePath);
// Assert
Assert.Null(result.Title);
Assert.Empty(result.Identifiers);
}
finally
{
File.Delete(opfFilePath);
}
}
/// <summary>
/// Creates a temporary OPF file with the given content and returns its path.
/// </summary>
/// <param name="content">The content of the OPF file to create.</param>
/// <returns>The file system path of the created OPF file.</returns>
private static string CreateOpfFile(string content)
{
string opfFilePath = Path.Combine(Path.GetTempPath(), $"opf-{Guid.NewGuid():N}.opf");
File.WriteAllText(opfFilePath, content);
return opfFilePath;
}
}
@@ -1,635 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Plugins.Epub.Core.Epub;
using Lumina.Plugins.Epub.Fixtures.Core.Epub;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
#endregion
namespace Lumina.Plugins.Epub.UnitTests.Core.Epub;
/// <summary>
/// Contains unit tests for the <see cref="EpubDocumentParser"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EpubDocumentParserTests : IDisposable
{
private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-epub-tests-{Guid.NewGuid():N}");
private readonly string _epubPath;
/// <summary>
/// Initializes a new instance of the <see cref="EpubDocumentParserTests"/> class.
/// </summary>
public EpubDocumentParserTests()
{
Directory.CreateDirectory(_temporaryDirectory);
_epubPath = Path.Combine(_temporaryDirectory, "minimal.epub");
}
[Fact]
public void Parse_WhenCalledOnValidEpub_ShouldReturnDocumentWithTitleAuthorAndSpine()
{
// Arrange
TestEpubFileFactory.CreateMinimalEpub(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal("Minimal EPUB Book", result.Title);
Assert.Equal("Test Author", result.Author);
Assert.Equal(2, result.Spine.Count);
Assert.Equal("chapter1", result.Spine[0].LocationRef);
Assert.Equal("chapter2", result.Spine[1].LocationRef);
Assert.True(result.HasTextContent);
}
[Fact]
public void Parse_WhenCalledOnValidEpub_ShouldExtractResourcesAndRewriteReferences()
{
// Arrange
TestEpubFileFactory.CreateMinimalEpub(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
string expectedKey = CreateResourceKey("images/cover.png");
KeyValuePair<string, ReadingResourceInfoDto> resource = Assert.Single(result.Resources);
Assert.Equal(expectedKey, resource.Key);
Assert.Equal("image/png", resource.Value.MimeType);
Assert.True(File.Exists(Path.Combine(workingDirectory, resource.Value.RelativeFilePath)));
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, result.Spine[0].RelativeSectionFilePath));
Assert.Contains($"data-lumina-resource=\"{expectedKey}\"", sectionContent, StringComparison.Ordinal);
Assert.DoesNotContain("src=\"images/cover.png\"", sectionContent, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenSectionDeclaresADoctypeAndNamedEntities_ShouldRewriteItsReferencesAndResolveTheEntities()
{
// Arrange
TestEpubFileFactory.CreateEpubWithDoctypeAndNamedEntities(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
ReadingSpineItemDto spineItem = Assert.Single(result.Spine);
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath));
string expectedKey = CreateResourceKey("images/cover.png");
// The DTD declaration was tolerated and the named character references resolved, so the section was rewritten instead of
// being served "as-is": the internal image reference became the resource marker and the non-breaking spaces were decoded.
Assert.Contains($"data-lumina-resource=\"{expectedKey}\"", sectionContent, StringComparison.Ordinal);
Assert.DoesNotContain("src=\"images/cover.png\"", sectionContent, StringComparison.Ordinal);
Assert.DoesNotContain("<!DOCTYPE", sectionContent, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("&nbsp;", sectionContent, StringComparison.Ordinal);
Assert.Contains("Chapter\u00A0One", sectionContent, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenCalledOnValidEpub_ShouldBuildTableOfContentsFromTheNavigationDocument()
{
// Arrange
TestEpubFileFactory.CreateMinimalEpub(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// The parser collects every list item of the navigation document, including the nested ones, so the nested
// "Part One" entry is present both at the top level and as a child of its parent entry; the anchor-less item
// yields a non-navigable entry.
Assert.Equal(4, result.TableOfContents.Count);
ReadingTocEntryDto firstEntry = result.TableOfContents[0];
Assert.Equal("Chapter One", firstEntry.Label);
Assert.Equal("chapter1", firstEntry.LocationRef);
ReadingTocEntryDto childEntry = Assert.Single(firstEntry.Children);
Assert.Equal("Part One", childEntry.Label);
Assert.Equal("chapter1", childEntry.LocationRef);
Assert.Equal("Part One", result.TableOfContents[1].Label);
Assert.Equal("chapter1", result.TableOfContents[1].LocationRef);
Assert.Equal("Chapter Two", result.TableOfContents[2].Label);
Assert.Equal("chapter2", result.TableOfContents[2].LocationRef);
Assert.Equal(string.Empty, result.TableOfContents[3].Label);
Assert.Equal(string.Empty, result.TableOfContents[3].LocationRef);
Assert.Equal("Chapter One", result.Spine[0].Title);
Assert.Equal("Chapter Two", result.Spine[1].Title);
}
[Fact]
public void Parse_WhenCalledOnValidEpub_ShouldExposeTheCoverResourceKey()
{
// Arrange
TestEpubFileFactory.CreateMinimalEpub(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal(CreateResourceKey("images/cover.png"), result.CoverResourceKey);
}
[Fact]
public void Parse_WhenEpubHasNoContainerDocument_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithoutContainer(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("OPF", exception.Message, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenEpubHasNoSpine_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithoutSpine(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("reading sections", exception.Message, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenEpubHasTraversalHref_ShouldSkipTheBrokenItemAndKeepTheRest()
{
// Arrange
TestEpubFileFactory.CreateEpubWithTraversalHref(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// The broken manifest item is skipped, while the resolvable section is still parsed.
Assert.Equal("Traversal Href", result.Title);
ReadingSpineItemDto spineItem = Assert.Single(result.Spine);
Assert.Equal("chapter2", spineItem.LocationRef);
}
[Fact]
public void Parse_WhenSectionIsNotWellFormedXml_ShouldServeTheSectionAsIs()
{
// Arrange
TestEpubFileFactory.CreateEpubWithBrokenSection(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
ReadingSpineItemDto spineItem = Assert.Single(result.Spine);
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath));
Assert.Contains("Not well formed", sectionContent, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenEpub2HasNcxToc_ShouldBuildTableOfContentsFromTheNcxDocument()
{
// Arrange
TestEpubFileFactory.CreateEpubWithNcxToc(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal("EPUB 2 Book", result.Title);
// The NCX entries: Chapter One (with its nested Part One), Chapter Two, the anchor-less entry whose target is
// missing, and the entry with a blank label and no content source.
Assert.Equal(4, result.TableOfContents.Count);
ReadingTocEntryDto firstEntry = result.TableOfContents[0];
Assert.Equal("NCX Chapter One", firstEntry.Label);
Assert.Equal("chapter1", firstEntry.LocationRef);
ReadingTocEntryDto childEntry = Assert.Single(firstEntry.Children);
Assert.Equal("NCX Part One", childEntry.Label);
Assert.Equal("chapter1", childEntry.LocationRef);
Assert.Equal("NCX Chapter Two", result.TableOfContents[1].Label);
Assert.Equal("chapter2", result.TableOfContents[1].LocationRef);
// A navigation point without a label and pointing at an unknown file yields a non-navigable entry.
Assert.Equal(string.Empty, result.TableOfContents[2].Label);
Assert.Equal(string.Empty, result.TableOfContents[2].LocationRef);
// A navigation point with a blank label and no content source also yields a non-navigable entry.
Assert.Equal(string.Empty, result.TableOfContents[3].Label);
Assert.Equal(string.Empty, result.TableOfContents[3].LocationRef);
Assert.Equal("NCX Chapter One", result.Spine[0].Title);
Assert.Equal("NCX Chapter Two", result.Spine[1].Title);
// The cover is declared with an EPUB 2 meta element, and is still exposed.
Assert.Equal(CreateResourceKey("images/cover.png"), result.CoverResourceKey);
}
[Fact]
public void Parse_WhenEpub2HasNcxTocAndNoNavigationDocument_ShouldUseTheNcxDocument()
{
// Arrange
TestEpubFileFactory.CreateEpubWithNcxToc(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// No EPUB 3 navigation document is present, so every named entry comes from the NCX document.
Assert.Equal("NCX Chapter One", result.TableOfContents[0].Label);
Assert.Equal("NCX Chapter Two", result.TableOfContents[1].Label);
}
[Fact]
public void Parse_WhenManifestCarriesVariedMediaTypes_ShouldExtractOnlyTheUsableResources()
{
// Arrange
TestEpubFileFactory.CreateEpubWithVariedMediaTypes(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// The font, audio, video, and CSS items are extracted as resources; the script is not a resource the reader serves.
Assert.Equal(6, result.Resources.Count);
Assert.Contains(result.Resources, resource => resource.Value.MimeType == "font/woff2");
Assert.Contains(result.Resources, resource => resource.Value.MimeType == "application/vnd.ms-opentype");
Assert.Contains(result.Resources, resource => resource.Value.MimeType == "application/x-font-ttf");
Assert.Contains(result.Resources, resource => resource.Value.MimeType == "audio/mpeg");
Assert.Contains(result.Resources, resource => resource.Value.MimeType == "video/mp4");
Assert.DoesNotContain(result.Resources, resource => resource.Value.MimeType == "application/javascript");
Assert.Contains(result.Resources, resource => resource.Value.MimeType == "text/css");
// The section is the only spine item, so the document still reads.
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenContainerDocumentIsMalformed_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithMalformedContainer(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("OPF", exception.Message, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenNavigationDocumentHasNoTocNav_ShouldReturnEmptyTableOfContents()
{
// Arrange
TestEpubFileFactory.CreateEpubWithNonTocNav(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Empty(result.TableOfContents);
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenEpubHasNoTitle_ShouldUseTheFileNameAsTheTitle()
{
// Arrange
TestEpubFileFactory.CreateEpubWithoutTitle(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal("minimal", result.Title);
Assert.Null(result.Author);
}
[Fact]
public void Parse_WhenManifestContainsBrokenItems_ShouldSkipThemAndKeepTheValidSections()
{
// Arrange
TestEpubFileFactory.CreateEpubWithBrokenManifest(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// The two valid spine items are kept, and the reference to the unknown Id is dropped.
Assert.Equal(2, result.Spine.Count);
Assert.Equal("chapter1", result.Spine[0].LocationRef);
Assert.Equal("chapter2", result.Spine[1].LocationRef);
// The plain item (no properties) is not extracted as a resource because it is not a spine section and not a usable media type.
Assert.Empty(result.Resources);
}
[Fact]
public void Parse_WhenArchiveHasTooManyEntries_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithTooManyEntries(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("too many entries", exception.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Parse_WhenArchiveExpandsBeyondTheLimit_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithTooLargeExpandedSize(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("too large", exception.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Parse_WhenRootfileHasNoFullPath_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithRootfileWithoutPath(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("OPF", exception.Message, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenArchiveFilesAreMissing_ShouldSkipTheBrokenItemsAndKeepTheReadableSection()
{
// Arrange
TestEpubFileFactory.CreateEpubWithMissingArchiveFiles(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// The section whose file is missing from the archive is skipped, while the readable one is kept.
Assert.Single(result.Spine);
Assert.Equal("chapter1", result.Spine[0].LocationRef);
// The resource whose file is missing from the archive is not extracted.
Assert.Empty(result.Resources);
}
[Fact]
public void Parse_WhenTwoItemsShareAHref_ShouldExtractTheResourceOnce()
{
// Arrange
TestEpubFileFactory.CreateEpubWithDuplicateResource(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
string expectedKey = CreateResourceKey("images/cover.png");
KeyValuePair<string, ReadingResourceInfoDto> resource = Assert.Single(result.Resources);
Assert.Equal(expectedKey, resource.Key);
}
[Fact]
public void Parse_WhenNavigationDocumentIsMalformed_ShouldReturnEmptyTableOfContents()
{
// Arrange
TestEpubFileFactory.CreateEpubWithMalformedNavigationDocument(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Empty(result.TableOfContents);
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenNcxDocumentIsMalformed_ShouldReturnEmptyTableOfContents()
{
// Arrange
TestEpubFileFactory.CreateEpubWithMalformedNcx(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Empty(result.TableOfContents);
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenSectionCarriesVariedReferences_ShouldRewriteOnlyTheResolvableOnes()
{
// Arrange
TestEpubFileFactory.CreateEpubWithVariedReferences(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, result.Spine[0].RelativeSectionFilePath));
string expectedKey = CreateResourceKey("images/cover.png");
// The resolvable internal image is rewritten to the resource marker; the fragment variant resolves to the same image.
Assert.Contains($"data-lumina-resource=\"{expectedKey}\"", sectionContent, StringComparison.Ordinal);
Assert.Equal(2, CountOccurrences(sectionContent, "data-lumina-resource"));
// The same-page anchor, data URI, absolute links, mailto, and broken path keep their original value.
Assert.Contains("href=\"#part\"", sectionContent, StringComparison.Ordinal);
Assert.Contains("data:image/png;base64,AAAA", sectionContent, StringComparison.Ordinal);
Assert.Contains("href=\"http://example.com\"", sectionContent, StringComparison.Ordinal);
Assert.Contains("href=\"https://example.com\"", sectionContent, StringComparison.Ordinal);
Assert.Contains("href=\"mailto:a@b.com\"", sectionContent, StringComparison.Ordinal);
Assert.Contains("href=\"tel:+123\"", sectionContent, StringComparison.Ordinal);
Assert.Contains("src=\"missing/image.png\"", sectionContent, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenEpubHasNoMetadataElement_ShouldUseTheFileNameAsTheTitleAndLeaveAuthorNull()
{
// Arrange
TestEpubFileFactory.CreateEpubWithoutMetadataElement(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal("minimal", result.Title);
Assert.Null(result.Author);
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenOpfFileIsMissing_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithMissingOpf(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Throws<InvalidDataException>(act);
}
[Fact]
public void Parse_WhenOpfSitsAtTheArchiveRoot_ShouldResolveSectionsRelativeToIt()
{
// Arrange
TestEpubFileFactory.CreateEpubWithRootLevelOpf(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal("Root Level OPF", result.Title);
ReadingSpineItemDto spineItem = Assert.Single(result.Spine);
Assert.Equal("chapter1", spineItem.LocationRef);
}
[Fact]
public void Parse_WhenResourceHrefEscapesTheArchive_ShouldSkipTheResource()
{
// Arrange
TestEpubFileFactory.CreateEpubWithEscapingResourceHref(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal("Escaping Resource", result.Title);
Assert.Empty(result.Resources);
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenResourceExceedsTheSizeCap_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithOversizedResource(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("too large", exception.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Parse_WhenEntriesFitPerEntryCapsButActualExpandedBytesExceedTheTotalCap_ShouldThrowInvalidDataException()
{
// Arrange
// The entries each declare a tiny uncompressed size and each actual one is under its per-entry cap, so only the budget
// that counts the bytes actually read while the entries are streamed can reject the archive.
TestEpubFileFactory.CreateEpubWithUnderPerEntryCapsButOversizedExpandedSize(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// The declared sizes stay well under the 256 MB cap, so the declared-size quick guard in ValidateArchive cannot be
// what rejects the archive; the rejection can only come from counting the bytes actually read.
long declaredTotalBytes;
using (FileStream fileStream = File.OpenRead(_epubPath))
using (ZipArchive zipArchive = new(fileStream, ZipArchiveMode.Read))
declaredTotalBytes = zipArchive.Entries.Sum(entry => entry.Length);
Assert.True(declaredTotalBytes <= 256 * 1024 * 1024);
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// The total-expanded message is specific to the archive-wide cap, unlike the per-entry "too large" message.
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("expanded EPUB archive", exception.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Parse_WhenManifestItemHasNoMediaType_ShouldSkipIt()
{
// Arrange
TestEpubFileFactory.CreateEpubWithMissingMediaType(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// A manifest item without a media type cannot be classified as an extractable resource, so it is skipped.
Assert.Empty(result.Resources);
Assert.Single(result.Spine);
}
/// <summary>
/// Counts the occurrences of <paramref name="needle"/> in <paramref name="haystack"/>.
/// </summary>
/// <param name="haystack">The text to search.</param>
/// <param name="needle">The substring to count.</param>
/// <returns>The number of occurrences of the substring.</returns>
private static int CountOccurrences(string haystack, string needle)
{
int count = 0;
int index = 0;
while ((index = haystack.IndexOf(needle, index, StringComparison.Ordinal)) >= 0)
{
count++;
index += needle.Length;
}
return count;
}
/// <summary>
/// Computes the resource key the parser derives from a manifest href.
/// </summary>
/// <param name="href">The manifest href.</param>
/// <returns>The resource key of the href.</returns>
private static string CreateResourceKey(string href)
{
return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(href)))[..32].ToLowerInvariant();
}
/// <inheritdoc/>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
}
}
@@ -1,15 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Epub.Core;
using Lumina.Plugins.Epub.Fixtures.Core.Epub;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.Epub.UnitTests.Core;
@@ -18,71 +11,27 @@ namespace Lumina.Plugins.Epub.UnitTests.Core;
/// Contains unit tests for the <see cref="EpubReader"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EpubReaderTests : IDisposable
public class EpubReaderTests
{
private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-epub-reader-{Guid.NewGuid():N}");
private readonly string _epubPath;
private readonly EpubReader _sut = new();
/// <summary>
/// Initializes a new instance of the <see cref="EpubReaderTests"/> class.
/// </summary>
public EpubReaderTests()
{
Directory.CreateDirectory(_temporaryDirectory);
_epubPath = Path.Combine(_temporaryDirectory, "minimal.epub");
TestEpubFileFactory.CreateMinimalEpub(_epubPath);
}
[Fact]
public void SupportedExtensions_WhenAccessed_ShouldOnlyContainEpub()
{
// Act
IReadOnlyList<string> result = _sut.SupportedExtensions;
// Assert
Assert.Equal([".epub"], _sut.SupportedExtensions);
Assert.Equal([".epub"], result);
}
[Fact]
public void SupportedLibraryTypes_WhenAccessed_ShouldContainEBookAndBook()
{
// Assert
Assert.Equal([LibraryType.EBook, LibraryType.Book], _sut.SupportedLibraryTypes);
}
[Fact]
public async Task OpenAsync_WhenCalled_ShouldReturnTheParsedDocument()
{
// Arrange
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = await _sut.OpenAsync(_epubPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
IReadOnlyList<LibraryType> result = _sut.SupportedLibraryTypes;
// Assert
Assert.Equal("Minimal EPUB Book", result.Title);
Assert.Equal(2, result.Spine.Count);
}
[Fact]
public async Task GetResourceAsync_WhenResourceWasExtracted_ShouldReturnItsBytes()
{
// Arrange
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
ReadingDocumentDto document = await _sut.OpenAsync(_epubPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
string resourceKey = document.Resources.Keys.Single();
// Act
byte[] result = await _sut.GetResourceAsync(_epubPath, workingDirectory, resourceKey, CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.NotEmpty(result);
}
/// <inheritdoc/>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
Assert.Equal([LibraryType.EBook, LibraryType.Book], result);
}
}
@@ -1,9 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Pdf.Core.Pdf;
using Lumina.Plugins.Pdf.Fixtures.Core.Pdf;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.Versioning;
@@ -16,81 +13,18 @@ namespace Lumina.Plugins.Pdf.UnitTests.Core.Pdf;
/// Contains unit tests for the <see cref="PdfDocumentParser"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PdfDocumentParserTests : IDisposable
public class PdfDocumentParserTests
{
private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-pdf-tests-{Guid.NewGuid():N}");
private readonly string _pdfPath;
/// <summary>
/// Initializes a new instance of the <see cref="PdfDocumentParserTests"/> class.
/// </summary>
public PdfDocumentParserTests()
{
Directory.CreateDirectory(_temporaryDirectory);
_pdfPath = Path.Combine(_temporaryDirectory, "minimal.pdf");
TestPdfFileFactory.CreateMinimalPdf(_pdfPath);
}
[Fact]
public void Parse_WhenCalledOnPdfWithTextLayer_ShouldReturnDocumentWithTextSections()
{
// Arrange
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(_pdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.Equal("minimal", result.Title);
Assert.True(result.HasTextContent);
ReadingSpineItemDto spineItem = Assert.Single(result.Spine);
Assert.Equal("page:1", spineItem.LocationRef);
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath));
Assert.Contains("<p>Hello PDF Page 1</p>", sectionContent, StringComparison.Ordinal);
Assert.Empty(result.Resources);
}
[Fact]
public void Parse_WhenCalledWithRenderAsImages_ShouldReturnDocumentWithImageSectionsAndNoTextContent()
{
// Arrange
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(_pdfPath, workingDirectory, shouldRenderPdfAsImages: true, CancellationToken.None);
// Assert
Assert.Equal("minimal", result.Title);
Assert.False(result.HasTextContent);
ReadingSpineItemDto spineItem = Assert.Single(result.Spine);
Assert.Equal("page:1", spineItem.LocationRef);
KeyValuePair<string, ReadingResourceInfoDto> resource = Assert.Single(result.Resources);
Assert.Equal("page:1", resource.Key);
Assert.Equal("image/png", resource.Value.MimeType);
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath));
Assert.Contains("data-lumina-resource=\"page:1\"", sectionContent, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenPdfFileDoesNotExist_ShouldThrowFileNotFoundException()
{
// Arrange
string missingPdfPath = Path.Combine(_temporaryDirectory, "missing.pdf");
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => PdfDocumentParser.Parse(missingPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.Throws<FileNotFoundException>(act);
}
[SupportedOSPlatform("windows")]
[Fact]
public void RenderResource_WhenResourceKeyDoesNotIdentifyAPage_ShouldThrowInvalidDataException()
{
// Arrange
// The resource key is rejected before RenderResource opens the PDF, so the path never needs to exist.
string missingPdfPath = "missing.pdf";
// Act
Action act = () => PdfDocumentParser.RenderResource(_pdfPath, "not-a-page", CancellationToken.None);
Action act = () => PdfDocumentParser.RenderResource(missingPdfPath, "not-a-page", CancellationToken.None);
// Assert
Assert.Throws<InvalidDataException>(act);
@@ -100,142 +34,14 @@ public class PdfDocumentParserTests : IDisposable
[Fact]
public void RenderResource_WhenResourceKeyNamesAPageBeyondThePageCap_ShouldThrowInvalidDataException()
{
// Arrange
// The page cap is enforced before RenderResource opens the PDF, so the path never needs to exist.
string missingPdfPath = "missing.pdf";
// Act
// The minimal PDF has a single page, but the key is rejected by the page cap before the document is even opened.
Action act = () => PdfDocumentParser.RenderResource(_pdfPath, "page:10001", CancellationToken.None);
Action act = () => PdfDocumentParser.RenderResource(missingPdfPath, "page:10001", CancellationToken.None);
// Assert
Assert.Throws<InvalidDataException>(act);
}
[SupportedOSPlatform("windows")]
[Fact]
public void RenderResource_WhenResourceKeyNamesAPageBeyondTheDocument_ShouldThrowInvalidDataException()
{
// Act
// The minimal PDF has a single page, so page 2 is rejected against the page count of the document without rendering it.
Action act = () => PdfDocumentParser.RenderResource(_pdfPath, "page:2", CancellationToken.None);
// Assert
Assert.Throws<InvalidDataException>(act);
}
[Fact]
public void Parse_WhenPdfHasBookmarks_ShouldBuildTableOfContentsFromTheOutline()
{
// Arrange
string outlinedPdfPath = Path.Combine(_temporaryDirectory, "outlined.pdf");
TestPdfFileFactory.CreatePdfWithOutline(outlinedPdfPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(outlinedPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
// PdfPig does not surface a bookmark without a title, so only the three titled top-level entries appear.
Assert.Equal(3, result.TableOfContents.Count);
ReadingTocEntryDto chapterOne = result.TableOfContents[0];
Assert.Equal("Chapter One", chapterOne.Label);
Assert.Equal("page:1", chapterOne.LocationRef);
ReadingTocEntryDto partOne = Assert.Single(chapterOne.Children);
Assert.Equal("Part One", partOne.Label);
Assert.Equal("page:1", partOne.LocationRef);
Assert.Equal("Chapter Two", result.TableOfContents[1].Label);
Assert.Equal("page:2", result.TableOfContents[1].LocationRef);
// A bookmark pointing at a URI instead of a page yields an entry that is not navigable.
Assert.Equal("External Link", result.TableOfContents[2].Label);
Assert.Equal(string.Empty, result.TableOfContents[2].LocationRef);
}
[Fact]
public void Parse_WhenPdfIsTooLarge_ShouldThrowInvalidDataException()
{
// Arrange
string oversizedPdfPath = Path.Combine(_temporaryDirectory, "oversized.pdf");
// A sparse file larger than the 500 MB cap, without allocating disk space.
using (FileStream fileStream = new(oversizedPdfPath, FileMode.Create, FileAccess.Write))
fileStream.SetLength(501L * 1024 * 1024);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => PdfDocumentParser.Parse(oversizedPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.Throws<InvalidDataException>(act);
}
[Fact]
public void Parse_WhenPdfHasABlankTextLine_ShouldSkipTheBlankLineAndKeepTheOthers()
{
// Arrange
string blankLinePdfPath = Path.Combine(_temporaryDirectory, "blankline.pdf");
TestPdfFileFactory.CreatePdfWithBlankLine(blankLinePdfPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(blankLinePdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, result.Spine[0].RelativeSectionFilePath));
Assert.Contains("<p>First line</p>", sectionContent, StringComparison.Ordinal);
Assert.Contains("<p>Third line</p>", sectionContent, StringComparison.Ordinal);
Assert.DoesNotContain("<p></p>", sectionContent, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenPdfOutlineIsMalformed_ShouldSkipTheTableOfContentsAndKeepThePages()
{
// Arrange
string malformedOutlinePdfPath = Path.Combine(_temporaryDirectory, "malformed-outline.pdf");
TestPdfFileFactory.CreatePdfWithMalformedOutline(malformedOutlinePdfPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(malformedOutlinePdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
// The malformed bookmarks are best effort: the table of contents is skipped, but the pages are still readable.
Assert.Empty(result.TableOfContents);
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenPdfExceedsThePageCap_ShouldStopAtTheCap()
{
// Arrange
string manyPagesPdfPath = Path.Combine(_temporaryDirectory, "many-pages.pdf");
TestPdfFileFactory.CreatePdfWithMorePagesThanAllowed(manyPagesPdfPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(manyPagesPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
// The parser stops enumerating after the page cap instead of reading every page.
Assert.Equal(10_000, result.Spine.Count);
}
[Fact]
public void ParseAsImages_WhenPdfExceedsThePageCap_ShouldStopAtTheCap()
{
// Arrange
string manyPagesPdfPath = Path.Combine(_temporaryDirectory, "many-pages-images.pdf");
TestPdfFileFactory.CreatePdfWithMorePagesThanAllowed(manyPagesPdfPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(manyPagesPdfPath, workingDirectory, shouldRenderPdfAsImages: true, CancellationToken.None);
// Assert
Assert.Equal(10_000, result.Spine.Count);
Assert.Equal(10_000, result.Resources.Count);
}
/// <inheritdoc/>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
}
}
@@ -1,14 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Pdf.Core;
using Lumina.Plugins.Pdf.Fixtures.Core.Pdf;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.Pdf.UnitTests.Core;
@@ -17,70 +11,27 @@ namespace Lumina.Plugins.Pdf.UnitTests.Core;
/// Contains unit tests for the <see cref="PdfReader"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PdfReaderTests : IDisposable
public class PdfReaderTests
{
private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-pdf-reader-{Guid.NewGuid():N}");
private readonly string _pdfPath;
private readonly PdfReader _sut = new();
/// <summary>
/// Initializes a new instance of the <see cref="PdfReaderTests"/> class.
/// </summary>
public PdfReaderTests()
{
Directory.CreateDirectory(_temporaryDirectory);
_pdfPath = Path.Combine(_temporaryDirectory, "minimal.pdf");
TestPdfFileFactory.CreateMinimalPdf(_pdfPath);
}
[Fact]
public void SupportedExtensions_WhenAccessed_ShouldOnlyContainPdf()
{
// Act
IReadOnlyList<string> result = _sut.SupportedExtensions;
// Assert
Assert.Equal([".pdf"], _sut.SupportedExtensions);
Assert.Equal([".pdf"], result);
}
[Fact]
public void SupportedLibraryTypes_WhenAccessed_ShouldContainEBookAndBook()
{
// Assert
Assert.Equal([LibraryType.EBook, LibraryType.Book], _sut.SupportedLibraryTypes);
}
[Fact]
public async Task OpenAsync_WhenCalled_ShouldReturnTheParsedDocument()
{
// Arrange
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = await _sut.OpenAsync(_pdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
IReadOnlyList<LibraryType> result = _sut.SupportedLibraryTypes;
// Assert
Assert.Equal("minimal", result.Title);
Assert.Single(result.Spine);
}
[SupportedOSPlatform("windows")]
[Fact]
public async Task GetResourceAsync_WhenCalledForAPage_ShouldRenderThePageImage()
{
// Arrange
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
byte[] result = await _sut.GetResourceAsync(_pdfPath, workingDirectory, "page:1", CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.NotEmpty(result);
}
/// <inheritdoc/>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
Assert.Equal([LibraryType.EBook, LibraryType.Book], result);
}
}