refactor(entity): update fetch strategies to LAZY for improved relibility (#122)

This commit is contained in:
brios
2026-04-22 17:26:32 -04:00
committed by Zach Yale
parent 21c23d61fb
commit b905e825f3
111 changed files with 1204 additions and 849 deletions
@@ -1,5 +1,6 @@
package org.booklore.service;
import jakarta.persistence.EntityNotFoundException;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.mapper.BookReviewMapper;
import org.booklore.model.dto.BookLoreUser;
@@ -17,7 +18,6 @@ import org.booklore.service.appsettings.AppSettingService;
import org.booklore.service.book.BookReviewService;
import org.booklore.service.metadata.BookReviewUpdateService;
import org.booklore.service.metadata.MetadataRefreshService;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -122,7 +122,7 @@ class BookReviewServiceTest {
AppSettings appSettings = new AppSettings();
appSettings.setMetadataPublicReviewsSettings(createReviewSettings(true));
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithMetadata(bookId)).thenReturn(Optional.of(bookEntity));
when(bookReviewRepository.findByBookMetadataBookId(bookId))
.thenReturn(Collections.singletonList(entity));
when(mapper.toDto(entity)).thenReturn(dto);
@@ -142,7 +142,7 @@ class BookReviewServiceTest {
AppSettings appSettings = new AppSettings();
appSettings.setMetadataPublicReviewsSettings(createReviewSettings(false));
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithMetadata(bookId)).thenReturn(Optional.of(bookEntity));
when(bookReviewRepository.findByBookMetadataBookId(bookId))
.thenReturn(Collections.emptyList());
when(appSettingService.getAppSettings()).thenReturn(appSettings);
@@ -161,7 +161,7 @@ class BookReviewServiceTest {
appSettings.setMetadataPublicReviewsSettings(createReviewSettings(true, MetadataProvider.Amazon));
BookLoreUser user = createUser(false, false);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithMetadata(bookId)).thenReturn(Optional.of(bookEntity));
when(bookReviewRepository.findByBookMetadataBookId(bookId))
.thenReturn(Collections.emptyList());
when(appSettingService.getAppSettings()).thenReturn(appSettings);
@@ -189,7 +189,7 @@ class BookReviewServiceTest {
.thenReturn(Collections.singletonList(savedEntity));
when(appSettingService.getAppSettings()).thenReturn(appSettings);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithMetadata(bookId)).thenReturn(Optional.of(bookEntity));
when(mapper.toDto(savedEntity)).thenReturn(freshReview);
Map<MetadataProvider, BookMetadata> metadataMap = new EnumMap<>(MetadataProvider.class);
@@ -225,7 +225,7 @@ class BookReviewServiceTest {
.thenReturn(Collections.singletonList(savedEntity));
when(appSettingService.getAppSettings()).thenReturn(appSettings);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithMetadata(bookId)).thenReturn(Optional.of(bookEntity));
when(mapper.toDto(savedEntity)).thenReturn(freshReview);
Map<MetadataProvider, BookMetadata> metadataMap = new EnumMap<>(MetadataProvider.class);
@@ -247,7 +247,7 @@ class BookReviewServiceTest {
void getByBookId_throwsException_whenBookNotFound() {
Long bookId = 1L;
when(bookRepository.findById(bookId)).thenReturn(Optional.empty());
when(bookRepository.findByIdWithMetadata(bookId)).thenReturn(Optional.empty());
RuntimeException exception = assertThrows(RuntimeException.class,
() -> service.getByBookId(bookId));
@@ -76,7 +76,7 @@ class OpdsBookServiceTest {
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
when(userRepository.findById(userId)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(userId)).thenReturn(Optional.of(entity));
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
when(user.getPermissions()).thenReturn(perms);
when(perms.isAdmin()).thenReturn(isAdmin);
@@ -102,7 +102,7 @@ class OpdsBookServiceTest {
void getAccessibleLibraries_returnsAssignedLibraries_forNonAdmin() {
OpdsUserDetails details = v2UserDetails(1L, false, Set.of(2L, 3L));
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -135,7 +135,7 @@ class OpdsBookServiceTest {
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(999L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(999L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -150,7 +150,7 @@ class OpdsBookServiceTest {
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
when(shelfUser.getId()).thenReturn(999L);
when(shelf.getUser()).thenReturn(shelfUser);
when(shelfRepository.findById(2L)).thenReturn(Optional.of(shelf));
when(shelfRepository.findByIdWithUser(2L)).thenReturn(Optional.of(shelf));
when(bookOpdsRepository.findBookIds(any())).thenReturn(Page.empty());
when(bookOpdsRepository.findRecentBookIds(any())).thenReturn(Page.empty());
@@ -194,7 +194,7 @@ class OpdsBookServiceTest {
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(true);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
@@ -206,7 +206,7 @@ class OpdsBookServiceTest {
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
when(shelfUser.getId()).thenReturn(1L);
when(shelf.getUser()).thenReturn(shelfUser);
when(shelfRepository.findById(anyLong())).thenReturn(Optional.of(shelf));
when(shelfRepository.findByIdWithUser(anyLong())).thenReturn(Optional.of(shelf));
opdsBookService.getBooksPage(details.getOpdsUserV2().getUserId(), "q", 1L, Set.of(2L), 0, 10);
}
@@ -215,7 +215,7 @@ class OpdsBookServiceTest {
void getRecentBooksPage_returnsRecentBooks_forLegacyUser() {
OpdsUserDetails details = legacyUserDetails();
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
when(userRepository.findById(999L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(999L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -232,7 +232,7 @@ class OpdsBookServiceTest {
void getRecentBooksPage_appliesBookFilters_forNonAdminV2User() {
OpdsUserDetails details = v2UserDetails(2L, false, Set.of(1L, 2L));
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
when(userRepository.findById(2L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(2L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -341,7 +341,7 @@ class OpdsBookServiceTest {
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(false);
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(entity));
assertThatThrownBy(() ->
opdsBookService.getBooksPage(1L, null, null, null, 0, 10)
@@ -356,7 +356,7 @@ class OpdsBookServiceTest {
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -371,7 +371,7 @@ class OpdsBookServiceTest {
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
when(shelfUser.getId()).thenReturn(1L);
when(shelf.getUser()).thenReturn(shelfUser);
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf));
when(shelfRepository.findByIdWithUser(10L)).thenReturn(Optional.of(shelf));
BookEntity bookEntity = mock(BookEntity.class);
when(bookEntity.getId()).thenReturn(1L);
@@ -395,7 +395,7 @@ class OpdsBookServiceTest {
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -412,8 +412,8 @@ class OpdsBookServiceTest {
when(shelfUser.getId()).thenReturn(1L);
when(shelf1.getUser()).thenReturn(shelfUser);
when(shelf2.getUser()).thenReturn(shelfUser);
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf1));
when(shelfRepository.findById(20L)).thenReturn(Optional.of(shelf2));
when(shelfRepository.findByIdWithUser(10L)).thenReturn(Optional.of(shelf1));
when(shelfRepository.findByIdWithUser(20L)).thenReturn(Optional.of(shelf2));
BookEntity bookEntity1 = mock(BookEntity.class);
BookEntity bookEntity2 = mock(BookEntity.class);
@@ -441,7 +441,7 @@ class OpdsBookServiceTest {
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -456,7 +456,7 @@ class OpdsBookServiceTest {
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
when(shelfUser.getId()).thenReturn(1L);
when(shelf.getUser()).thenReturn(shelfUser);
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf));
when(shelfRepository.findByIdWithUser(10L)).thenReturn(Optional.of(shelf));
BookEntity bookEntity = mock(BookEntity.class);
when(bookEntity.getId()).thenReturn(1L);
@@ -480,7 +480,7 @@ class OpdsBookServiceTest {
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -495,7 +495,7 @@ class OpdsBookServiceTest {
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
when(shelfUser.getId()).thenReturn(999L); // Different user
when(shelf.getUser()).thenReturn(shelfUser);
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf));
when(shelfRepository.findByIdWithUser(10L)).thenReturn(Optional.of(shelf));
assertThatThrownBy(() ->
opdsBookService.getBooksPage(1L, null, null, Set.of(10L), 0, 10)
@@ -510,7 +510,7 @@ class OpdsBookServiceTest {
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(true);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -525,7 +525,7 @@ class OpdsBookServiceTest {
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
when(shelfUser.getId()).thenReturn(999L); // Different user, but admin
when(shelf.getUser()).thenReturn(shelfUser);
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf));
when(shelfRepository.findByIdWithUser(10L)).thenReturn(Optional.of(shelf));
when(bookOpdsRepository.findBookIdsByShelfIds(eq(Set.of(10L)), any())).thenReturn(Page.empty());
@@ -642,7 +642,7 @@ class OpdsBookServiceTest {
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -682,7 +682,7 @@ class OpdsBookServiceTest {
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(true);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -701,7 +701,7 @@ class OpdsBookServiceTest {
@Test
void getRecentBooksPage_appliesContentRestrictions_forNonAdmin() {
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
when(userRepository.findById(2L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(2L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -727,7 +727,7 @@ class OpdsBookServiceTest {
@Test
void getRecentBooksPage_skipsContentRestrictions_forAdmin() {
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -773,7 +773,7 @@ class OpdsBookServiceTest {
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(3L)).thenReturn(Optional.of(entity));
when(userRepository.findByIdWithDetails(3L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
@@ -129,7 +129,7 @@ class OpdsUserV2ServiceTest {
OpdsUserV2Entity target = mock(OpdsUserV2Entity.class);
when(target.getUser()).thenReturn(ownerEntity);
when(opdsUserV2Repository.findById(100L)).thenReturn(Optional.of(target));
when(opdsUserV2Repository.findByIdWithUser(100L)).thenReturn(Optional.of(target));
service.deleteOpdsUser(100L);
@@ -148,7 +148,7 @@ class OpdsUserV2ServiceTest {
OpdsUserV2Entity target = mock(OpdsUserV2Entity.class);
when(target.getUser()).thenReturn(ownerEntity);
when(opdsUserV2Repository.findById(200L)).thenReturn(Optional.of(target));
when(opdsUserV2Repository.findByIdWithUser(200L)).thenReturn(Optional.of(target));
assertThrows(AccessDeniedException.class, () -> service.deleteOpdsUser(200L));
verify(opdsUserV2Repository, never()).delete(any());
@@ -179,7 +179,7 @@ class OpdsUserV2ServiceTest {
BookLoreUser authUser = mock(BookLoreUser.class);
when(authenticationService.getAuthenticatedUser()).thenReturn(authUser);
when(opdsUserV2Repository.findById(300L)).thenReturn(Optional.empty());
when(opdsUserV2Repository.findByIdWithUser(300L)).thenReturn(Optional.empty());
RuntimeException ex = assertThrows(RuntimeException.class, () -> service.deleteOpdsUser(300L));
assertTrue(ex.getMessage().contains("User not found with ID: 300"));
@@ -1,7 +1,6 @@
package org.booklore.service.book;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Query;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.APIException;
import org.booklore.mapper.BookMapper;
@@ -10,6 +9,7 @@ import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.response.AttachBookFileResponse;
import org.booklore.model.entity.*;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookFileRepository;
import org.booklore.repository.BookRepository;
import org.booklore.repository.UserBookProgressRepository;
import org.booklore.service.file.FileMoveHelper;
@@ -35,6 +35,7 @@ import static org.mockito.Mockito.*;
class BookFileAttachmentServiceTest {
@Mock private BookRepository bookRepository;
@Mock private BookFileRepository bookFileRepository;
@Mock private UserBookProgressRepository userBookProgressRepository;
@Mock private AuthenticationService authenticationService;
@Mock private ReadingProgressService readingProgressService;
@@ -283,11 +284,6 @@ class BookFileAttachmentServiceTest {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
Query mockQuery = mock(Query.class);
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
when(mockQuery.executeUpdate()).thenReturn(1);
setupGetUpdatedBookMocks(1L, target);
service.attachBookFiles(1L, List.of(2L, 2L, 2L), false);
@@ -313,11 +309,6 @@ class BookFileAttachmentServiceTest {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
Query mockQuery = mock(Query.class);
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
when(mockQuery.executeUpdate()).thenReturn(1);
when(bookRepository.findAllById(List.of(2L))).thenReturn(List.of(source));
setupGetUpdatedBookMocks(1L, target);
@@ -326,7 +317,7 @@ class BookFileAttachmentServiceTest {
assertNotNull(result);
assertNotNull(result.updatedBook());
assertEquals(List.of(2L), result.deletedSourceBookIds());
verify(entityManager).createQuery(contains("UPDATE BookFileEntity"));
verify(bookFileRepository).reassignFilesToBook(eq(1L), anyList());
verify(entityManager).flush();
verify(entityManager).clear();
verify(bookRepository).deleteAll(List.of(source));
@@ -348,17 +339,12 @@ class BookFileAttachmentServiceTest {
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source1));
when(bookRepository.findByIdWithBookFiles(3L)).thenReturn(Optional.of(source2));
Query mockQuery = mock(Query.class);
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
when(mockQuery.executeUpdate()).thenReturn(1);
when(bookRepository.findAllById(anyList())).thenReturn(List.of(source1, source2));
setupGetUpdatedBookMocks(1L, target);
service.attachBookFiles(1L, List.of(2L, 3L), false);
verify(entityManager, times(2)).createQuery(contains("UPDATE BookFileEntity"));
verify(bookFileRepository, times(2)).reassignFilesToBook(eq(1L), anyList());
verify(bookRepository).deleteAll(anyList());
}
@@ -375,11 +361,6 @@ class BookFileAttachmentServiceTest {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
Query mockQuery = mock(Query.class);
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
when(mockQuery.executeUpdate()).thenReturn(1);
setupGetUpdatedBookMocks(1L, target);
service.attachBookFiles(1L, List.of(2L), false);
@@ -400,11 +381,6 @@ class BookFileAttachmentServiceTest {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
Query mockQuery = mock(Query.class);
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
when(mockQuery.executeUpdate()).thenReturn(1);
when(bookRepository.findAllById(List.of(2L))).thenReturn(List.of(source));
setupGetUpdatedBookMocks(1L, target);
@@ -679,10 +655,6 @@ class BookFileAttachmentServiceTest {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
Query mockQuery = mock(Query.class);
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
when(mockQuery.executeUpdate()).thenReturn(1);
when(bookRepository.findAllById(List.of(2L))).thenReturn(List.of(source));
BookLoreUser user = BookLoreUser.builder().id(1L).username("testuser").build();
@@ -724,11 +696,6 @@ class BookFileAttachmentServiceTest {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
Query mockQuery = mock(Query.class);
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
when(mockQuery.executeUpdate()).thenReturn(1);
setupGetUpdatedBookMocks(1L, target);
AttachBookFileResponse result = service.attachBookFiles(1L, List.of(2L), false);
@@ -751,17 +718,12 @@ class BookFileAttachmentServiceTest {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
Query mockQuery = mock(Query.class);
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
when(mockQuery.executeUpdate()).thenReturn(1);
when(bookRepository.findAllById(List.of(2L))).thenReturn(List.of(source));
setupGetUpdatedBookMocks(1L, target);
service.attachBookFiles(1L, List.of(2L), false);
verify(entityManager).createQuery(contains("UPDATE BookFileEntity"));
verify(bookFileRepository).reassignFilesToBook(eq(1L), anyList());
verify(bookRepository).deleteAll(List.of(source));
}
@@ -830,11 +792,6 @@ class BookFileAttachmentServiceTest {
Files.createDirectories(sourceDir);
Files.createFile(sourceDir.resolve("source.pdf"));
Query mockQuery = mock(Query.class);
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
when(mockQuery.executeUpdate()).thenReturn(1);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
setupGetUpdatedBookMocks(1L, target);
@@ -843,7 +800,7 @@ class BookFileAttachmentServiceTest {
assertTrue(Files.exists(sourceDir.resolve("source.pdf")),
"Source file should remain at original location");
verify(entityManager).createQuery(contains("bf.fileSubPath"));
verify(bookFileRepository).reassignFileToBookWithPath(eq(1L), anyString(), eq(20L));
assertEquals(List.of(2L), result.deletedSourceBookIds());
}
@@ -1,8 +1,9 @@
package org.booklore.service.book;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.APIException;
import org.booklore.service.audit.AuditService;
import org.booklore.mapper.BookMapper;
import org.booklore.model.dto.*;
import org.booklore.model.dto.request.ReadProgressRequest;
@@ -11,6 +12,7 @@ import org.booklore.model.dto.response.BookStatusUpdateResponse;
import org.booklore.model.entity.*;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.*;
import org.booklore.service.audit.AuditService;
import org.booklore.service.monitoring.MonitoringRegistrationService;
import org.booklore.service.progress.ReadingProgressService;
import org.booklore.util.FileService;
@@ -323,7 +325,7 @@ class BookServiceTest {
void getBookContent_returnsResource() throws Exception {
BookEntity entity = new BookEntity();
entity.setId(10L);
when(bookRepository.findById(10L)).thenReturn(Optional.of(entity));
when(bookRepository.findByIdWithBookFiles(10L)).thenReturn(Optional.of(entity));
Path path = Paths.get("/tmp/bookcontent.txt");
Files.write(path, "hello".getBytes());
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
@@ -338,7 +340,7 @@ class BookServiceTest {
@Test
void getBookContent_bookNotFound_throwsException() {
when(bookRepository.findById(404L)).thenReturn(Optional.empty());
when(bookRepository.findByIdWithBookFiles(404L)).thenReturn(Optional.empty());
assertThrows(APIException.class, () -> bookService.getBookContent(404L));
}
@@ -346,7 +348,7 @@ class BookServiceTest {
void getBookContent_fileNotFound_throwsException() {
BookEntity entity = new BookEntity();
entity.setId(12L);
when(bookRepository.findById(12L)).thenReturn(Optional.of(entity));
when(bookRepository.findByIdWithBookFiles(12L)).thenReturn(Optional.of(entity));
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn("/tmp/nonexistentfile.txt");
assertThrows(APIException.class, () -> bookService.getBookContent(12L));
@@ -440,4 +442,47 @@ class BookServiceTest {
assertEquals(1, result.size());
assertTrue(result.contains(shelf1));
}
@Mock
private org.booklore.service.FileStreamingService fileStreamingService;
@Test
void streamBookContent_delegatesToStreamingService() throws Exception {
BookEntity entity = new BookEntity();
entity.setId(15L);
BookFileEntity primaryFile = new BookFileEntity();
primaryFile.setBook(entity);
primaryFile.setBookType(BookFileType.EPUB);
primaryFile.setFileSubPath("");
primaryFile.setFileName("book.epub");
// Ensure bookFiles list is populated to avoid IndexOutOfBounds or similar if logic accesses it
entity.setBookFiles(List.of(primaryFile));
when(bookRepository.findByIdWithBookFiles(15L)).thenReturn(Optional.of(entity));
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
// We don't need to mock FileUtils static method if we set up the entity correctly
// But streamBookContent calls FileUtils.getBookFullPath(bookEntity) if bookType is null.
// Let's passed bookType="EPUB" to hit the specific branch, or null to hit default.
// The code uses:
// if (bookType != null) { ... } else { filePath = FileUtils.getBookFullPath(bookEntity); }
// Let's test the specific type path first as it isolates logic better,
// OR test the null path which is likely what the browser uses.
// The original error was "Cannot lazily initialize collection... getPrimaryBookFile... FileUtils.getBookFullPath"
// So I should test the `bookType = null` case which triggers `FileUtils.getBookFullPath`.
// However, `FileUtils.getBookFullPath` is static. I may need to mock it or ensure it works with the entity.
// `FileUtils.getBookFullPath` calls `book.getPrimaryBookFile()`.
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn("/tmp/library/book.epub");
bookService.streamBookContent(15L, null, request, response);
verify(bookRepository).findByIdWithBookFiles(15L);
verify(fileStreamingService).streamWithRangeSupport(eq(Paths.get("/tmp/library/book.epub")), eq("application/epub+zip"), eq(request), eq(response));
}
}
}
@@ -262,7 +262,7 @@ class BookDropServiceTest {
BookEntity bookEntity = new BookEntity();
bookEntity.setId(1L);
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
@@ -476,7 +476,7 @@ class BookDropServiceTest {
BookEntity bookEntity = new BookEntity();
bookEntity.setId(1L);
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.save(any())).thenAnswer(i -> i.getArguments()[0]);
@@ -594,7 +594,7 @@ class BookDropServiceTest {
BookEntity bookEntity = new BookEntity();
bookEntity.setId(1L);
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
doNothing().when(bookdropFileRepository).deleteById(any());
doNothing().when(bookdropNotificationService).sendBookdropFileSummaryNotification();
@@ -8,12 +8,12 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.web.client.RestClient;
import org.mockito.ArgumentMatchers;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@@ -80,7 +80,7 @@ class HardcoverSyncServiceTest {
hardcoverSyncSettings.setHardcoverApiKey("test-api-key");
when(hardcoverSyncSettingsService.getSettingsForUserId(TEST_USER_ID)).thenReturn(hardcoverSyncSettings);
when(bookRepository.findById(TEST_BOOK_ID)).thenReturn(Optional.of(testBook));
when(bookRepository.findByIdWithMetadata(TEST_BOOK_ID)).thenReturn(Optional.of(testBook));
// Setup RestClient mock chain - handles multiple calls
when(restClient.post()).thenReturn(requestBodyUriSpec);
@@ -133,7 +133,7 @@ class HardcoverSyncServiceTest {
@Test
@DisplayName("Should skip sync when book not found")
void syncProgressToHardcover_whenBookNotFound_shouldSkip() {
when(bookRepository.findById(TEST_BOOK_ID)).thenReturn(Optional.empty());
when(bookRepository.findByIdWithMetadata(TEST_BOOK_ID)).thenReturn(Optional.empty());
service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID);
@@ -55,7 +55,7 @@ class HardcoverSyncSettingsServiceTest {
.hardcoverSyncEnabled(true)
.build();
when(userRepository.findById(1L)).thenReturn(Optional.of(user));
when(userRepository.findByIdWithSettings(1L)).thenReturn(Optional.of(user));
when(koboUserSettingsRepository.findByUserId(1L)).thenReturn(Optional.of(legacy));
HardcoverSyncSettings settings = service.getSettingsForUserId(1L);
@@ -81,7 +81,7 @@ class HardcoverSyncSettingsServiceTest {
.settingValue("old")
.build());
when(userRepository.findById(1L)).thenReturn(Optional.of(user));
when(userRepository.findByIdWithSettings(1L)).thenReturn(Optional.of(user));
HardcoverSyncSettings update = new HardcoverSyncSettings();
update.setHardcoverApiKey(" new-key ");
@@ -15,7 +15,10 @@ import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.*;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import static org.mockito.Mockito.*;
@@ -89,7 +92,7 @@ class KoboAutoShelfServiceTest {
void autoAddBookToKoboShelves_withNullBookId_shouldReturnEarly() {
koboAutoShelfService.autoAddBookToKoboShelves(null);
verify(bookRepository, never()).findById(anyLong());
verify(bookRepository, never()).findByIdWithBookFiles(anyLong());
verify(koboUserSettingsRepository, never()).findByAutoAddToShelfTrueAndSyncEnabledTrue();
verify(shelfRepository, never()).findByUserIdInAndName(anyList(), anyString());
verify(bookRepository, never()).save(any());
@@ -97,11 +100,11 @@ class KoboAutoShelfServiceTest {
@Test
void autoAddBookToKoboShelves_withNonExistentBook_shouldReturnEarly() {
when(bookRepository.findById(1L)).thenReturn(Optional.empty());
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.empty());
koboAutoShelfService.autoAddBookToKoboShelves(1L);
verify(bookRepository).findById(1L);
verify(bookRepository).findByIdWithBookFiles(1L);
verify(koboUserSettingsRepository, never()).findByAutoAddToShelfTrueAndSyncEnabledTrue();
verify(shelfRepository, never()).findByUserIdInAndName(anyList(), anyString());
verify(bookRepository, never()).save(any());
@@ -109,12 +112,12 @@ class KoboAutoShelfServiceTest {
@Test
void autoAddBookToKoboShelves_withIncompatibleBook_shouldReturnEarly() {
when(bookRepository.findById(1L)).thenReturn(Optional.of(testBook));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(testBook));
when(koboCompatibilityService.isBookSupportedForKobo(testBook)).thenReturn(false);
koboAutoShelfService.autoAddBookToKoboShelves(1L);
verify(bookRepository).findById(1L);
verify(bookRepository).findByIdWithBookFiles(1L);
verify(koboCompatibilityService).isBookSupportedForKobo(testBook);
verify(koboUserSettingsRepository, never()).findByAutoAddToShelfTrueAndSyncEnabledTrue();
verify(shelfRepository, never()).findByUserIdInAndName(anyList(), anyString());
@@ -123,14 +126,14 @@ class KoboAutoShelfServiceTest {
@Test
void autoAddBookToKoboShelves_withNoEligibleUsers_shouldReturnEarly() {
when(bookRepository.findById(1L)).thenReturn(Optional.of(testBook));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(testBook));
when(koboCompatibilityService.isBookSupportedForKobo(testBook)).thenReturn(true);
when(koboUserSettingsRepository.findByAutoAddToShelfTrueAndSyncEnabledTrue())
.thenReturn(Collections.emptyList());
koboAutoShelfService.autoAddBookToKoboShelves(1L);
verify(bookRepository).findById(1L);
verify(bookRepository).findByIdWithBookFiles(1L);
verify(koboCompatibilityService).isBookSupportedForKobo(testBook);
verify(koboUserSettingsRepository).findByAutoAddToShelfTrueAndSyncEnabledTrue();
verify(shelfRepository, never()).findByUserIdInAndName(anyList(), anyString());
@@ -139,7 +142,7 @@ class KoboAutoShelfServiceTest {
@Test
void autoAddBookToKoboShelves_successfully_shouldAddBookToShelves() {
when(bookRepository.findById(1L)).thenReturn(Optional.of(testBook));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(testBook));
when(koboCompatibilityService.isBookSupportedForKobo(testBook)).thenReturn(true);
when(koboUserSettingsRepository.findByAutoAddToShelfTrueAndSyncEnabledTrue())
.thenReturn(List.of(settings1, settings2));
@@ -148,7 +151,7 @@ class KoboAutoShelfServiceTest {
koboAutoShelfService.autoAddBookToKoboShelves(1L);
verify(bookRepository).findById(1L);
verify(bookRepository).findByIdWithBookFiles(1L);
verify(koboCompatibilityService).isBookSupportedForKobo(testBook);
verify(koboUserSettingsRepository).findByAutoAddToShelfTrueAndSyncEnabledTrue();
verify(shelfRepository).findByUserIdInAndName(List.of(100L, 200L), ShelfType.KOBO.getName());
@@ -161,7 +164,7 @@ class KoboAutoShelfServiceTest {
@Test
void autoAddBookToKoboShelves_withOneUserMissingShelf_shouldAddOnlyToExistingShelves() {
when(bookRepository.findById(1L)).thenReturn(Optional.of(testBook));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(testBook));
when(koboCompatibilityService.isBookSupportedForKobo(testBook)).thenReturn(true);
when(koboUserSettingsRepository.findByAutoAddToShelfTrueAndSyncEnabledTrue())
.thenReturn(List.of(settings1, settings2));
@@ -180,7 +183,7 @@ class KoboAutoShelfServiceTest {
void autoAddBookToKoboShelves_withBookAlreadyOnShelf_shouldNotDuplicate() {
testBook.getShelves().add(koboShelf1);
when(bookRepository.findById(1L)).thenReturn(Optional.of(testBook));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(testBook));
when(koboCompatibilityService.isBookSupportedForKobo(testBook)).thenReturn(true);
when(koboUserSettingsRepository.findByAutoAddToShelfTrueAndSyncEnabledTrue())
.thenReturn(List.of(settings1, settings2));
@@ -200,7 +203,7 @@ class KoboAutoShelfServiceTest {
testBook.getShelves().add(koboShelf1);
testBook.getShelves().add(koboShelf2);
when(bookRepository.findById(1L)).thenReturn(Optional.of(testBook));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(testBook));
when(koboCompatibilityService.isBookSupportedForKobo(testBook)).thenReturn(true);
when(koboUserSettingsRepository.findByAutoAddToShelfTrueAndSyncEnabledTrue())
.thenReturn(List.of(settings1, settings2));
@@ -215,7 +218,7 @@ class KoboAutoShelfServiceTest {
@Test
void autoAddBookToKoboShelves_withNoKoboShelvesFound_shouldNotSave() {
when(bookRepository.findById(1L)).thenReturn(Optional.of(testBook));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(testBook));
when(koboCompatibilityService.isBookSupportedForKobo(testBook)).thenReturn(true);
when(koboUserSettingsRepository.findByAutoAddToShelfTrueAndSyncEnabledTrue())
.thenReturn(List.of(settings1, settings2));
@@ -231,7 +234,7 @@ class KoboAutoShelfServiceTest {
@Test
void autoAddBookToKoboShelves_withSingleUser_shouldAddToSingleShelf() {
when(bookRepository.findById(1L)).thenReturn(Optional.of(testBook));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(testBook));
when(koboCompatibilityService.isBookSupportedForKobo(testBook)).thenReturn(true);
when(koboUserSettingsRepository.findByAutoAddToShelfTrueAndSyncEnabledTrue())
.thenReturn(List.of(settings1));
@@ -252,7 +255,7 @@ class KoboAutoShelfServiceTest {
.shelves(null)
.build();
when(bookRepository.findById(1L)).thenReturn(Optional.of(testBook));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(testBook));
when(koboCompatibilityService.isBookSupportedForKobo(testBook)).thenReturn(true);
when(koboUserSettingsRepository.findByAutoAddToShelfTrueAndSyncEnabledTrue())
.thenReturn(List.of(settings1));
@@ -174,7 +174,7 @@ class KomgaServiceTest {
book.setId(100L);
book.setMetadata(metadata);
when(bookRepository.findById(100L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book));
// When: Get book pages
List<KomgaPageDto> pages = komgaService.getBookPages(100L);
@@ -196,7 +196,7 @@ class KomgaServiceTest {
book.setId(100L);
book.setMetadata(metadata);
when(bookRepository.findById(100L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book));
// When: Get book pages
List<KomgaPageDto> pages = komgaService.getBookPages(100L);
@@ -1,5 +1,6 @@
package org.booklore.service.library;
import jakarta.persistence.EntityManager;
import org.booklore.model.dto.settings.LibraryFile;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.LibraryEntity;
@@ -8,7 +9,6 @@ import org.booklore.repository.BookAdditionalFileRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.NotificationService;
import org.booklore.task.options.RescanLibraryContext;
import jakarta.persistence.EntityManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -88,7 +88,7 @@ class LibraryProcessingServiceRegressionTest {
libraryEntity.setBookEntities(List.of(filelessBook));
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(
LibraryFile.builder()
.libraryPathEntity(pathEntity)
@@ -1,5 +1,6 @@
package org.booklore.service.library;
import jakarta.persistence.EntityManager;
import org.booklore.exception.APIException;
import org.booklore.model.dto.settings.LibraryFile;
import org.booklore.model.entity.BookEntity;
@@ -10,7 +11,6 @@ import org.booklore.repository.BookAdditionalFileRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.NotificationService;
import org.booklore.task.options.RescanLibraryContext;
import jakarta.persistence.EntityManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -346,7 +346,7 @@ class LibraryProcessingServiceTest {
book.setBookFiles(List.of(epub, pdf, image));
libraryEntity.setBookEntities(List.of(book));
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
// Only epub exists on disk, pdf was removed
LibraryFile epubOnDisk = LibraryFile.builder()
@@ -385,7 +385,7 @@ class LibraryProcessingServiceTest {
libraryEntity.setLibraryPaths(List.of(pathEntity));
libraryEntity.setBookEntities(Collections.emptyList());
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
@@ -422,7 +422,7 @@ class LibraryProcessingServiceTest {
existingBook.getPrimaryBookFile().setFileName("book1.epub");
libraryEntity.setBookEntities(List.of(existingBook));
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList());
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
@@ -467,7 +467,7 @@ class LibraryProcessingServiceTest {
.fileName("book1.epub")
.build();
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
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());
@@ -497,7 +497,7 @@ class LibraryProcessingServiceTest {
libraryEntity.setLibraryPaths(List.of(pathEntity));
libraryEntity.setBookEntities(Collections.emptyList());
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList());
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
@@ -551,7 +551,7 @@ class LibraryProcessingServiceTest {
.fileName("book (with parens).epub")
.build();
when(libraryRepository.findById(libraryId))
when(libraryRepository.findByIdWithBooks(libraryId))
.thenReturn(Optional.of(libraryEntity))
.thenReturn(Optional.of(freshLibraryEntity)); // Second call returns fresh entity
when(libraryFileHelper.getAllLibraryFiles(any(LibraryEntity.class))).thenReturn(List.of(fileOnDisk));
@@ -564,7 +564,7 @@ class LibraryProcessingServiceTest {
libraryProcessingService.rescanLibrary(context);
verify(libraryRepository, times(2)).findById(libraryId);
verify(libraryRepository, times(2)).findByIdWithBooks(libraryId);
verify(bookGroupingService).groupForRescan(eq(Collections.emptyList()), any(LibraryEntity.class));
}
@@ -88,7 +88,7 @@ class BookCoverServiceTest {
@Test
void generateCustomCoverThrowsWhenBookNotFound() {
when(bookRepository.findById(1L)).thenReturn(Optional.empty());
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.generateCustomCover(1L))
.isInstanceOf(APIException.class)
@@ -97,7 +97,7 @@ class BookCoverServiceTest {
@Test
void updateCoverFromFileThrowsWhenBookNotFound() {
when(bookRepository.findById(1L)).thenReturn(Optional.empty());
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.empty());
MultipartFile file = mock(MultipartFile.class);
assertThatThrownBy(() -> service.updateCoverFromFile(1L, file))
@@ -106,7 +106,7 @@ class BookCoverServiceTest {
@Test
void updateCoverFromUrlThrowsWhenBookNotFound() {
when(bookRepository.findById(1L)).thenReturn(Optional.empty());
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.updateCoverFromUrl(1L, "http://example.com/cover.jpg"))
.isInstanceOf(APIException.class);
@@ -127,7 +127,7 @@ class BookCoverServiceTest {
@Test
void generateCustomCoverThrowsWhenCoverLocked() {
BookEntity book = buildBook(1L, true);
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
assertThatThrownBy(() -> service.generateCustomCover(1L))
.isInstanceOf(APIException.class)
@@ -137,7 +137,7 @@ class BookCoverServiceTest {
@Test
void updateCoverFromFileThrowsWhenCoverLocked() {
BookEntity book = buildBook(1L, true);
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
MultipartFile file = mock(MultipartFile.class);
assertThatThrownBy(() -> service.updateCoverFromFile(1L, file))
@@ -148,7 +148,7 @@ class BookCoverServiceTest {
@Test
void updateCoverFromUrlThrowsWhenCoverLocked() {
BookEntity book = buildBook(1L, true);
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
assertThatThrownBy(() -> service.updateCoverFromUrl(1L, "http://example.com"))
.isInstanceOf(APIException.class)
@@ -370,7 +370,7 @@ class BookCoverServiceTest {
AuthorEntity author = AuthorEntity.builder().name("Jane Doe").build();
book.getMetadata().setAuthors(List.of(author));
book.setBookFiles(new ArrayList<>());
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(coverImageGenerator.generateCover("Test Book", "Jane Doe")).thenReturn(new byte[]{1, 2, 3});
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
@@ -490,7 +490,7 @@ class BookCoverServiceTest {
@Test
void successfullyUpdatesCoverFromUrl() {
BookEntity book = buildBook(1L, false);
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
@@ -508,7 +508,7 @@ class BookCoverServiceTest {
@Test
void successfullyUpdatesCoverFromFile() {
BookEntity book = buildBook(1L, false);
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
MultipartFile file = mock(MultipartFile.class);
@@ -751,7 +751,7 @@ class BookCoverServiceTest {
var callback = inv.getArgument(0, org.springframework.transaction.support.TransactionCallback.class);
return callback.doInTransaction(null);
});
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(processor);
when(processor.generateCover(book)).thenReturn(true);
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
@@ -816,7 +816,7 @@ class BookCoverServiceTest {
var callback = inv.getArgument(0, org.springframework.transaction.support.TransactionCallback.class);
return callback.doInTransaction(null);
});
when(bookRepository.findById(2L)).thenReturn(Optional.of(withoutCover));
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(withoutCover));
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(processor);
when(processor.generateCover(withoutCover)).thenReturn(true);
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
@@ -977,7 +977,7 @@ class BookCoverServiceTest {
MetadataWriter writer = mock(MetadataWriter.class);
when(metadataWriterFactory.getWriter(BookFileType.EPUB)).thenReturn(Optional.of(writer));
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
try (MockedStatic<FileFingerprint> fpMock = mockStatic(FileFingerprint.class)) {
@@ -994,7 +994,7 @@ class BookCoverServiceTest {
void skipsWriteWhenNoPrimaryFile() {
BookEntity book = buildBook(1L, false);
book.setBookFiles(new ArrayList<>());
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
@@ -1009,7 +1009,7 @@ class BookCoverServiceTest {
@Test
void sendsNotificationWhenUpdatesExist() {
BookEntity book = buildBook(1L, false);
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class);
when(bookRepository.findCoverUpdateInfoByIds(List.of(1L))).thenReturn(List.of(projection));
@@ -1022,7 +1022,7 @@ class BookCoverServiceTest {
@Test
void doesNotSendNotificationWhenNoUpdates() {
BookEntity book = buildBook(1L, false);
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
@@ -1038,7 +1038,7 @@ class BookCoverServiceTest {
void returnsNullForEmptyAuthors() {
BookEntity book = buildBook(1L, false);
book.getMetadata().setAuthors(new ArrayList<>());
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(coverImageGenerator.generateCover("Test Book", null)).thenReturn(new byte[]{1});
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
@@ -1054,7 +1054,7 @@ class BookCoverServiceTest {
authors.add(AuthorEntity.builder().name("Alice").build());
authors.add(AuthorEntity.builder().name("Bob").build());
book.getMetadata().setAuthors(authors);
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(coverImageGenerator.generateCover(eq("Test Book"), argThat(s -> s.contains("Alice") && s.contains("Bob"))))
.thenReturn(new byte[]{1});
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
@@ -1078,7 +1078,7 @@ class BookCoverServiceTest {
.isBookFormat(true)
.build();
book.setBookFiles(List.of(bookFile));
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
@@ -59,6 +59,7 @@ class BookMetadataServiceTest {
@Mock private NotificationService notificationService;
@Mock private BookMetadataRepository bookMetadataRepository;
@Mock private BookQueryService bookQueryService;
@Mock private org.booklore.service.audit.AuditService auditService;
@Mock private CbxMetadataExtractor cbxMetadataExtractor;
@Mock private MetadataExtractorFactory metadataExtractorFactory;
@Mock private MetadataClearFlagsMapper metadataClearFlagsMapper;
@@ -74,7 +75,7 @@ class BookMetadataServiceTest {
service = new BookMetadataService(
bookRepository, bookMapper, bookMetadataMapper, bookMetadataUpdater,
notificationService, bookMetadataRepository, bookQueryService,
parserMap, cbxMetadataExtractor, metadataExtractorFactory,
auditService, parserMap, cbxMetadataExtractor, metadataExtractorFactory,
metadataClearFlagsMapper, transactionManager, appSettingService
);
}
@@ -449,7 +450,7 @@ class BookMetadataServiceTest {
@Test
void throwsWhenBookNotFound() {
when(bookRepository.findById(1L)).thenReturn(Optional.empty());
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.getComicInfoMetadata(1L))
.isInstanceOf(APIException.class);
@@ -458,7 +459,7 @@ class BookMetadataServiceTest {
@Test
void returnsNullWhenPrimaryFileIsNull() {
BookEntity bookEntity = BookEntity.builder().id(1L).bookFiles(new ArrayList<>()).build();
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
BookMetadata result = service.getComicInfoMetadata(1L);
@@ -469,7 +470,7 @@ class BookMetadataServiceTest {
void returnsNullWhenFileTypeIsNotCbx() {
BookFileEntity file = BookFileEntity.builder().bookType(BookFileType.PDF).isBookFormat(true).build();
BookEntity bookEntity = BookEntity.builder().id(1L).bookFiles(List.of(file)).build();
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
BookMetadata result = service.getComicInfoMetadata(1L);
@@ -514,8 +515,8 @@ class BookMetadataServiceTest {
BookEntity book1 = BookEntity.builder().id(1L).build();
BookEntity book2 = BookEntity.builder().id(2L).build();
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book1));
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(book2));
when(bookRepository.findByIdFull(1L)).thenReturn(Optional.of(book1));
when(bookRepository.findByIdFull(2L)).thenReturn(Optional.of(book2));
var txStatus = mock(org.springframework.transaction.TransactionStatus.class);
when(transactionManager.getTransaction(any())).thenReturn(txStatus);
@@ -542,8 +543,8 @@ class BookMetadataServiceTest {
when(transactionManager.getTransaction(any())).thenReturn(txStatus);
BookEntity book2 = BookEntity.builder().id(2L).build();
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.empty());
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(book2));
when(bookRepository.findByIdFull(1L)).thenReturn(Optional.empty());
when(bookRepository.findByIdFull(2L)).thenReturn(Optional.of(book2));
service.bulkUpdateMetadata(request, false, false, false);
@@ -565,7 +566,7 @@ class BookMetadataServiceTest {
when(transactionManager.getTransaction(any())).thenReturn(txStatus);
BookEntity book = BookEntity.builder().id(1L).build();
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdFull(1L)).thenReturn(Optional.of(book));
service.bulkUpdateMetadata(request, false, false, false);
@@ -581,7 +582,7 @@ class BookMetadataServiceTest {
@Test
void throwsWhenBookNotFound() {
when(bookRepository.findById(99L)).thenReturn(Optional.empty());
when(bookRepository.findByIdWithBookFiles(99L)).thenReturn(Optional.empty());
FetchMetadataRequest request = FetchMetadataRequest.builder()
.providers(List.of(MetadataProvider.Google))
.build();
@@ -21,8 +21,10 @@ import org.mockito.junit.jupiter.MockitoExtension;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import static org.assertj.core.api.Assertions.assertThat;
@@ -233,10 +235,10 @@ class OidcGroupMappingServiceTest {
@Test
void syncUserGroups_onLogin_replacesLibraries() {
var perms = new UserPermissionsEntity();
var librariesHolder = new AtomicReference<List<LibraryEntity>>();
var librariesHolder = new AtomicReference<Set<LibraryEntity>>();
var existingLib = new LibraryEntity();
existingLib.setId(10L);
librariesHolder.set(new ArrayList<>(List.of(existingLib)));
librariesHolder.set(new HashSet<>(List.of(existingLib)));
var user = createMockedUserWithLibraries(perms, librariesHolder);
var mapping = createMapping(false, "[]", "[1,2]");
@@ -277,10 +279,10 @@ class OidcGroupMappingServiceTest {
@Test
void syncUserGroups_onLoginAdditive_addsLibrariesToExisting() {
var perms = new UserPermissionsEntity();
var librariesHolder = new AtomicReference<List<LibraryEntity>>();
var librariesHolder = new AtomicReference<Set<LibraryEntity>>();
var existingLib = new LibraryEntity();
existingLib.setId(10L);
librariesHolder.set(new ArrayList<>(List.of(existingLib)));
librariesHolder.set(new HashSet<>(List.of(existingLib)));
var user = createMockedUserWithLibraries(perms, librariesHolder);
var mapping = createMapping(false, "[]", "[1]");
@@ -370,7 +372,7 @@ class OidcGroupMappingServiceTest {
}
private BookLoreUserEntity createMockedUserWithLibraries(UserPermissionsEntity perms,
AtomicReference<List<LibraryEntity>> librariesHolder) {
AtomicReference<Set<LibraryEntity>> librariesHolder) {
var user = mock(BookLoreUserEntity.class);
lenient().when(user.getUsername()).thenReturn("testuser");
when(user.getPermissions()).thenReturn(perms);
@@ -61,7 +61,7 @@ class CbxReaderServiceTest {
@Test
void testGetAvailablePages_CBZ_Success() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cbzPath.toString());
@@ -92,7 +92,7 @@ class CbxReaderServiceTest {
@Test
void testGetAvailablePages_CBZ_Fallback_Success() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cbzPath.toString());
@@ -139,7 +139,7 @@ class CbxReaderServiceTest {
@Test
void testStreamPageImage_CBZ_Success() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cbzPath.toString());
@@ -172,13 +172,13 @@ class CbxReaderServiceTest {
@Test
void testGetAvailablePages_CBZ_ThrowsOnMissingBook() {
when(bookRepository.findById(2L)).thenReturn(Optional.empty());
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.empty());
assertThrows(ApiError.BOOK_NOT_FOUND.createException().getClass(), () -> cbxReaderService.getAvailablePages(2L));
}
@Test
void testGetAvailablePages_CB7_Success() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cb7Path.toString());
@@ -207,7 +207,7 @@ class CbxReaderServiceTest {
@Test
void testGetAvailablePages_CBR_Success() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cbrPath.toString());
@@ -230,7 +230,7 @@ class CbxReaderServiceTest {
@Test
void testStreamPageImage_CBR_Success() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cbrPath.toString());
@@ -259,7 +259,7 @@ class CbxReaderServiceTest {
@Test
void testStreamPageImage_PageOutOfRange_Throws() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cbzPath.toString());
@@ -290,7 +290,7 @@ class CbxReaderServiceTest {
void testGetAvailablePages_UnsupportedArchive_Throws() throws Exception {
Path unknownPath = Path.of("/tmp/test.unknown");
Files.deleteIfExists(unknownPath);
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(unknownPath.toString());
@@ -303,7 +303,7 @@ class CbxReaderServiceTest {
@Test
void testStreamPageImage_EntryNotFound_Throws() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cbzPath.toString());
@@ -1,5 +1,7 @@
package org.booklore.service.reader;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.response.EpubBookInfo;
import org.booklore.model.dto.response.EpubManifestItem;
@@ -8,8 +10,6 @@ import org.booklore.model.dto.response.EpubTocItem;
import org.booklore.model.entity.BookEntity;
import org.booklore.repository.BookRepository;
import org.booklore.util.FileUtils;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -21,7 +21,9 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.io.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -105,7 +107,7 @@ class EpubReaderServiceTest {
@Test
void testGetBookInfo_Success() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -136,7 +138,7 @@ class EpubReaderServiceTest {
@Test
void testGetBookInfo_BookNotFound() {
when(bookRepository.findById(999L)).thenReturn(Optional.empty());
when(bookRepository.findByIdWithBookFiles(999L)).thenReturn(Optional.empty());
assertThrows(ApiError.BOOK_NOT_FOUND.createException().getClass(),
() -> epubReaderService.getBookInfo(999L));
@@ -144,7 +146,7 @@ class EpubReaderServiceTest {
@Test
void testGetBookInfo_CacheHit() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -172,7 +174,7 @@ class EpubReaderServiceTest {
@Test
void testStreamFile_Success() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -207,7 +209,7 @@ class EpubReaderServiceTest {
@Test
void testStreamFile_FileNotFound() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -233,7 +235,7 @@ class EpubReaderServiceTest {
@Test
void testStreamFile_PathTraversalBlocked() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -259,7 +261,7 @@ class EpubReaderServiceTest {
@Test
void testStreamFile_ContainerXmlAllowed() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -294,7 +296,7 @@ class EpubReaderServiceTest {
@Test
void testGetContentType_FromManifest() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -320,7 +322,7 @@ class EpubReaderServiceTest {
@Test
void testGetContentType_Fallback() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -348,7 +350,7 @@ class EpubReaderServiceTest {
@Test
void testGetFileSize_FromManifest() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -370,7 +372,7 @@ class EpubReaderServiceTest {
@Test
void testGetFileSize_NotFound() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -391,7 +393,7 @@ class EpubReaderServiceTest {
@Test
void testSpineOrder() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -419,7 +421,7 @@ class EpubReaderServiceTest {
@Test
void testTocParsing() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -448,7 +450,7 @@ class EpubReaderServiceTest {
@Test
void testManifestProperties() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -489,7 +491,7 @@ class EpubReaderServiceTest {
@Test
void testStreamFile_LeadingSlashHandled() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
@@ -5,20 +5,20 @@ import org.booklore.exception.APIException;
import org.booklore.exception.ApiError;
import org.booklore.mapper.AdditionalFileMapper;
import org.booklore.model.dto.BookFile;
import org.booklore.model.dto.BookMetadata;
import org.booklore.model.dto.settings.AppSettings;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.model.enums.BookFileExtension;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookAdditionalFileRepository;
import org.booklore.repository.BookRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.file.FileFingerprint;
import org.booklore.service.appsettings.AppSettingService;
import org.booklore.service.file.FileFingerprint;
import org.booklore.service.file.FileMovingHelper;
import org.booklore.model.dto.BookMetadata;
import org.booklore.model.enums.BookFileExtension;
import org.booklore.service.metadata.extractor.MetadataExtractorFactory;
import org.booklore.service.audit.AuditService;
import org.booklore.service.monitoring.MonitoringRegistrationService;
@@ -26,8 +26,6 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.MockitoAnnotations;
@@ -38,14 +36,11 @@ import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.mockito.Mockito.*;
class FileUploadServiceTest {
@@ -244,7 +239,7 @@ class FileUploadServiceTest {
primaryFile.setBookType(BookFileType.EPUB);
book.setBookFiles(new ArrayList<>(List.of(primaryFile)));
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.of(book));
try (MockedStatic<FileFingerprint> fp = mockStatic(FileFingerprint.class)) {
fp.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash-123");
@@ -287,7 +282,7 @@ class FileUploadServiceTest {
primaryFile.setBookType(BookFileType.EPUB);
book.setBookFiles(new ArrayList<>(List.of(primaryFile)));
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.of(book));
try (MockedStatic<FileFingerprint> fp = mockStatic(FileFingerprint.class)) {
fp.when(() -> FileFingerprint.generateHash(any())).thenReturn("dup-hash");
@@ -363,7 +358,7 @@ class FileUploadServiceTest {
book.setBookFiles(new ArrayList<>(List.of(primaryFile)));
book.getPrimaryBookFile().setFileSubPath(".");
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.of(book));
when(bookAdditionalFileRepository.save(any(BookFileEntity.class))).thenAnswer(inv -> inv.getArgument(0));
when(additionalFileMapper.toAdditionalFile(any(BookFileEntity.class))).thenReturn(mock(BookFile.class));
@@ -210,7 +210,7 @@ class UserProvisioningServiceTest {
provisionDetails);
verify(userRepository).save(userCaptor.capture());
assertThat(userCaptor.getValue().getLibraries()).isNull();
assertThat(userCaptor.getValue().getLibraries()).isNullOrEmpty();
verifyNoInteractions(libraryRepository);
}
@@ -224,7 +224,7 @@ class UserProvisioningServiceTest {
provisionDetails);
verify(userRepository).save(userCaptor.capture());
assertThat(userCaptor.getValue().getLibraries()).isNull();
assertThat(userCaptor.getValue().getLibraries()).isNullOrEmpty();
verifyNoInteractions(libraryRepository);
}