Refactor book service in BE and FE (#2013)

* Refactor book service in BE and FE

* Add missing method

---------

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2025-12-28 19:37:35 -07:00
committed by GitHub
co-authored by acx10
parent 60095c2173
commit 01446c2537
37 changed files with 2085 additions and 807 deletions
@@ -6,9 +6,9 @@ import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.book.BookDownloadService;
import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.book.BookService;
import com.adityachandel.booklore.service.book.BookUpdateService;
import com.adityachandel.booklore.service.user.UserProgressService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.adityachandel.booklore.service.kobo.KoboReadingStateService;
import com.adityachandel.booklore.util.FileService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -41,17 +41,15 @@ class BookServiceDeleteTests {
EpubViewerPreferencesRepository epubViewerPreferencesRepository = Mockito.mock(EpubViewerPreferencesRepository.class);
CbxViewerPreferencesRepository cbxViewerPreferencesRepository = Mockito.mock(CbxViewerPreferencesRepository.class);
NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository = Mockito.mock(NewPdfViewerPreferencesRepository.class);
ShelfRepository shelfRepository = Mockito.mock(ShelfRepository.class);
FileService fileService = Mockito.mock(FileService.class);
BookMapper bookMapper = Mockito.mock(BookMapper.class);
UserRepository userRepository = Mockito.mock(UserRepository.class);
UserBookProgressRepository userBookProgressRepository = Mockito.mock(UserBookProgressRepository.class);
AuthenticationService authenticationService = Mockito.mock(AuthenticationService.class);
BookQueryService bookQueryService = Mockito.mock(BookQueryService.class);
UserProgressService userProgressService = Mockito.mock(UserProgressService.class);
BookDownloadService bookDownloadService = Mockito.mock(BookDownloadService.class);
MonitoringRegistrationService monitoringRegistrationService = Mockito.mock(MonitoringRegistrationService.class);
KoboReadingStateService koboReadingStateService = Mockito.mock(KoboReadingStateService.class);
BookUpdateService bookUpdateService = Mockito.mock(BookUpdateService.class);
bookService = new BookService(
bookRepository,
@@ -59,17 +57,15 @@ class BookServiceDeleteTests {
epubViewerPreferencesRepository,
cbxViewerPreferencesRepository,
newPdfViewerPreferencesRepository,
shelfRepository,
fileService,
bookMapper,
userRepository,
userBookProgressRepository,
authenticationService,
bookQueryService,
userProgressService,
bookDownloadService,
monitoringRegistrationService,
koboReadingStateService
bookUpdateService
);
}
@@ -0,0 +1,394 @@
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.dto.response.BookDeletionResponse;
import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.adityachandel.booklore.service.user.UserProgressService;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(org.mockito.junit.jupiter.MockitoExtension.class)
class BookServiceTest {
@Mock private BookRepository bookRepository;
@Mock private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
@Mock private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
@Mock private CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
@Mock private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
@Mock private FileService fileService;
@Mock private BookMapper bookMapper;
@Mock private UserBookProgressRepository userBookProgressRepository;
@Mock private AuthenticationService authenticationService;
@Mock private BookQueryService bookQueryService;
@Mock private UserProgressService userProgressService;
@Mock private BookDownloadService bookDownloadService;
@Mock private MonitoringRegistrationService monitoringRegistrationService;
@Mock private BookUpdateService bookUpdateService;
@InjectMocks
private BookService bookService;
private BookLoreUser testUser;
@BeforeEach
void setUp() {
BookLoreUser.UserPermissions perms = new BookLoreUser.UserPermissions();
perms.setAdmin(true);
testUser = BookLoreUser.builder()
.id(1L)
.permissions(perms)
.assignedLibraries(List.of())
.build();
}
@Test
void getBookDTOs_adminUser_returnsBooksWithProgress() {
Book book = Book.builder().id(1L).bookType(BookFileType.PDF).shelves(Set.of()).build();
when(bookQueryService.getAllBooks(anyBoolean())).thenReturn(List.of(book));
when(userProgressService.fetchUserProgress(anyLong(), anySet())).thenReturn(Map.of(1L, new UserBookProgressEntity()));
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
List<Book> result = bookService.getBookDTOs(true);
assertEquals(1, result.size());
verify(bookQueryService).getAllBooks(true);
}
@Test
void getBooksByIds_returnsMappedBooksWithProgress() {
BookEntity entity = new BookEntity();
entity.setId(2L);
entity.setBookType(BookFileType.EPUB);
LibraryPathEntity libPath = new LibraryPathEntity();
libPath.setPath("/tmp/library");
LibraryEntity library = new LibraryEntity();
library.setLibraryPaths(List.of(libPath));
entity.setLibrary(library);
when(bookQueryService.findAllWithMetadataByIds(anySet())).thenReturn(List.of(entity));
when(userProgressService.fetchUserProgress(anyLong(), anySet())).thenReturn(Map.of(2L, new UserBookProgressEntity()));
Book mappedBook = Book.builder().id(2L).bookType(BookFileType.EPUB).metadata(BookMetadata.builder().build()).build();
when(bookMapper.toBook(entity)).thenReturn(mappedBook);
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn("/tmp/library/book.epub");
List<Book> result = bookService.getBooksByIds(Set.of(2L), false);
assertEquals(1, result.size());
assertEquals(2L, result.get(0).getId());
}
}
@Test
void getBook_existingBook_returnsBookWithProgress() {
BookEntity entity = new BookEntity();
entity.setId(3L);
entity.setBookType(BookFileType.PDF);
LibraryPathEntity libPath = new LibraryPathEntity();
libPath.setPath("/tmp/library");
LibraryEntity library = new LibraryEntity();
library.setLibraryPaths(List.of(libPath));
entity.setLibrary(library);
when(bookRepository.findById(3L)).thenReturn(Optional.of(entity));
when(userBookProgressRepository.findByUserIdAndBookId(anyLong(), eq(3L))).thenReturn(Optional.of(new UserBookProgressEntity()));
Book mappedBook = Book.builder().id(3L).bookType(BookFileType.PDF).metadata(BookMetadata.builder().build()).shelves(Set.of()).build();
when(bookMapper.toBook(entity)).thenReturn(mappedBook);
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn("/tmp/library/book.pdf");
Book result = bookService.getBook(3L, true);
assertEquals(3L, result.getId());
verify(bookRepository).findById(3L);
}
}
@Test
void getBook_notFound_throwsException() {
when(bookRepository.findById(99L)).thenReturn(Optional.empty());
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
assertThrows(APIException.class, () -> bookService.getBook(99L, true));
}
@Test
void getBookViewerSetting_epub_returnsEpubSettings() {
BookEntity entity = new BookEntity();
entity.setId(4L);
entity.setBookType(BookFileType.EPUB);
when(bookRepository.findById(4L)).thenReturn(Optional.of(entity));
EpubViewerPreferencesEntity epubPref = new EpubViewerPreferencesEntity();
epubPref.setFont("Arial");
when(epubViewerPreferencesRepository.findByBookIdAndUserId(4L, testUser.getId())).thenReturn(Optional.of(epubPref));
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
BookViewerSettings settings = bookService.getBookViewerSetting(4L);
assertNotNull(settings.getEpubSettings());
assertEquals("Arial", settings.getEpubSettings().getFont());
}
@Test
void getBookViewerSetting_unsupportedType_throwsException() {
BookEntity entity = new BookEntity();
entity.setId(5L);
entity.setBookType(null);
when(bookRepository.findById(5L)).thenReturn(Optional.of(entity));
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
assertThrows(APIException.class, () -> bookService.getBookViewerSetting(5L));
}
@Test
void updateBookViewerSetting_delegatesToUpdateService() {
BookViewerSettings settings = BookViewerSettings.builder().build();
bookService.updateBookViewerSetting(1L, settings);
verify(bookUpdateService).updateBookViewerSetting(1L, settings);
}
@Test
void updateReadProgress_delegatesToUpdateService() {
ReadProgressRequest req = new ReadProgressRequest();
bookService.updateReadProgress(req);
verify(bookUpdateService).updateReadProgress(req);
}
@Test
void updateReadStatus_delegatesToUpdateService() {
List<Long> ids = List.of(1L, 2L);
List<BookStatusUpdateResponse> responses = List.of(new BookStatusUpdateResponse());
when(bookUpdateService.updateReadStatus(ids, "READ")).thenReturn(responses);
List<BookStatusUpdateResponse> result = bookService.updateReadStatus(ids, "READ");
assertEquals(responses, result);
}
@Test
void assignShelvesToBooks_delegatesToUpdateService() {
Set<Long> bookIds = Set.of(1L);
Set<Long> assign = Set.of(2L);
Set<Long> unassign = Set.of(3L);
List<Book> books = List.of(Book.builder().id(1L).build());
when(bookUpdateService.assignShelvesToBooks(bookIds, assign, unassign)).thenReturn(books);
List<Book> result = bookService.assignShelvesToBooks(bookIds, assign, unassign);
assertEquals(books, result);
}
@Test
void getBookThumbnail_fileExists_returnsUrlResource() throws Exception {
when(fileService.getThumbnailFile(1L)).thenReturn("/tmp/cover.jpg");
Path path = Paths.get("/tmp/cover.jpg");
Files.createFile(path);
try {
Resource res = bookService.getBookThumbnail(1L);
assertTrue(res instanceof UrlResource);
} finally {
Files.deleteIfExists(path);
}
}
@Test
void getBookThumbnail_fileMissing_returnsDefault() throws Exception {
when(fileService.getThumbnailFile(1L)).thenReturn("/tmp/nonexistent.jpg");
Resource res = bookService.getBookThumbnail(1L);
assertTrue(res instanceof UrlResource);
}
@Test
void getBookThumbnail_malformedPath_throwsRuntimeException() {
when(fileService.getThumbnailFile(123L)).thenReturn("\0illegal:path");
assertThrows(RuntimeException.class, () -> bookService.getBookThumbnail(123L));
}
@Test
void getBookCover_fileExists_returnsUrlResource() throws Exception {
when(fileService.getCoverFile(1L)).thenReturn("/tmp/cover2.jpg");
Path path = Paths.get("/tmp/cover2.jpg");
Files.createFile(path);
try {
Resource res = bookService.getBookCover(1L);
assertTrue(res instanceof UrlResource);
} finally {
Files.deleteIfExists(path);
}
}
@Test
void getBookCover_fileMissing_returnsClassPathResource() {
when(fileService.getCoverFile(1L)).thenReturn("/tmp/nonexistent2.jpg");
Resource res = bookService.getBookCover(1L);
assertTrue(res instanceof ClassPathResource);
}
@Test
void getBookCover_malformedPath_throwsRuntimeException() {
when(fileService.getCoverFile(123L)).thenReturn("\0illegal:path");
assertThrows(RuntimeException.class, () -> bookService.getBookCover(123L));
}
@Test
void getBackgroundImage_returnsResource() {
Resource mockResource = mock(Resource.class);
when(fileService.getBackgroundResource(testUser.getId())).thenReturn(mockResource);
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
Resource res = bookService.getBackgroundImage();
assertEquals(mockResource, res);
}
@Test
void downloadBook_delegatesToDownloadService() {
ResponseEntity<Resource> response = ResponseEntity.ok(mock(Resource.class));
when(bookDownloadService.downloadBook(1L)).thenReturn(response);
ResponseEntity<Resource> result = bookService.downloadBook(1L);
assertEquals(response, result);
}
@Test
void getBookContent_returnsByteArrayResource() throws Exception {
BookEntity entity = new BookEntity();
entity.setId(10L);
when(bookRepository.findById(10L)).thenReturn(Optional.of(entity));
Path path = Paths.get("/tmp/bookcontent.txt");
Files.write(path, "hello".getBytes());
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn(path.toString());
ResponseEntity<ByteArrayResource> response = bookService.getBookContent(10L);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertArrayEquals("hello".getBytes(), response.getBody().getByteArray());
} finally {
Files.deleteIfExists(path);
}
}
@Test
void getBookContent_bookNotFound_throwsException() {
when(bookRepository.findById(404L)).thenReturn(Optional.empty());
assertThrows(APIException.class, () -> bookService.getBookContent(404L));
}
@Test
void getBookContent_fileIoError_throwsIOException() throws Exception {
BookEntity entity = new BookEntity();
entity.setId(12L);
when(bookRepository.findById(12L)).thenReturn(Optional.of(entity));
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn("/tmp/nonexistentfile.txt");
assertThrows(java.io.FileNotFoundException.class, () -> bookService.getBookContent(12L));
}
}
@Test
void deleteBooks_deletesFilesAndEntities() throws Exception {
BookEntity entity = new BookEntity();
entity.setId(11L);
LibraryEntity library = new LibraryEntity();
LibraryPathEntity libPath = new LibraryPathEntity();
libPath.setPath("/tmp/library");
library.setLibraryPaths(List.of(libPath));
entity.setLibrary(library);
Path filePath = Paths.get("/tmp/bookfile.txt");
Files.createDirectories(filePath.getParent());
Files.write(filePath, "abc".getBytes());
when(bookQueryService.findAllWithMetadataByIds(Set.of(11L))).thenReturn(List.of(entity));
doNothing().when(bookRepository).deleteAll(anyList());
BookEntity spyEntity = spy(entity);
doReturn(filePath).when(spyEntity).getFullFilePath();
when(bookQueryService.findAllWithMetadataByIds(Set.of(11L))).thenReturn(List.of(spyEntity));
BookDeletionResponse response = bookService.deleteBooks(Set.of(11L)).getBody();
assertNotNull(response);
assertTrue(response.getFailedFileDeletions().isEmpty());
assertEquals(Set.of(11L), response.getDeleted());
Files.deleteIfExists(filePath);
}
@Test
void deleteBooks_fileDoesNotExist_deletesEntityOnly() {
BookEntity entity = new BookEntity();
entity.setId(13L);
LibraryEntity library = new LibraryEntity();
LibraryPathEntity libPath = new LibraryPathEntity();
libPath.setPath("/tmp/library");
library.setLibraryPaths(List.of(libPath));
entity.setLibrary(library);
BookEntity spyEntity = spy(entity);
doReturn(Paths.get("/tmp/nonexistentfile.txt")).when(spyEntity).getFullFilePath();
when(bookQueryService.findAllWithMetadataByIds(Set.of(13L))).thenReturn(List.of(spyEntity));
doNothing().when(bookRepository).deleteAll(anyList());
BookDeletionResponse response = bookService.deleteBooks(Set.of(13L)).getBody();
assertNotNull(response);
assertTrue(response.getFailedFileDeletions().isEmpty());
assertEquals(Set.of(13L), response.getDeleted());
}
@Test
void deleteEmptyParentDirsUpToLibraryFolders_deletesEmptyDirs() throws Exception {
Path root = Files.createTempDirectory("libroot");
Path subdir = Files.createDirectory(root.resolve("subdir"));
Path file = subdir.resolve(".DS_Store");
Files.createFile(file);
Set<Path> roots = Set.of(root);
bookService.deleteEmptyParentDirsUpToLibraryFolders(subdir, roots);
assertFalse(Files.exists(subdir));
Files.deleteIfExists(root);
}
@Test
void filterShelvesByUserId_returnsOnlyUserShelves() {
Shelf shelf1 = Shelf.builder().id(1L).userId(1L).build();
Shelf shelf2 = Shelf.builder().id(2L).userId(2L).build();
Set<Shelf> shelves = Set.of(shelf1, shelf2);
Set<Shelf> result = org.springframework.test.util.ReflectionTestUtils.invokeMethod(
bookService, "filterShelvesByUserId", shelves, 1L);
assertEquals(1, result.size());
assertTrue(result.contains(shelf1));
}
}
@@ -0,0 +1,343 @@
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.model.dto.progress.EpubProgress;
import com.adityachandel.booklore.model.dto.progress.PdfProgress;
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse;
import com.adityachandel.booklore.model.dto.response.PersonalRatingUpdateResponse;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.ReadStatus;
import com.adityachandel.booklore.model.enums.ResetProgressType;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.kobo.KoboReadingStateService;
import com.adityachandel.booklore.service.user.UserProgressService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class BookUpdateServiceTest {
@Mock private BookRepository bookRepository;
@Mock private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
@Mock private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
@Mock private CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
@Mock private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
@Mock private ShelfRepository shelfRepository;
@Mock private BookMapper bookMapper;
@Mock private UserRepository userRepository;
@Mock private UserBookProgressRepository userBookProgressRepository;
@Mock private AuthenticationService authenticationService;
@Mock private BookQueryService bookQueryService;
@Mock private UserProgressService userProgressService;
@Mock private KoboReadingStateService koboReadingStateService;
@InjectMocks
private BookUpdateService bookUpdateService;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
bookUpdateService = new BookUpdateService(
bookRepository,
pdfViewerPreferencesRepository,
epubViewerPreferencesRepository,
cbxViewerPreferencesRepository,
newPdfViewerPreferencesRepository,
shelfRepository,
bookMapper,
userRepository,
userBookProgressRepository,
authenticationService,
bookQueryService,
userProgressService,
koboReadingStateService
);
}
@Test
void updateBookViewerSetting_pdf_shouldUpdatePdfPrefs() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
book.setBookType(BookFileType.PDF);
BookLoreUser user = mock(BookLoreUser.class);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(2L);
PdfViewerPreferencesEntity pdfPrefs = new PdfViewerPreferencesEntity();
when(pdfViewerPreferencesRepository.findByBookIdAndUserId(bookId, 2L)).thenReturn(Optional.of(pdfPrefs));
BookViewerSettings settings = BookViewerSettings.builder()
.pdfSettings(PdfViewerPreferences.builder()
.zoom("1.5")
.spread("spread")
.build())
.build();
bookUpdateService.updateBookViewerSetting(bookId, settings);
verify(pdfViewerPreferencesRepository).save(pdfPrefs);
assertEquals("1.5", pdfPrefs.getZoom());
assertEquals("spread", pdfPrefs.getSpread());
}
@Test
void updateBookViewerSetting_epub_shouldUpdateEpubPrefs() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
book.setBookType(BookFileType.EPUB);
BookLoreUser user = mock(BookLoreUser.class);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(2L);
EpubViewerPreferencesEntity epubPrefs = new EpubViewerPreferencesEntity();
when(epubViewerPreferencesRepository.findByBookIdAndUserId(bookId, 2L)).thenReturn(Optional.of(epubPrefs));
BookViewerSettings settings = BookViewerSettings.builder()
.epubSettings(EpubViewerPreferences.builder()
.font("font")
.fontSize(12)
.theme("theme")
.flow("flow")
.spread("spread")
.letterSpacing(1.2f)
.lineHeight(1.3f)
.build())
.build();
bookUpdateService.updateBookViewerSetting(bookId, settings);
verify(epubViewerPreferencesRepository).save(epubPrefs);
assertEquals("font", epubPrefs.getFont());
assertEquals(12, epubPrefs.getFontSize());
assertEquals("theme", epubPrefs.getTheme());
assertEquals("flow", epubPrefs.getFlow());
assertEquals("spread", epubPrefs.getSpread());
assertEquals(1.2f, epubPrefs.getLetterSpacing());
assertEquals(1.3f, epubPrefs.getLineHeight());
}
@Test
void updateBookViewerSetting_unsupportedType_shouldThrow() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
book.setBookType(null);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
when(authenticationService.getAuthenticatedUser()).thenReturn(mock(BookLoreUser.class));
BookViewerSettings settings = BookViewerSettings.builder().build();
assertThrows(APIException.class, () -> bookUpdateService.updateBookViewerSetting(bookId, settings));
}
@Test
void updateReadProgress_epub_shouldUpdateProgress() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
book.setBookType(BookFileType.EPUB);
BookLoreUser user = mock(BookLoreUser.class);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(2L);
UserBookProgressEntity progress = new UserBookProgressEntity();
when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress));
BookLoreUserEntity userEntity = new BookLoreUserEntity();
when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity));
ReadProgressRequest req = new ReadProgressRequest();
req.setBookId(bookId);
EpubProgress epubProgress = EpubProgress.builder().cfi("cfi").percentage(100f).build();
req.setEpubProgress(epubProgress);
bookUpdateService.updateReadProgress(req);
verify(userBookProgressRepository).save(progress);
assertEquals("cfi", progress.getEpubProgress());
assertEquals(ReadStatus.READ, progress.getReadStatus());
assertEquals(100f, progress.getEpubProgressPercent());
}
@Test
void updateReadProgress_pdf_shouldUpdateProgress() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
book.setBookType(BookFileType.PDF);
BookLoreUser user = mock(BookLoreUser.class);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(2L);
UserBookProgressEntity progress = new UserBookProgressEntity();
when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress));
BookLoreUserEntity userEntity = new BookLoreUserEntity();
when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity));
ReadProgressRequest req = new ReadProgressRequest();
req.setBookId(bookId);
PdfProgress pdfProgress = PdfProgress.builder().page(5).percentage(50f).build();
req.setPdfProgress(pdfProgress);
bookUpdateService.updateReadProgress(req);
verify(userBookProgressRepository).save(progress);
assertEquals(5, progress.getPdfProgress());
assertEquals(ReadStatus.READING, progress.getReadStatus());
assertEquals(50f, progress.getPdfProgressPercent());
}
@Test
void updateReadStatus_shouldUpdateExistingAndCreateNew() {
BookLoreUser user = mock(BookLoreUser.class);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(1L);
List<Long> bookIds = Arrays.asList(1L, 2L, 3L);
when(bookRepository.countByIdIn(bookIds)).thenReturn(3L);
Set<Long> existing = new HashSet<>(Arrays.asList(1L, 2L));
when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing);
BookLoreUserEntity userEntity = new BookLoreUserEntity();
when(userRepository.findById(1L)).thenReturn(Optional.of(userEntity));
List<BookStatusUpdateResponse> result = bookUpdateService.updateReadStatus(bookIds, "READ");
verify(userBookProgressRepository).bulkUpdateReadStatus(eq(1L), eq(new ArrayList<>(existing)), eq(ReadStatus.READ), any(), any());
verify(userBookProgressRepository).saveAll(anyList());
assertEquals(3, result.size());
assertEquals(ReadStatus.READ, result.get(0).getReadStatus());
}
@Test
void resetProgress_shouldCallBulkReset() {
BookLoreUser user = mock(BookLoreUser.class);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(1L);
List<Long> bookIds = Arrays.asList(1L, 2L);
when(bookRepository.countByIdIn(bookIds)).thenReturn(2L);
Set<Long> existing = new HashSet<>(bookIds);
when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing);
List<BookStatusUpdateResponse> result = bookUpdateService.resetProgress(bookIds, ResetProgressType.BOOKLORE);
verify(userBookProgressRepository).bulkResetBookloreProgress(eq(1L), eq(new ArrayList<>(bookIds)), any());
assertEquals(2, result.size());
}
@Test
void updatePersonalRating_shouldUpdateAndCreate() {
BookLoreUser user = mock(BookLoreUser.class);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(1L);
List<Long> bookIds = Arrays.asList(1L, 2L, 3L);
when(bookRepository.countByIdIn(bookIds)).thenReturn(3L);
Set<Long> existing = new HashSet<>(Arrays.asList(1L, 2L));
when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing);
BookLoreUserEntity userEntity = new BookLoreUserEntity();
when(userRepository.findById(1L)).thenReturn(Optional.of(userEntity));
List<PersonalRatingUpdateResponse> result = bookUpdateService.updatePersonalRating(bookIds, 5);
verify(userBookProgressRepository).bulkUpdatePersonalRating(eq(1L), eq(new ArrayList<>(existing)), eq(5));
verify(userBookProgressRepository).saveAll(anyList());
assertEquals(3, result.size());
assertEquals(5, result.get(0).getPersonalRating());
}
@Test
void resetPersonalRating_shouldUpdateExisting() {
BookLoreUser user = mock(BookLoreUser.class);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(1L);
List<Long> bookIds = Arrays.asList(1L, 2L);
when(bookRepository.countByIdIn(bookIds)).thenReturn(2L);
Set<Long> existing = new HashSet<>(bookIds);
when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing);
List<PersonalRatingUpdateResponse> result = bookUpdateService.resetPersonalRating(bookIds);
verify(userBookProgressRepository).bulkUpdatePersonalRating(eq(1L), eq(new ArrayList<>(bookIds)), isNull());
assertEquals(2, result.size());
assertNull(result.get(0).getPersonalRating());
}
@Test
void assignShelvesToBooks_shouldAssignAndReturnBooks() {
BookLoreUser user = mock(BookLoreUser.class);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(1L);
BookLoreUserEntity userEntity = new BookLoreUserEntity();
ShelfEntity shelf1 = new ShelfEntity(); shelf1.setId(10L);
ShelfEntity shelf2 = new ShelfEntity(); shelf2.setId(20L);
userEntity.setShelves(new HashSet<>(Arrays.asList(shelf1, shelf2)));
when(userRepository.findById(1L)).thenReturn(Optional.of(userEntity));
Set<Long> bookIds = new HashSet<>(Arrays.asList(1L, 2L));
Set<Long> assignIds = new HashSet<>(Collections.singletonList(10L));
Set<Long> unassignIds = new HashSet<>(Collections.singletonList(20L));
BookEntity bookEntity1 = spy(new BookEntity());
bookEntity1.setId(1L);
bookEntity1.setShelves(new HashSet<>());
LibraryPathEntity libraryPath1 = new LibraryPathEntity();
libraryPath1.setPath("/mock/path/1");
doReturn(libraryPath1).when(bookEntity1).getLibraryPath();
bookEntity1.setFileSubPath("sub1");
bookEntity1.setFileName("file1.pdf");
BookEntity bookEntity2 = spy(new BookEntity());
bookEntity2.setId(2L);
bookEntity2.setShelves(new HashSet<>());
LibraryPathEntity libraryPath2 = new LibraryPathEntity();
libraryPath2.setPath("/mock/path/2");
doReturn(libraryPath2).when(bookEntity2).getLibraryPath();
bookEntity2.setFileSubPath("sub2");
bookEntity2.setFileName("file2.pdf");
when(bookQueryService.findAllWithMetadataByIds(bookIds)).thenReturn(Arrays.asList(bookEntity1, bookEntity2));
ShelfEntity assignShelf = new ShelfEntity(); assignShelf.setId(10L);
when(shelfRepository.findAllById(assignIds)).thenReturn(Collections.singletonList(assignShelf));
Book mockBook = mock(Book.class);
when(bookMapper.toBook(any())).thenReturn(mockBook);
when(userProgressService.fetchUserProgress(eq(1L), anySet())).thenReturn(Collections.emptyMap());
List<Book> result = bookUpdateService.assignShelvesToBooks(bookIds, assignIds, unassignIds);
verify(bookRepository).saveAll(anyList());
assertEquals(2, result.size());
}
@Test
void assignShelvesToBooks_shouldThrowIfUnauthorized() {
BookLoreUser user = mock(BookLoreUser.class);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(1L);
BookLoreUserEntity userEntity = new BookLoreUserEntity();
ShelfEntity shelf1 = new ShelfEntity(); shelf1.setId(10L);
userEntity.setShelves(new HashSet<>(Collections.singletonList(shelf1)));
when(userRepository.findById(1L)).thenReturn(Optional.of(userEntity));
Set<Long> bookIds = new HashSet<>(Collections.singletonList(1L));
Set<Long> assignIds = new HashSet<>(Collections.singletonList(99L));
Set<Long> unassignIds = new HashSet<>();
assertThrows(APIException.class, () -> bookUpdateService.assignShelvesToBooks(bookIds, assignIds, unassignIds));
}
}