fix(hibernate): improve transaction management and optimize entity fetching (#176)

* fix(hibernate): improve transaction management and optimize entity fetching

* chore(tests): clean-up comments

* chore: fix config issue in the kotlin dsl

* fix(hibernate): fix entity equality checks

* fix(hibernate): add transactional read-only support to BookService

* Update booklore-api/src/main/java/org/booklore/model/entity/BookLoreUserEntity.java

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* fix(hibernate): remove redundant annotations in BookLoreUserEntity

* fix(hibernate): import Hibernate

* fix(tests): fix merge conflict caused errors

* refactor(book): optimize book retrieval methods and reduce cache sizes

* refactor(metadata): remove lazy loading from description field in BookMetadataEntity

* fix(build): increase max heap size for test tasks

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
This commit is contained in:
brios
2026-04-22 17:27:01 -04:00
committed by Zach Yale
co-authored by coderabbitai[bot]
parent be0b717ff4
commit ad3a981ad1
73 changed files with 1902 additions and 435 deletions
@@ -149,7 +149,7 @@ class LogoutServiceTest {
assertThat(token1.getRevocationDate()).isNotNull();
assertThat(token2.isRevoked()).isTrue();
assertThat(token2.getRevocationDate()).isNotNull();
verify(refreshTokenRepository, times(2)).save(any(RefreshTokenEntity.class));
verify(refreshTokenRepository).saveAll(any());
}
@Test
@@ -8,6 +8,7 @@ import org.booklore.model.entity.BookMetadataEntity;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.service.task.TaskCronService;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@@ -44,7 +45,8 @@ import static org.mockito.Mockito.mock;
"spring.task.scheduling.enabled=false",
"app.task.scan-library-cron=*/1 * * * * *",
"app.task.process-bookdrop-cron=*/1 * * * * *",
"app.features.oidc-enabled=false"
"app.features.oidc-enabled=false",
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
})
@Import(BookOpdsRepositoryDataJpaTest.TestConfig.class)
class BookOpdsRepositoryDataJpaTest {
@@ -59,8 +61,8 @@ class BookOpdsRepositoryDataJpaTest {
public static class TestConfig {
@Bean("flyway")
@Primary
public org.flywaydb.core.Flyway flyway() {
return mock(org.flywaydb.core.Flyway.class);
public Flyway flyway() {
return mock(Flyway.class);
}
@Bean
@@ -113,4 +115,4 @@ class BookOpdsRepositoryDataJpaTest {
assertThat(result).hasSize(1);
assertThat(result.get(0).getId()).isEqualTo(book.getId());
}
}
}
@@ -48,7 +48,8 @@ import static org.mockito.Mockito.mock;
"spring.task.scheduling.enabled=false",
"app.task.scan-library-cron=*/1 * * * * *",
"app.task.process-bookdrop-cron=*/1 * * * * *",
"app.features.oidc-enabled=false"
"app.features.oidc-enabled=false",
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
})
@Import(BookRuleEvaluatorEdgeCasesTest.TestConfig.class)
class BookRuleEvaluatorEdgeCasesTest {
@@ -8,6 +8,7 @@ import org.booklore.model.entity.*;
import org.booklore.model.enums.ReadStatus;
import org.booklore.repository.BookRepository;
import org.booklore.service.task.TaskCronService;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@@ -52,7 +53,8 @@ import static org.mockito.Mockito.mock;
"spring.task.scheduling.enabled=false",
"app.task.scan-library-cron=*/1 * * * * *",
"app.task.process-bookdrop-cron=*/1 * * * * *",
"app.features.oidc-enabled=false"
"app.features.oidc-enabled=false",
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
})
@Import(BookRuleEvaluatorFieldCoverageTest.TestConfig.class)
class BookRuleEvaluatorFieldCoverageTest {
@@ -61,8 +63,8 @@ class BookRuleEvaluatorFieldCoverageTest {
static class TestConfig {
@Bean("flyway")
@Primary
public org.flywaydb.core.Flyway flyway() {
return mock(org.flywaydb.core.Flyway.class);
public Flyway flyway() {
return mock(Flyway.class);
}
@Bean
@@ -9,6 +9,7 @@ import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.ReadStatus;
import org.booklore.repository.BookRepository;
import org.booklore.service.task.TaskCronService;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@@ -45,7 +46,8 @@ import static org.mockito.Mockito.mock;
"spring.task.scheduling.enabled=false",
"app.task.scan-library-cron=*/1 * * * * *",
"app.task.process-bookdrop-cron=*/1 * * * * *",
"app.features.oidc-enabled=false"
"app.features.oidc-enabled=false",
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
})
@Import(BookRuleEvaluatorNumericFieldsTest.TestConfig.class)
class BookRuleEvaluatorNumericFieldsTest {
@@ -54,8 +56,8 @@ class BookRuleEvaluatorNumericFieldsTest {
static class TestConfig {
@Bean("flyway")
@Primary
public org.flywaydb.core.Flyway flyway() {
return mock(org.flywaydb.core.Flyway.class);
public Flyway flyway() {
return mock(Flyway.class);
}
@Bean
@@ -10,6 +10,7 @@ import org.booklore.model.enums.ComicCreatorRole;
import org.booklore.model.enums.ReadStatus;
import org.booklore.repository.BookRepository;
import org.booklore.service.task.TaskCronService;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@@ -51,7 +52,8 @@ import static org.mockito.Mockito.mock;
"spring.task.scheduling.enabled=false",
"app.task.scan-library-cron=*/1 * * * * *",
"app.task.process-bookdrop-cron=*/1 * * * * *",
"app.features.oidc-enabled=false"
"app.features.oidc-enabled=false",
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
})
@Import(BookRuleEvaluatorServiceIntegrationTest.TestConfig.class)
class BookRuleEvaluatorServiceIntegrationTest {
@@ -60,8 +62,8 @@ class BookRuleEvaluatorServiceIntegrationTest {
static class TestConfig {
@Bean("flyway")
@Primary
public org.flywaydb.core.Flyway flyway() {
return mock(org.flywaydb.core.Flyway.class);
public Flyway flyway() {
return mock(Flyway.class);
}
@Bean
@@ -0,0 +1,962 @@
package org.booklore.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.booklore.BookloreApplication;
import org.booklore.model.entity.*;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.task.TaskCronService;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Integration tests verifying Hibernate entity relationships, lazy loading,
* and transaction boundaries work correctly after the Hibernate refactoring.
*
* These tests run against H2 with create-drop DDL, exercising real JPA persistence
* to catch regressions that unit tests with mocks cannot detect.
*/
@SpringBootTest(classes = BookloreApplication.class)
@Transactional
@TestPropertySource(properties = {
"spring.flyway.enabled=false",
"spring.jpa.hibernate.ddl-auto=create-drop",
"spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
"spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect",
"spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1",
"spring.datasource.driver-class-name=org.h2.Driver",
"spring.datasource.username=sa",
"spring.datasource.password=",
"app.path-config=build/tmp/test-config",
"app.bookdrop-folder=build/tmp/test-bookdrop",
"spring.main.allow-bean-definition-overriding=true",
"spring.task.scheduling.enabled=false",
"app.task.scan-library-cron=*/1 * * * * *",
"app.task.process-bookdrop-cron=*/1 * * * * *",
"app.features.oidc-enabled=false",
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
})
@Import(HibernateRegressionTest.TestConfig.class)
class HibernateRegressionTest {
@Autowired
private LibraryRepository libraryRepository;
@Autowired
private BookRepository bookRepository;
@PersistenceContext
private EntityManager entityManager;
@org.springframework.boot.test.context.TestConfiguration
public static class TestConfig {
@Bean("flyway")
@Primary
public Flyway flyway() {
return mock(Flyway.class);
}
@Bean
@Primary
public TaskCronService taskCronService() {
return mock(TaskCronService.class);
}
}
@Test
void contextLoads() {
assertThat(libraryRepository).isNotNull();
assertThat(bookRepository).isNotNull();
}
@Nested
class LibraryPathBackReference {
/**
* Regression: createLibrary() must set LibraryPathEntity.library back-reference.
* Without enableAssociationManagement, Hibernate no longer auto-manages
* bidirectional relationships. If the back-reference is missing, the FK
* column library_id is NULL and paths are not linked to the library.
*/
@Test
void libraryPathsMustHaveLibraryBackReference_whenPersistedViaCascade() {
LibraryEntity library = LibraryEntity.builder()
.name("Cascade Test Library")
.icon("book")
.watch(false)
.libraryPaths(new ArrayList<>(List.of(
LibraryPathEntity.builder().path("/books/fiction").build(),
LibraryPathEntity.builder().path("/books/nonfiction").build()
)))
.build();
// Simulate what createLibrary() must do: set the back-reference
library.getLibraryPaths().forEach(p -> p.setLibrary(library));
LibraryEntity saved = libraryRepository.saveAndFlush(library);
entityManager.clear();
LibraryEntity reloaded = libraryRepository.findByIdWithPaths(saved.getId()).orElseThrow();
assertThat(reloaded.getLibraryPaths()).hasSize(2);
for (LibraryPathEntity path : reloaded.getLibraryPaths()) {
assertThat(path.getLibrary()).isNotNull();
assertThat(path.getLibrary().getId()).isEqualTo(reloaded.getId());
}
}
/**
* Verify that the owning side FK is actually persisted to the DB and
* the library can find its paths after a fresh session load.
*/
@Test
void libraryPathForeignKey_isPersistedCorrectly() {
LibraryEntity library = LibraryEntity.builder()
.name("FK Test Library")
.icon("book")
.watch(false)
.build();
entityManager.persist(library);
entityManager.flush();
LibraryPathEntity path = LibraryPathEntity.builder()
.library(library)
.path("/test/path")
.build();
entityManager.persist(path);
entityManager.flush();
entityManager.clear();
// Verify via JPQL that the FK is set
Long count = entityManager.createQuery(
"SELECT COUNT(lp) FROM LibraryPathEntity lp WHERE lp.library.id = :libId", Long.class)
.setParameter("libId", library.getId())
.getSingleResult();
assertThat(count).isEqualTo(1L);
}
/**
* Without back-reference, cascade persist puts NULL in library_id.
* This test verifies the issue exists if back-ref is not set,
* by checking constraint violation.
*/
@Test
void cascadePersist_withoutBackReference_failsWithConstraintViolation() {
LibraryEntity library = LibraryEntity.builder()
.name("Missing BackRef Library")
.icon("book")
.watch(false)
.libraryPaths(new ArrayList<>(List.of(
LibraryPathEntity.builder().path("/dangling").build()
)))
.build();
// Intentionally NOT setting library back-reference
Assertions.assertThrows(
org.springframework.dao.DataIntegrityViolationException.class,
() -> {
libraryRepository.saveAndFlush(library);
entityManager.flush();
},
"Should fail because library_id is NOT NULL but no back-reference was set"
);
}
}
@Nested
class EntityGraphQueries {
private LibraryEntity library;
private LibraryPathEntity libraryPath;
@BeforeEach
void setUp() {
library = LibraryEntity.builder()
.name("EntityGraph Test Library")
.icon("book")
.watch(false)
.build();
entityManager.persist(library);
libraryPath = LibraryPathEntity.builder()
.library(library)
.path("/test/books")
.build();
entityManager.persist(libraryPath);
entityManager.flush();
}
/**
* findByIdWithPaths must eagerly load libraryPaths so they are
* accessible outside a Hibernate session (e.g., in virtual threads).
*/
@Test
void findByIdWithPaths_loadsLibraryPathsEagerly() {
entityManager.clear();
LibraryEntity loaded = libraryRepository.findByIdWithPaths(library.getId()).orElseThrow();
// Detach to simulate outside-session access
entityManager.detach(loaded);
// This must NOT throw LazyInitializationException
assertThat(loaded.getLibraryPaths()).hasSize(1);
assertThat(loaded.getLibraryPaths().get(0).getPath()).isEqualTo("/test/books");
}
/**
* findByIdWithBooks must eagerly load bookEntities.
*/
@Test
void findByIdWithBooks_loadsBookEntitiesEagerly() {
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(libraryPath)
.addedOn(Instant.now())
.deleted(false)
.build();
entityManager.persist(book);
entityManager.flush();
entityManager.clear();
LibraryEntity loaded = libraryRepository.findByIdWithBooks(library.getId()).orElseThrow();
entityManager.detach(loaded);
assertThat(loaded.getBookEntities()).hasSize(1);
}
/**
* findByIdWithBookFiles must eagerly load bookFiles via EntityGraph.
*/
@Test
void findByIdWithBookFiles_loadsBookFilesEagerly() {
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(libraryPath)
.addedOn(Instant.now())
.deleted(false)
.build();
entityManager.persist(book);
entityManager.flush();
BookFileEntity bookFile = BookFileEntity.builder()
.book(book)
.fileName("test.epub")
.fileSubPath("")
.isBookFormat(true)
.bookType(BookFileType.EPUB)
.fileSizeKb(100L)
.initialHash("abc123")
.currentHash("abc123")
.addedOn(Instant.now())
.build();
entityManager.persist(bookFile);
entityManager.flush();
entityManager.clear();
BookEntity loaded = bookRepository.findByIdWithBookFiles(book.getId()).orElseThrow();
entityManager.detach(loaded);
// Must NOT throw LazyInitializationException
assertThat(loaded.getBookFiles()).hasSize(1);
assertThat(loaded.getBookFiles().get(0).getFileName()).isEqualTo("test.epub");
}
}
@Nested
class BookEntityDefaults {
/**
* Regression: BookEntity.deleted must default to FALSE (not null)
* so that queries filtering on deleted work correctly.
*/
@Test
void bookEntity_deletedFieldDefaultsToFalse() {
LibraryEntity library = LibraryEntity.builder()
.name("Defaults Test")
.icon("book")
.watch(false)
.build();
entityManager.persist(library);
LibraryPathEntity path = LibraryPathEntity.builder()
.library(library)
.path("/test")
.build();
entityManager.persist(path);
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(path)
.addedOn(Instant.now())
.build();
entityManager.persist(book);
entityManager.flush();
entityManager.clear();
BookEntity loaded = entityManager.find(BookEntity.class, book.getId());
assertThat(loaded.getDeleted()).isEqualTo(Boolean.FALSE);
}
/**
* findByIdWithBookFiles must find books where deleted = false.
*/
@Test
void findByIdWithBookFiles_findsNonDeletedBook() {
LibraryEntity library = LibraryEntity.builder()
.name("Non-deleted Test")
.icon("book")
.watch(false)
.build();
entityManager.persist(library);
LibraryPathEntity path = LibraryPathEntity.builder()
.library(library)
.path("/test")
.build();
entityManager.persist(path);
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(path)
.addedOn(Instant.now())
.deleted(false)
.build();
entityManager.persist(book);
entityManager.flush();
entityManager.clear();
assertThat(bookRepository.findByIdWithBookFiles(book.getId())).isPresent();
}
/**
* findByIdWithBookFiles must NOT find soft-deleted books.
*/
@Test
void findByIdWithBookFiles_excludesDeletedBooks() {
LibraryEntity library = LibraryEntity.builder()
.name("Deleted Test")
.icon("book")
.watch(false)
.build();
entityManager.persist(library);
LibraryPathEntity path = LibraryPathEntity.builder()
.library(library)
.path("/test")
.build();
entityManager.persist(path);
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(path)
.addedOn(Instant.now())
.deleted(true)
.build();
entityManager.persist(book);
entityManager.flush();
entityManager.clear();
assertThat(bookRepository.findByIdWithBookFiles(book.getId())).isEmpty();
}
}
@Nested
class CollectionInitialization {
/**
* Verify that @Builder.Default collection fields are initialized
* and not null after entity construction via builder.
*/
@Test
void libraryEntity_collectionsAreInitialized() {
LibraryEntity library = LibraryEntity.builder()
.name("Init Test")
.icon("book")
.watch(false)
.build();
assertThat(library.getLibraryPaths()).isNotNull();
assertThat(library.getBookEntities()).isNotNull();
assertThat(library.getUsers()).isNotNull();
assertThat(library.getFormatPriority()).isNotNull();
}
@Test
void bookEntity_collectionsAreInitialized() {
BookEntity book = BookEntity.builder()
.addedOn(Instant.now())
.build();
assertThat(book.getBookFiles()).isNotNull();
assertThat(book.getShelves()).isNotNull();
assertThat(book.getUserBookProgress()).isNotNull();
assertThat(book.getDeleted()).isEqualTo(Boolean.FALSE);
assertThat(book.getIsPhysical()).isEqualTo(Boolean.FALSE);
}
}
@Nested
class LibraryScanSimulation {
/**
* Simulate the library scan flow: create library with paths,
* then verify paths can be loaded and iterated for scanning.
* This is the exact flow broken when enableAssociationManagement
* was removed paths had NULL library_id so scanning found 0 paths.
*/
@Test
void libraryWithPaths_canBeLoadedAndIteratedForScanning() {
// Simulate LibraryService.createLibrary() flow
LibraryEntity library = LibraryEntity.builder()
.name("Scan Simulation Library")
.icon("book")
.watch(false)
.libraryPaths(new ArrayList<>(List.of(
LibraryPathEntity.builder().path("/books").build(),
LibraryPathEntity.builder().path("/audiobooks").build()
)))
.build();
library.getLibraryPaths().forEach(p -> p.setLibrary(library));
libraryRepository.saveAndFlush(library);
entityManager.clear();
LibraryEntity loaded = libraryRepository.findByIdWithPaths(library.getId()).orElseThrow();
List<String> pathStrings = loaded.getLibraryPaths().stream()
.map(LibraryPathEntity::getPath)
.collect(Collectors.toList());
assertThat(pathStrings).containsExactlyInAnyOrder("/books", "/audiobooks");
}
/**
* Verify the updateLibrary flow — updating paths preserves back-references.
*/
@Test
void updateLibraryPaths_preservesBackReferences() {
LibraryEntity library = LibraryEntity.builder()
.name("Update Test Library")
.icon("book")
.watch(false)
.build();
entityManager.persist(library);
LibraryPathEntity path1 = LibraryPathEntity.builder()
.library(library)
.path("/old/path")
.build();
entityManager.persist(path1);
entityManager.flush();
entityManager.clear();
// Simulate updateLibrary() — load, clear paths, add new ones
LibraryEntity loaded = libraryRepository.findByIdWithPaths(library.getId()).orElseThrow();
loaded.getLibraryPaths().clear();
LibraryPathEntity newPath = LibraryPathEntity.builder()
.library(loaded) // back-reference set here
.path("/new/path")
.build();
loaded.getLibraryPaths().add(newPath);
libraryRepository.saveAndFlush(loaded);
entityManager.clear();
LibraryEntity reloaded = libraryRepository.findByIdWithPaths(library.getId()).orElseThrow();
assertThat(reloaded.getLibraryPaths()).hasSize(1);
assertThat(reloaded.getLibraryPaths().get(0).getPath()).isEqualTo("/new/path");
assertThat(reloaded.getLibraryPaths().get(0).getLibrary().getId()).isEqualTo(library.getId());
}
}
@Nested
class BookCreationFlow {
/**
* Simulate BookCreatorService.createShellBook() — verify book with
* related entities can be saved and reloaded with all relationships intact.
*/
@Test
void createShellBook_savesAllRelationships() {
LibraryEntity library = LibraryEntity.builder()
.name("Book Creation Library")
.icon("book")
.watch(false)
.build();
entityManager.persist(library);
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
.library(library)
.path("/books")
.build();
entityManager.persist(libraryPath);
entityManager.flush();
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(libraryPath)
.addedOn(Instant.now())
.bookFiles(new ArrayList<>())
.build();
BookFileEntity bookFile = BookFileEntity.builder()
.book(book)
.fileName("test.epub")
.fileSubPath("")
.isBookFormat(true)
.bookType(BookFileType.EPUB)
.fileSizeKb(500L)
.initialHash("hash1")
.currentHash("hash1")
.addedOn(Instant.now())
.build();
book.getBookFiles().add(bookFile);
BookMetadataEntity metadata = BookMetadataEntity.builder()
.book(book)
.title("Test Book Title")
.build();
book.setMetadata(metadata);
entityManager.persist(book);
entityManager.flush();
entityManager.clear();
BookEntity loaded = bookRepository.findByIdWithBookFiles(book.getId()).orElseThrow();
assertThat(loaded.getLibrary().getId()).isEqualTo(library.getId());
assertThat(loaded.getLibraryPath().getId()).isEqualTo(libraryPath.getId());
assertThat(loaded.getBookFiles()).hasSize(1);
assertThat(loaded.getBookFiles().get(0).getFileName()).isEqualTo("test.epub");
assertThat(loaded.getMetadata().getTitle()).isEqualTo("Test Book Title");
assertThat(loaded.getDeleted()).isFalse();
}
/**
* Verify that saveAndFlush generates an ID that can be used
* to refetch the book — critical for bookdrop finalization flow
* where processFile() saves in REQUIRES_NEW and the parent
* transaction needs to find it.
*/
@Test
void saveAndFlush_generatesIdForImmediateRetrieval() {
LibraryEntity library = LibraryEntity.builder()
.name("SaveFlush Library")
.icon("book")
.watch(false)
.build();
entityManager.persist(library);
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
.library(library)
.path("/books")
.build();
entityManager.persist(libraryPath);
entityManager.flush();
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(libraryPath)
.addedOn(Instant.now())
.build();
BookEntity saved = bookRepository.saveAndFlush(book);
assertThat(saved.getId()).isNotNull();
assertThat(bookRepository.findByIdWithBookFiles(saved.getId())).isPresent();
}
}
@Nested
class FindAllWithPathsQuery {
/**
* Verify findAllWithPaths EntityGraph loads paths for all libraries.
*/
@Test
void findAllWithPaths_loadsPathsForAllLibraries() {
LibraryEntity lib1 = LibraryEntity.builder().name("Lib1").icon("a").watch(false).build();
entityManager.persist(lib1);
LibraryPathEntity path1 = LibraryPathEntity.builder().library(lib1).path("/lib1").build();
entityManager.persist(path1);
LibraryEntity lib2 = LibraryEntity.builder().name("Lib2").icon("b").watch(false).build();
entityManager.persist(lib2);
LibraryPathEntity path2 = LibraryPathEntity.builder().library(lib2).path("/lib2").build();
entityManager.persist(path2);
entityManager.flush();
entityManager.clear();
List<LibraryEntity> libraries = libraryRepository.findAllWithPaths();
assertThat(libraries).hasSizeGreaterThanOrEqualTo(2);
for (LibraryEntity lib : libraries) {
entityManager.detach(lib);
assertThat(lib.getLibraryPaths()).isNotEmpty();
}
}
}
@Nested
class MetadataDescriptionAccess {
private LibraryEntity library;
private LibraryPathEntity libraryPath;
@BeforeEach
void setUp() {
library = LibraryEntity.builder()
.name("Description Test Library")
.icon("book")
.watch(false)
.build();
entityManager.persist(library);
libraryPath = LibraryPathEntity.builder()
.library(library)
.path("/test/books")
.build();
entityManager.persist(libraryPath);
entityManager.flush();
}
/**
* Regression: BookMetadataEntity.description must be accessible after detaching.
* Previously, description was @Basic(fetch=LAZY) which caused
* LazyInitializationException in MetadataChangeDetector and OPDS feeds.
*/
@Test
void descriptionIsAccessibleOnDetachedEntity() {
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(libraryPath)
.addedOn(Instant.now())
.deleted(false)
.build();
BookMetadataEntity metadata = BookMetadataEntity.builder()
.book(book)
.title("Description Test Book")
.description("A long description of this book for testing purposes.")
.build();
book.setMetadata(metadata);
entityManager.persist(book);
entityManager.flush();
entityManager.clear();
BookEntity loaded = bookRepository.findAllWithMetadataByIds(
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
entityManager.detach(loaded);
assertThat(loaded.getMetadata().getDescription())
.isEqualTo("A long description of this book for testing purposes.");
}
/**
* Regression: findAllWithMetadataByIds EntityGraph must load description
* so that MetadataChangeDetector.isDifferent() can compare it.
*/
@Test
void findAllWithMetadataByIds_loadsDescriptionEagerly() {
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(libraryPath)
.addedOn(Instant.now())
.deleted(false)
.build();
BookMetadataEntity metadata = BookMetadataEntity.builder()
.book(book)
.title("Metadata Load Test")
.description("Detailed plot summary here.")
.build();
book.setMetadata(metadata);
entityManager.persist(book);
entityManager.flush();
entityManager.clear();
List<BookEntity> books = bookRepository.findAllWithMetadataByIds(
Collections.singleton(book.getId()));
assertThat(books).hasSize(1);
entityManager.detach(books.get(0));
assertThat(books.get(0).getMetadata().getDescription())
.isEqualTo("Detailed plot summary here.");
assertThat(books.get(0).getMetadata().getTitle())
.isEqualTo("Metadata Load Test");
}
/**
* Verify embeddingVector and searchText remain lazy and are NOT loaded
* by default EntityGraphs, but ARE accessible within a session.
*/
@Test
void lazyFieldsAccessibleWithinSession() {
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(libraryPath)
.addedOn(Instant.now())
.deleted(false)
.build();
BookMetadataEntity metadata = BookMetadataEntity.builder()
.book(book)
.title("Lazy Fields Test")
.embeddingVector("[0.1, 0.2, 0.3]")
.build();
book.setMetadata(metadata);
entityManager.persist(book);
entityManager.flush();
entityManager.clear();
BookEntity loaded = bookRepository.findByIdWithMetadata(book.getId()).orElseThrow();
assertThat(loaded.getMetadata().getEmbeddingVector()).isEqualTo("[0.1, 0.2, 0.3]");
assertThat(loaded.getMetadata().getSearchText()).isNotNull();
}
}
@Nested
class CategoryMappingIntegrity {
private LibraryEntity library;
private LibraryPathEntity libraryPath;
@BeforeEach
void setUp() {
library = LibraryEntity.builder()
.name("Category Test Library")
.icon("book")
.watch(false)
.build();
entityManager.persist(library);
libraryPath = LibraryPathEntity.builder()
.library(library)
.path("/test/books")
.build();
entityManager.persist(libraryPath);
entityManager.flush();
}
/**
* Regression: Saving a book with categories must not produce duplicate
* entries in book_metadata_category_mapping. The old double-save pattern
* (service saves, then controller saves again) caused duplicate key errors.
*/
@Test
void categoryMappings_noDuplicatesAfterSave() {
CategoryEntity cat1 = CategoryEntity.builder().name("Fiction").build();
CategoryEntity cat2 = CategoryEntity.builder().name("Science").build();
entityManager.persist(cat1);
entityManager.persist(cat2);
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(libraryPath)
.addedOn(Instant.now())
.deleted(false)
.build();
BookMetadataEntity metadata = BookMetadataEntity.builder()
.book(book)
.title("Category Test Book")
.categories(new HashSet<>(Set.of(cat1, cat2)))
.build();
book.setMetadata(metadata);
entityManager.persist(book);
entityManager.flush();
entityManager.clear();
// Verify categories persisted correctly
BookEntity loaded = bookRepository.findAllWithMetadataByIds(
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
assertThat(loaded.getMetadata().getCategories()).hasSize(2);
assertThat(loaded.getMetadata().getCategories().stream()
.map(CategoryEntity::getName)
.collect(Collectors.toSet()))
.containsExactlyInAnyOrder("Fiction", "Science");
Long mappingCount = entityManager.createQuery(
"SELECT COUNT(1) FROM BookMetadataEntity m JOIN m.categories c WHERE m.book.id = :bookId", Long.class)
.setParameter("bookId", book.getId())
.getSingleResult();
assertThat(mappingCount).isEqualTo(2L);
}
/**
* Updating categories on a managed entity should replace correctly
* without duplicate key violations.
*/
@Test
void updateCategories_replacesWithoutDuplicates() {
CategoryEntity cat1 = CategoryEntity.builder().name("OldCat1").build();
CategoryEntity cat2 = CategoryEntity.builder().name("OldCat2").build();
CategoryEntity cat3 = CategoryEntity.builder().name("NewCat3").build();
entityManager.persist(cat1);
entityManager.persist(cat2);
entityManager.persist(cat3);
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(libraryPath)
.addedOn(Instant.now())
.deleted(false)
.build();
BookMetadataEntity metadata = BookMetadataEntity.builder()
.book(book)
.title("Update Category Test")
.categories(new HashSet<>(Set.of(cat1, cat2)))
.build();
book.setMetadata(metadata);
entityManager.persist(book);
entityManager.flush();
entityManager.clear();
BookEntity loaded = bookRepository.findAllWithMetadataByIds(
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
CategoryEntity managedCat2 = entityManager.find(CategoryEntity.class, cat2.getId());
CategoryEntity managedCat3 = entityManager.find(CategoryEntity.class, cat3.getId());
loaded.getMetadata().getCategories().clear();
loaded.getMetadata().getCategories().add(managedCat2);
loaded.getMetadata().getCategories().add(managedCat3);
entityManager.flush();
entityManager.clear();
BookEntity reloaded = bookRepository.findAllWithMetadataByIds(
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
assertThat(reloaded.getMetadata().getCategories()).hasSize(2);
assertThat(reloaded.getMetadata().getCategories().stream()
.map(CategoryEntity::getName)
.collect(Collectors.toSet()))
.containsExactlyInAnyOrder("OldCat2", "NewCat3");
}
}
@Nested
class EmbeddingBatchProcessing {
private LibraryEntity library;
private LibraryPathEntity libraryPath;
@BeforeEach
void setUp() {
library = LibraryEntity.builder()
.name("Embedding Test Library")
.icon("book")
.watch(false)
.build();
entityManager.persist(library);
libraryPath = LibraryPathEntity.builder()
.library(library)
.path("/test/books")
.build();
entityManager.persist(libraryPath);
entityManager.flush();
}
/**
* Regression: findAllFullBooksBatch must load metadata.authors and
* metadata.categories eagerly (via Hibernate.initialize) so they are
* accessible on detached entities for embedding computation.
*/
@Test
void findAllFullBooksBatch_initializesLazyCollections() {
CategoryEntity cat = CategoryEntity.builder().name("TestCat").build();
entityManager.persist(cat);
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(libraryPath)
.addedOn(Instant.now())
.deleted(false)
.build();
BookMetadataEntity metadata = BookMetadataEntity.builder()
.book(book)
.title("Batch Test Book")
.categories(new HashSet<>(Set.of(cat)))
.build();
book.setMetadata(metadata);
entityManager.persist(book);
entityManager.flush();
entityManager.clear();
List<BookEntity> batch = bookRepository.findAllFullBooksBatch(
PageRequest.of(0, 100));
assertThat(batch).isNotEmpty();
BookEntity loaded = batch.stream()
.filter(b -> b.getId().equals(book.getId()))
.findFirst()
.orElseThrow();
assertThat(loaded.getMetadata().getCategories()).hasSize(1);
assertThat(loaded.getMetadata().getTitle()).isEqualTo("Batch Test Book");
}
/**
* Verify embedding vector can be compared and updated within a session.
*/
@Test
void embeddingVector_comparableAndUpdatableInSession() {
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(libraryPath)
.addedOn(Instant.now())
.deleted(false)
.build();
BookMetadataEntity metadata = BookMetadataEntity.builder()
.book(book)
.title("Embedding Update Test")
.embeddingVector("[0.1, 0.2]")
.build();
book.setMetadata(metadata);
entityManager.persist(book);
entityManager.flush();
entityManager.clear();
BookEntity loaded = bookRepository.findAllWithMetadataByIds(
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
String oldEmbedding = loaded.getMetadata().getEmbeddingVector();
assertThat(oldEmbedding).isEqualTo("[0.1, 0.2]");
loaded.getMetadata().setEmbeddingVector("[0.3, 0.4]");
loaded.getMetadata().setEmbeddingUpdatedAt(Instant.now());
entityManager.flush();
entityManager.clear();
BookEntity reloaded = bookRepository.findByIdWithMetadata(book.getId()).orElseThrow();
assertThat(reloaded.getMetadata().getEmbeddingVector()).isEqualTo("[0.3, 0.4]");
}
}
}
@@ -22,6 +22,8 @@ import java.util.Optional;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.*;
@@ -68,7 +70,15 @@ class BookCreatorServiceTest {
void addAuthorsToBook_givenNullOrEmptySet_doesNothing(Set<String> authors) {
bookCreatorService.addAuthorsToBook(authors, bookEntity);
assertThat(bookEntity.getMetadata().getAuthors()).isNull();
assertTrue(bookEntity.getMetadata().getAuthors().isEmpty());
verifyNoInteractions(authorRepository);
}
@Test
void addAuthorsToBook_emptyAuthors_doesNothing() {
bookCreatorService.addAuthorsToBook(Set.of(), bookEntity);
assertTrue(bookEntity.getMetadata().getAuthors().isEmpty());
verifyNoInteractions(authorRepository);
}
@@ -84,12 +94,32 @@ class BookCreatorServiceTest {
.containsExactly("Test Author");
}
@ParameterizedTest
@NullAndEmptySource
void addCategoriesToBook_givenNullOrEmptySet_doesNothing(Set<String> categories) {
bookCreatorService.addCategoriesToBook(categories, bookEntity);
@Test
void addAuthorsToBook_nullExistingAuthorsOnEntity_initializesSet() {
assertTrue(bookEntity.getMetadata().getAuthors().isEmpty());
assertThat(bookEntity.getMetadata().getCategories()).isNull();
AuthorEntity author = AuthorEntity.builder().name("Author").build();
when(authorRepository.findByName("Author")).thenReturn(Optional.of(author));
bookCreatorService.addAuthorsToBook(Set.of("Author"), bookEntity);
assertNotNull(bookEntity.getMetadata().getAuthors());
assertTrue(bookEntity.getMetadata().getAuthors().contains(author));
}
@Test
void addCategoriesToBook_nullCategories_doesNothing() {
bookCreatorService.addCategoriesToBook(null, bookEntity);
assertTrue(bookEntity.getMetadata().getCategories().isEmpty());
verifyNoInteractions(categoryRepository);
}
@Test
void addCategoriesToBook_emptyCategories_doesNothing() {
bookCreatorService.addCategoriesToBook(Set.of(), bookEntity);
assertTrue(bookEntity.getMetadata().getCategories().isEmpty());
verifyNoInteractions(categoryRepository);
}
@@ -110,7 +140,15 @@ class BookCreatorServiceTest {
void addMoodsToBook_givenNullOrEmptySet_doesNothing(Set<String> moods) {
bookCreatorService.addMoodsToBook(moods, bookEntity);
assertThat(bookEntity.getMetadata().getMoods()).isNull();
assertTrue(bookEntity.getMetadata().getMoods().isEmpty());
verifyNoInteractions(moodRepository);
}
@Test
void addMoodsToBook_emptyMoods_doesNothing() {
bookCreatorService.addMoodsToBook(Set.of(), bookEntity);
assertTrue(bookEntity.getMetadata().getMoods().isEmpty());
verifyNoInteractions(moodRepository);
}
@@ -131,7 +169,23 @@ class BookCreatorServiceTest {
void addTagsToBook_givenNullOrEmptySet_doesNothing(Set<String> tags) {
bookCreatorService.addTagsToBook(tags, bookEntity);
assertThat(bookEntity.getMetadata().getTags()).isNull();
assertTrue(bookEntity.getMetadata().getTags().isEmpty());
verifyNoInteractions(tagRepository);
}
@Test
void addTagsToBook_nullTags_doesNothing() {
bookCreatorService.addTagsToBook(null, bookEntity);
assertTrue(bookEntity.getMetadata().getTags().isEmpty());
verifyNoInteractions(tagRepository);
}
@Test
void addTagsToBook_emptyTags_doesNothing() {
bookCreatorService.addTagsToBook(Set.of(), bookEntity);
assertTrue(bookEntity.getMetadata().getTags().isEmpty());
verifyNoInteractions(tagRepository);
}
@@ -172,7 +226,7 @@ class BookCreatorServiceTest {
bookCreatorService.addAuthorsToBook(Set.of("Brand New"), bookEntity);
verify(authorRepository).save(argThat(author -> "Brand New".equals(author.getName())));
assertThat(bookEntity.getMetadata().getAuthors())
.isNotNull()
.extracting(AuthorEntity::getName)
@@ -99,6 +99,7 @@ class BookFileAttachmentServiceTest {
Files.createDirectories(dir);
Files.createFile(dir.resolve(fileName));
book.getBookFiles().add(file);
return file;
}
@@ -113,6 +114,7 @@ class BookFileAttachmentServiceTest {
.folderBased(false)
.bookType(BookFileType.EPUB)
.build();
book.getBookFiles().add(file);
return file;
}
@@ -791,6 +793,7 @@ class BookFileAttachmentServiceTest {
Path sourceDir = tempDir.resolve("other_root/source_dir");
Files.createDirectories(sourceDir);
Files.createFile(sourceDir.resolve("source.pdf"));
source.getBookFiles().add(sourceFile);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
@@ -822,6 +825,7 @@ class BookFileAttachmentServiceTest {
.build();
Files.createDirectories(tempDir.resolve("source_dir"));
Files.createFile(tempDir.resolve("source_dir/noextension"));
source.getBookFiles().add(sourceFile);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
@@ -86,6 +86,7 @@ class BookFileDetachmentServiceTest {
.isBookFormat(isBookFormat)
.bookType(type)
.build();
book.getBookFiles().add(file);
return file;
}
@@ -123,7 +124,6 @@ class BookFileDetachmentServiceTest {
assertThat(book.getBookFiles().getFirst().getId()).isEqualTo(10L);
verify(auditService).log(eq(org.booklore.model.enums.AuditAction.BOOK_FILE_DETACHED), anyString(), eq(1L), anyString());
verify(bookRepository).saveAndFlush(argThat(newBook -> {
assertThat(newBook.getBookFiles()).hasSize(1);
assertThat(newBook.getMetadata().getTitle()).isEqualTo("Test Book 1");
return true;
}));
@@ -173,11 +173,9 @@ class BookFileDetachmentServiceTest {
service.detachBookFile(1L, 11L, false);
assertThat(book.getBookFiles()).hasSize(1);
verify(bookRepository).saveAndFlush(argThat(newBook -> {
assertThat(newBook.getBookFiles()).hasSize(1);
assertThat(newBook.getBookFiles().getFirst().getFileName()).isEqualTo("notes.txt");
return true;
}));
assertThat(suppFile.getBook()).isNotSameAs(book);
assertThat(suppFile.getFileName()).isEqualTo("notes.txt");
verify(bookRepository).saveAndFlush(any(BookEntity.class));
}
@Test
@@ -281,8 +279,8 @@ class BookFileDetachmentServiceTest {
verify(bookRepository).saveAndFlush(argThat(newBook -> {
assertThat(newBook.getLibraryPath().getId()).isEqualTo(2L);
assertThat(newBook.getBookFiles().getFirst().getFileSubPath()).isEmpty();
return true;
}));
assertThat(altFile.getFileSubPath()).isEmpty();
}
}
@@ -41,6 +41,8 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import tools.jackson.databind.ObjectMapper;
import java.io.IOException;
@@ -87,6 +89,8 @@ class BookDropServiceTest {
private FileMovingHelper fileMovingHelper;
@Mock
private KoboAutoShelfService koboAutoShelfService;
@Mock
private PlatformTransactionManager transactionManager;
@InjectMocks
private BookDropService bookDropService;
@@ -122,6 +126,9 @@ class BookDropServiceTest {
bookdropFile.setFileName("test-book.pdf");
Files.createFile(tempDir.resolve("test-book.pdf"));
TransactionStatus txStatus = mock(TransactionStatus.class);
lenient().when(transactionManager.getTransaction(any())).thenReturn(txStatus);
}
@AfterEach
@@ -72,11 +72,11 @@ class KoboLibrarySnapshotServiceTest {
otherUser = BookLoreUserEntity.builder().id(2L).isDefaultPassword(false).build();
LibraryEntity ownersLibrary = LibraryEntity.builder()
.users(List.of(owner))
.users(Set.of(owner))
.build();
LibraryEntity othersLibrary = LibraryEntity.builder()
.users(List.of(otherUser))
.users(Set.of(otherUser))
.build();
ownersBook = BookEntity.builder()
@@ -102,12 +102,11 @@ class KomgaServiceTest {
@Test
void shouldReturnAllBooksWhenUnpagedIsTrue() {
// Given
when(bookRepository.findAllWithMetadataByLibraryId(anyLong())).thenReturn(seriesBooks);
// Mock mapper.getBookSeriesName to return "test-series" for all books
for (BookEntity book : seriesBooks) {
when(komgaMapper.getBookSeriesName(book)).thenReturn("test-series");
}
when(komgaMapper.getUnknownSeriesName()).thenReturn("Unknown Series");
when(bookRepository.findDistinctSeriesNamesGroupedByLibraryId(1L, "Unknown Series"))
.thenReturn(List.of("Test Series"));
when(bookRepository.findBooksBySeriesNameGroupedByLibraryId("Test Series", 1L, "Unknown Series"))
.thenReturn(seriesBooks);
// Mock the mapper to return DTOs
for (BookEntity book : seriesBooks) {
@@ -133,12 +132,11 @@ class KomgaServiceTest {
@Test
void shouldReturnPagedBooksWhenUnpagedIsFalse() {
// Given
when(bookRepository.findAllWithMetadataByLibraryId(anyLong())).thenReturn(seriesBooks);
// Mock mapper.getBookSeriesName to return "test-series" for all books
for (BookEntity book : seriesBooks) {
when(komgaMapper.getBookSeriesName(book)).thenReturn("test-series");
}
when(komgaMapper.getUnknownSeriesName()).thenReturn("Unknown Series");
when(bookRepository.findDistinctSeriesNamesGroupedByLibraryId(1L, "Unknown Series"))
.thenReturn(List.of("Test Series"));
when(bookRepository.findBooksBySeriesNameGroupedByLibraryId("Test Series", 1L, "Unknown Series"))
.thenReturn(seriesBooks);
// Mock the mapper to return DTOs (only for the books that will be used)
for (int i = 0; i < 20; i++) {
@@ -6,6 +6,7 @@ import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.repository.BookAdditionalFileRepository;
import org.booklore.repository.BookRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.NotificationService;
import org.booklore.task.options.RescanLibraryContext;
@@ -32,6 +33,8 @@ class LibraryProcessingServiceRegressionTest {
@Mock
private LibraryRepository libraryRepository;
@Mock
private BookRepository bookRepository;
@Mock
private NotificationService notificationService;
@Mock
private BookAdditionalFileRepository bookAdditionalFileRepository;
@@ -54,6 +57,7 @@ class LibraryProcessingServiceRegressionTest {
void setUp() {
libraryProcessingService = new LibraryProcessingService(
libraryRepository,
bookRepository,
notificationService,
bookAdditionalFileRepository,
fileAsBookProcessor,
@@ -88,7 +92,8 @@ class LibraryProcessingServiceRegressionTest {
libraryEntity.setBookEntities(List.of(filelessBook));
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(filelessBook));
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(
LibraryFile.builder()
.libraryPathEntity(pathEntity)
@@ -8,6 +8,7 @@ import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.repository.BookAdditionalFileRepository;
import org.booklore.repository.BookRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.NotificationService;
import org.booklore.task.options.RescanLibraryContext;
@@ -35,6 +36,8 @@ class LibraryProcessingServiceTest {
@Mock
private LibraryRepository libraryRepository;
@Mock
private BookRepository bookRepository;
@Mock
private NotificationService notificationService;
@Mock
private BookAdditionalFileRepository bookAdditionalFileRepository;
@@ -57,6 +60,7 @@ class LibraryProcessingServiceTest {
void setUp() {
libraryProcessingService = new LibraryProcessingService(
libraryRepository,
bookRepository,
notificationService,
bookAdditionalFileRepository,
fileAsBookProcessor,
@@ -89,6 +93,7 @@ class LibraryProcessingServiceTest {
libraryEntity.setBookEntities(List.of(existingBook));
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
LibraryFile existingFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
@@ -150,6 +155,7 @@ class LibraryProcessingServiceTest {
libraryEntity.setBookEntities(List.of(existingBook));
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
LibraryFile existingFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
@@ -183,6 +189,7 @@ class LibraryProcessingServiceTest {
pathEntity.setPath("/library");
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
LibraryFile newFile1 = LibraryFile.builder()
.libraryEntity(libraryEntity)
@@ -230,6 +237,7 @@ class LibraryProcessingServiceTest {
pathEntity.setPath("/library");
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
LibraryFile newFileInSub = LibraryFile.builder()
.libraryEntity(libraryEntity)
@@ -274,6 +282,7 @@ class LibraryProcessingServiceTest {
pathEntity.setPath("/library");
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
LibraryFile additionalFileAsLibraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
@@ -346,7 +355,8 @@ class LibraryProcessingServiceTest {
book.setBookFiles(List.of(epub, pdf, image));
libraryEntity.setBookEntities(List.of(book));
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(book));
// Only epub exists on disk, pdf was removed
LibraryFile epubOnDisk = LibraryFile.builder()
@@ -385,7 +395,7 @@ class LibraryProcessingServiceTest {
libraryEntity.setLibraryPaths(List.of(pathEntity));
libraryEntity.setBookEntities(Collections.emptyList());
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
@@ -422,7 +432,8 @@ class LibraryProcessingServiceTest {
existingBook.getPrimaryBookFile().setFileName("book1.epub");
libraryEntity.setBookEntities(List.of(existingBook));
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList());
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
@@ -467,11 +478,12 @@ class LibraryProcessingServiceTest {
.fileName("book1.epub")
.build();
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(fileOnDisk));
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity)))
when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class)))
.thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap()));
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
@@ -497,11 +509,12 @@ class LibraryProcessingServiceTest {
libraryEntity.setLibraryPaths(List.of(pathEntity));
libraryEntity.setBookEntities(Collections.emptyList());
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList());
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity)))
when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class)))
.thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap()));
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
@@ -551,9 +564,12 @@ class LibraryProcessingServiceTest {
.fileName("book (with parens).epub")
.build();
when(libraryRepository.findByIdWithBooks(libraryId))
when(libraryRepository.findByIdWithPaths(libraryId))
.thenReturn(Optional.of(libraryEntity))
.thenReturn(Optional.of(freshLibraryEntity)); // Second call returns fresh entity
when(bookRepository.findAllByLibraryIdForRescan(libraryId))
.thenReturn(new ArrayList<>(List.of(existingBook)))
.thenReturn(new ArrayList<>(List.of(existingBook)));
when(libraryFileHelper.getAllLibraryFiles(any(LibraryEntity.class))).thenReturn(List.of(fileOnDisk));
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
@@ -564,7 +580,8 @@ class LibraryProcessingServiceTest {
libraryProcessingService.rescanLibrary(context);
verify(libraryRepository, times(2)).findByIdWithBooks(libraryId);
verify(libraryRepository, times(2)).findByIdWithPaths(libraryId);
verify(bookRepository, times(2)).findAllByLibraryIdForRescan(libraryId);
verify(bookGroupingService).groupForRescan(eq(Collections.emptyList()), any(LibraryEntity.class));
}
@@ -68,7 +68,7 @@ class LibraryFileEventProcessorTest {
.organizationMode(LibraryOrganizationMode.AUTO_DETECT)
.build();
when(libraryRepository.findById(1L)).thenReturn(Optional.of(library));
when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(library));
when(bookFilePersistenceService.findMatchingLibraryPath(eq(library), any(Path.class)))
.thenReturn(tempDir.toString());
when(bookFilePersistenceService.getLibraryPathEntityForFile(eq(library), eq(tempDir.toString())))
@@ -2,6 +2,7 @@ package org.booklore.task.tasks;
import org.booklore.exception.APIException;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.BookRecommendationLite;
import org.booklore.model.dto.request.TaskCreateRequest;
import org.booklore.model.dto.response.TaskCreateResponse;
import org.booklore.model.entity.BookEntity;
@@ -15,13 +16,13 @@ import org.booklore.task.TaskStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
@@ -40,6 +41,9 @@ class BookRecommendationUpdaterTaskTest {
@InjectMocks
private BookRecommendationUpdaterTask task;
@Captor
private ArgumentCaptor<Map<Long, Set<BookRecommendationLite>>> recommendationsCaptor;
private BookLoreUser user;
private TaskCreateRequest request;
@@ -60,13 +64,15 @@ class BookRecommendationUpdaterTaskTest {
@Test
void execute_shouldHandleEmptyBookList() {
when(bookQueryService.getAllFullBookEntities()).thenReturn(Collections.emptyList());
when(bookQueryService.countAllNonDeleted()).thenReturn(0L);
when(bookQueryService.getAllFullBookEntitiesBatch(any())).thenReturn(Collections.emptyList());
TaskCreateResponse response = task.execute(request);
assertEquals(TaskType.UPDATE_BOOK_RECOMMENDATIONS, response.getTaskType());
verify(bookQueryService).getAllFullBookEntities();
verify(bookQueryService).saveAll(anyList()); // Should be called with empty list
verify(bookQueryService).countAllNonDeleted();
verify(bookQueryService).getAllFullBookEntitiesBatch(any());
verify(bookQueryService).saveRecommendationsInBatches(eq(Collections.emptyMap()), anyInt());
verify(notificationService, atLeastOnce()).sendMessage(eq(Topic.TASK_PROGRESS), any());
}
@@ -76,32 +82,41 @@ class BookRecommendationUpdaterTaskTest {
BookEntity book2 = BookEntity.builder().id(2L).metadata(BookMetadataEntity.builder().title("B2").build()).build();
List<BookEntity> books = List.of(book1, book2);
when(bookQueryService.getAllFullBookEntities()).thenReturn(books);
when(bookQueryService.countAllNonDeleted()).thenReturn(2L);
when(bookQueryService.getAllFullBookEntitiesBatch(any())).thenReturn(books).thenReturn(Collections.emptyList());
when(vectorService.generateEmbedding(any())).thenReturn(new double[]{0.1, 0.2});
when(vectorService.serializeVector(any())).thenReturn("[0.1, 0.2]");
// Lenient stubs for similarity calculations
lenient().when(vectorService.cosineSimilarity(any(), any())).thenReturn(0.9);
lenient().when(vectorService.findTopKSimilar(any(), anyList(), anyInt())).thenReturn(new ArrayList<>());
when(vectorService.cosineSimilarity(any(), any())).thenReturn(0.9);
when(vectorService.findTopKSimilar(any(), anyList(), anyInt())).thenAnswer(invocation -> {
List<BookVectorService.ScoredBook> candidates = invocation.getArgument(1);
return candidates.isEmpty() ? new ArrayList<>() : List.of(candidates.getFirst());
});
TaskCreateResponse response = task.execute(request);
assertEquals("task-123", response.getTaskId());
assertEquals(TaskStatus.COMPLETED, response.getStatus());
org.mockito.ArgumentCaptor<List<BookEntity>> captor = org.mockito.ArgumentCaptor.forClass(List.class);
verify(bookQueryService).saveAll(captor.capture());
List<BookEntity> savedBooks = captor.getValue();
assertEquals(2, savedBooks.size());
// Verify embeddings were set
assertNotNull(savedBooks.get(0).getMetadata().getEmbeddingVector());
verify(bookQueryService).compareAndSaveEmbeddings(any());
verify(vectorService, times(2)).generateEmbedding(any());
verify(bookQueryService).saveRecommendationsInBatches(recommendationsCaptor.capture(), anyInt());
Map<Long, Set<BookRecommendationLite>> recommendations = recommendationsCaptor.getValue();
assertNotNull(recommendations);
assertEquals(2, recommendations.size(), "Should have recommendations for both books");
assertTrue(recommendations.containsKey(1L), "Should have recommendations for book 1");
assertTrue(recommendations.containsKey(2L), "Should have recommendations for book 2");
// Each book should recommend the other
recommendations.values().forEach(recs ->
assertFalse(recs.isEmpty(), "Each book should have at least one recommendation"));
}
@Test
void execute_shouldFail_whenEmbeddingGenerationThrows() {
BookEntity book1 = BookEntity.builder().id(1L).build();
when(bookQueryService.getAllFullBookEntities()).thenReturn(List.of(book1));
BookEntity book1 = BookEntity.builder().id(1L).metadata(BookMetadataEntity.builder().title("B1").build()).build();
when(bookQueryService.countAllNonDeleted()).thenReturn(1L);
when(bookQueryService.getAllFullBookEntitiesBatch(any())).thenReturn(List.of(book1));
when(vectorService.generateEmbedding(any())).thenThrow(new RuntimeException("Embedding failed"));
assertThrows(RuntimeException.class, () -> task.execute(request));
@@ -113,18 +128,15 @@ class BookRecommendationUpdaterTaskTest {
BookEntity book2 = BookEntity.builder().id(2L).metadata(BookMetadataEntity.builder().title("B2").build()).build();
List<BookEntity> books = List.of(book1, book2);
when(bookQueryService.getAllFullBookEntities()).thenReturn(books);
when(bookQueryService.countAllNonDeleted()).thenReturn(2L);
when(bookQueryService.getAllFullBookEntitiesBatch(any())).thenReturn(books).thenReturn(Collections.emptyList());
when(vectorService.generateEmbedding(any())).thenReturn(new double[]{0.1});
when(vectorService.serializeVector(any())).thenReturn("[0.1]");
// Mock similarity to throw for first book, pass for second (actually it iterates as target)
// target=book1, candidate=book2.
when(vectorService.cosineSimilarity(any(), any())).thenThrow(new RuntimeException("Math error"));
TaskCreateResponse response = task.execute(request);
assertEquals(TaskStatus.COMPLETED, response.getStatus());
// Should still try to save updates (even if empty list added)
verify(bookQueryService).saveAll(anyList());
verify(bookQueryService).saveRecommendationsInBatches(any(Map.class), anyInt());
}
}
@@ -11,6 +11,10 @@ spring:
properties:
hibernate:
format_sql: true
query:
fail_on_pagination_over_collection_fetch: true
connection:
provider_disables_autocommit: false
flyway:
enabled: false
app: