Introduce multi-format book support, including audiobooks (#2486)
* fix: support reading alternative book formats using bookType query param * feat: add streaming reader support for alternative EPUB formats * refactor: extract tabs section into MetadataTabsComponent * feat: implement per-file reading progress tracking * feat: add configurable format priority with cascading fallback * refactor: redesign library creator with single-page layout * refactor: unify reading progress into ReadingProgressService * refactor: improve delete options with clearer file format and book deletion * refactor: improve book format matching with normalization and fuzzy fallback * feat: add folder-based audiobook support with ZIP downloads and preparing state * fix: display unique format types in metadata viewer * refactor: auto-attach files to single book in folder during rescan * feat: implement folder-centric book file grouping with fuzzy matching * refactor: consolidate book grouping with organization mode support * fix: use folder hash for folder-based audiobooks in auto-attach * fix: delete only BookFileEntity on file removal, not entire book * fix: set folderBased flag and correct file size for auto-attached audiobook folders * fix: use count query to avoid lazy initialization in file delete handler * fix: preserve book metadata when file is moved by detecting hash match * fix: skip books with no files in restoration to avoid NPE * fix: round all progress percentages to one decimal place before sending to UI * style: improve library creator dialog spacing and layout * fix: migrate FOLDER_AS_BOOK to BOOK_PER_FOLDER for backwards compatibility * fix: FileMoveService now handles multi-file BookEntity properly * style: redesign metadata-picker and file-mover UI components * style: redesign file-naming-pattern UI and improve theme contrast * style: relax spacing in library-creator component * style: tighten directory-picker layout for consistency * fix: PathPatternResolver now respects folderBased flag for audiobooks * style: move checkmark column to left side and add pending status in file-mover * refactor: consolidate BookFileType into BookType and add audiobook styling * feat: show 'Continue Reading' button for in-progress books * fix: preserve dots in folder names during grouping and prevent duplicate attachments * style: reduce gap between download-all button and primary file section * style: shorten 'Continue Reading' button to 'Read' on mobile * feat: add DISK_TYPE config to disable file moves on network storage * style: standardize settings pages with shared styles and consistent spacing * style: revamp settings pages with modern card-based layouts * style: revamp OPDS, auth, and task management settings layouts * fix: update FileMoveService tests to include AppProperties parameter * fix: derive BookFileType from extension when uploading additional book files * feat: show format type and size in download button with dropdown for alternatives * feat: add audiobook streaming player with HTTP Range support * feat: add M4B chapter extraction and chapter navigation * feat: add audiobook bookmarks and sleep timer * refactor: split AudiobookReaderService into focused services * feat: add Media Session API for background audio playback * feat: display file extensions in format tags with distinct colors and add audiobook upload support * feat: require bookFileId for viewer settings API * fix: show split button for audiobooks with readable alternatives * feat: improve reading sessions table with book type badges and better formatting * feat: add audiobook play button in files tab * feat: use file extension for format display and meaningful tab values * feat: add extension field to BookFile DTO * feat: use extension field for book card format pill * fix: use mixed orientation for format priority drag-drop to support multi-line layout * feat: add attach book files feature to consolidate single-file books * fix: increase drag handle size for format priority chips * fix: add missing BookFileRepository mock to BookServiceDeleteTests * feat: add delete buttons to files tab and move shelf to other items menu * feat: add physical books support for cataloging books without digital files * refactor: redesign icon-picker component with improved styling * refactor: redesign metadata-picker component with improved layout and alignment * refactor: move Add Physical Book to top of library menu * refactor: use p-autoComplete for authors/categories in add-physical-book dialog * feat: add square cover search and display support for audiobooks * fix: navigate to first page when opening unread ebooks * fix: exclude API requests from service worker interception * feat: support fileless books with automatic file attachment * fix: bypass service worker for audiobook streaming requests * refactor: remove alphabetical filter sorting, default to count, limit filters to 100 --------- Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
@@ -7,7 +7,7 @@ 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.progress.ReadingProgressService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -37,6 +37,7 @@ class BookServiceDeleteTests {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
BookRepository bookRepository = Mockito.mock(BookRepository.class);
|
||||
BookFileRepository bookFileRepository = Mockito.mock(BookFileRepository.class);
|
||||
PdfViewerPreferencesRepository pdfViewerPreferencesRepository = Mockito.mock(PdfViewerPreferencesRepository.class);
|
||||
EbookViewerPreferenceRepository ebookViewerPreferenceRepository = Mockito.mock(EbookViewerPreferenceRepository.class);
|
||||
CbxViewerPreferencesRepository cbxViewerPreferencesRepository = Mockito.mock(CbxViewerPreferencesRepository.class);
|
||||
@@ -46,13 +47,14 @@ class BookServiceDeleteTests {
|
||||
UserBookProgressRepository userBookProgressRepository = Mockito.mock(UserBookProgressRepository.class);
|
||||
AuthenticationService authenticationService = Mockito.mock(AuthenticationService.class);
|
||||
BookQueryService bookQueryService = Mockito.mock(BookQueryService.class);
|
||||
UserProgressService userProgressService = Mockito.mock(UserProgressService.class);
|
||||
ReadingProgressService readingProgressService = Mockito.mock(ReadingProgressService.class);
|
||||
BookDownloadService bookDownloadService = Mockito.mock(BookDownloadService.class);
|
||||
MonitoringRegistrationService monitoringRegistrationService = Mockito.mock(MonitoringRegistrationService.class);
|
||||
BookUpdateService bookUpdateService = Mockito.mock(BookUpdateService.class);
|
||||
|
||||
bookService = new BookService(
|
||||
bookRepository,
|
||||
bookFileRepository,
|
||||
pdfViewerPreferencesRepository,
|
||||
cbxViewerPreferencesRepository,
|
||||
newPdfViewerPreferencesRepository,
|
||||
@@ -61,7 +63,7 @@ class BookServiceDeleteTests {
|
||||
userBookProgressRepository,
|
||||
authenticationService,
|
||||
bookQueryService,
|
||||
userProgressService,
|
||||
readingProgressService,
|
||||
bookDownloadService,
|
||||
monitoringRegistrationService,
|
||||
bookUpdateService,
|
||||
|
||||
@@ -48,7 +48,7 @@ class BookMapperTest {
|
||||
assertThat(dto.getLibraryName()).isEqualTo("Test Library");
|
||||
assertThat(dto.getLibraryPath()).isNotNull();
|
||||
assertThat(dto.getLibraryPath().getId()).isEqualTo(1L);
|
||||
assertThat(dto.getBookType()).isEqualTo(BookFileType.EPUB);
|
||||
assertThat(dto.getPrimaryFile().getBookType()).isEqualTo(BookFileType.EPUB);
|
||||
assertThat(dto.getAlternativeFormats()).isEmpty();
|
||||
assertThat(dto.getSupplementaryFiles()).isEmpty();
|
||||
|
||||
|
||||
-2
@@ -4,7 +4,6 @@ import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
@@ -39,7 +38,6 @@ class BookOpdsRepositoryDataJpaTest {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.name("Test Library")
|
||||
.icon("book")
|
||||
.scanMode(LibraryScanMode.FILE_AS_BOOK)
|
||||
.watch(false)
|
||||
.build();
|
||||
library = entityManager.persistAndFlush(library);
|
||||
|
||||
+16
-4
@@ -80,8 +80,12 @@ class BookMarkServiceTest {
|
||||
|
||||
@Test
|
||||
void createBookmark_Success() {
|
||||
CreateBookMarkRequest request = new CreateBookMarkRequest(bookId, "new-cfi", "New Bookmark");
|
||||
|
||||
CreateBookMarkRequest request = CreateBookMarkRequest.builder()
|
||||
.bookId(bookId)
|
||||
.cfi("new-cfi")
|
||||
.title("New Bookmark")
|
||||
.build();
|
||||
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(userDto);
|
||||
when(bookmarkProperties.getDefaultPriority()).thenReturn(3);
|
||||
when(bookMarkRepository.existsByCfiAndBookIdAndUserId("new-cfi", bookId, userId)).thenReturn(false);
|
||||
@@ -99,7 +103,11 @@ class BookMarkServiceTest {
|
||||
|
||||
@Test
|
||||
void createBookmark_Duplicate() {
|
||||
CreateBookMarkRequest request = new CreateBookMarkRequest(bookId, "new-cfi", "New Bookmark");
|
||||
CreateBookMarkRequest request = CreateBookMarkRequest.builder()
|
||||
.bookId(bookId)
|
||||
.cfi("new-cfi")
|
||||
.title("New Bookmark")
|
||||
.build();
|
||||
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(userDto);
|
||||
when(bookMarkRepository.existsByCfiAndBookIdAndUserId("new-cfi", bookId, userId)).thenReturn(true); // Duplicate exists
|
||||
@@ -110,7 +118,11 @@ class BookMarkServiceTest {
|
||||
|
||||
@Test
|
||||
void createBookmark_BookNotFound() {
|
||||
CreateBookMarkRequest request = new CreateBookMarkRequest(bookId, "new-cfi", "New Bookmark");
|
||||
CreateBookMarkRequest request = CreateBookMarkRequest.builder()
|
||||
.bookId(bookId)
|
||||
.cfi("new-cfi")
|
||||
.title("New Bookmark")
|
||||
.build();
|
||||
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(userDto);
|
||||
when(bookMarkRepository.existsByCfiAndBookIdAndUserId("new-cfi", bookId, userId)).thenReturn(false); // No duplicate
|
||||
|
||||
+409
@@ -0,0 +1,409 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import jakarta.servlet.ServletOutputStream;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class FileStreamingServiceTest {
|
||||
|
||||
private FileStreamingService fileStreamingService;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
Path testFile;
|
||||
byte[] testContent;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
fileStreamingService = new FileStreamingService();
|
||||
|
||||
// Create a test file with known content
|
||||
testContent = new byte[10000];
|
||||
for (int i = 0; i < testContent.length; i++) {
|
||||
testContent[i] = (byte) (i % 256);
|
||||
}
|
||||
testFile = tempDir.resolve("test.bin");
|
||||
Files.write(testFile, testContent);
|
||||
}
|
||||
|
||||
// ==================== streamWithRangeSupport - Full file tests ====================
|
||||
|
||||
@Test
|
||||
void streamWithRangeSupport_noRangeHeader_streamsFullFile() throws IOException {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
||||
|
||||
when(request.getHeader("Range")).thenReturn(null);
|
||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||
|
||||
fileStreamingService.streamWithRangeSupport(testFile, "application/octet-stream", request, response);
|
||||
|
||||
verify(response).setStatus(HttpServletResponse.SC_OK);
|
||||
verify(response).setContentLengthLong(testContent.length);
|
||||
verify(response).setHeader("Accept-Ranges", "bytes");
|
||||
verify(response).setContentType("application/octet-stream");
|
||||
assertArrayEquals(testContent, outputStream.toByteArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamWithRangeSupport_fileNotFound_sends404() throws IOException {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
|
||||
Path nonexistent = tempDir.resolve("nonexistent.bin");
|
||||
|
||||
fileStreamingService.streamWithRangeSupport(nonexistent, "audio/mp4", request, response);
|
||||
|
||||
verify(response).sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
|
||||
}
|
||||
|
||||
// ==================== streamWithRangeSupport - Range request tests ====================
|
||||
|
||||
@Test
|
||||
void streamWithRangeSupport_fullRange_streamsPartialContent() throws IOException {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
||||
|
||||
when(request.getHeader("Range")).thenReturn("bytes=0-99");
|
||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||
|
||||
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||
|
||||
verify(response).setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
|
||||
verify(response).setContentLengthLong(100);
|
||||
verify(response).setHeader("Content-Range", "bytes 0-99/" + testContent.length);
|
||||
|
||||
byte[] expected = new byte[100];
|
||||
System.arraycopy(testContent, 0, expected, 0, 100);
|
||||
assertArrayEquals(expected, outputStream.toByteArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamWithRangeSupport_openEndedRange_streamsToEnd() throws IOException {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
||||
|
||||
when(request.getHeader("Range")).thenReturn("bytes=9900-");
|
||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||
|
||||
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||
|
||||
verify(response).setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
|
||||
verify(response).setContentLengthLong(100);
|
||||
verify(response).setHeader("Content-Range", "bytes 9900-9999/" + testContent.length);
|
||||
|
||||
byte[] expected = new byte[100];
|
||||
System.arraycopy(testContent, 9900, expected, 0, 100);
|
||||
assertArrayEquals(expected, outputStream.toByteArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamWithRangeSupport_suffixRange_streamsLastNBytes() throws IOException {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
||||
|
||||
when(request.getHeader("Range")).thenReturn("bytes=-500");
|
||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||
|
||||
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||
|
||||
verify(response).setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
|
||||
verify(response).setContentLengthLong(500);
|
||||
verify(response).setHeader("Content-Range", "bytes 9500-9999/" + testContent.length);
|
||||
|
||||
byte[] expected = new byte[500];
|
||||
System.arraycopy(testContent, 9500, expected, 0, 500);
|
||||
assertArrayEquals(expected, outputStream.toByteArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamWithRangeSupport_invalidRange_sends416() throws IOException {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
|
||||
when(request.getHeader("Range")).thenReturn("bytes=50000-60000"); // Beyond file size
|
||||
|
||||
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||
|
||||
verify(response).setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
|
||||
verify(response).setHeader("Content-Range", "bytes */" + testContent.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamWithRangeSupport_rangeEndBeyondFileSize_clampsToFileSize() throws IOException {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
||||
|
||||
when(request.getHeader("Range")).thenReturn("bytes=9990-99999"); // End beyond file
|
||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||
|
||||
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||
|
||||
verify(response).setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
|
||||
verify(response).setContentLengthLong(10); // 9990 to 9999
|
||||
verify(response).setHeader("Content-Range", "bytes 9990-9999/" + testContent.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamWithRangeSupport_setsCacheControlHeader() throws IOException {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
||||
|
||||
when(request.getHeader("Range")).thenReturn(null);
|
||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||
|
||||
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||
|
||||
verify(response).setHeader("Cache-Control", "public, max-age=3600");
|
||||
}
|
||||
|
||||
// ==================== parseRange tests ====================
|
||||
|
||||
@Test
|
||||
void parseRange_fullRange_parsesCorrectly() {
|
||||
var result = fileStreamingService.parseRange("bytes=100-199", 1000);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(100, result.start());
|
||||
assertEquals(199, result.end());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRange_openEndedRange_parsesCorrectly() {
|
||||
var result = fileStreamingService.parseRange("bytes=500-", 1000);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(500, result.start());
|
||||
assertEquals(999, result.end());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRange_suffixRange_parsesCorrectly() {
|
||||
var result = fileStreamingService.parseRange("bytes=-200", 1000);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(800, result.start());
|
||||
assertEquals(999, result.end());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRange_suffixRangeLargerThanFile_startsAtZero() {
|
||||
var result = fileStreamingService.parseRange("bytes=-2000", 1000);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(0, result.start());
|
||||
assertEquals(999, result.end());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRange_clampsEndToFileSize() {
|
||||
var result = fileStreamingService.parseRange("bytes=900-2000", 1000);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(900, result.start());
|
||||
assertEquals(999, result.end());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"invalid",
|
||||
"bytes",
|
||||
"bytes=",
|
||||
"bytes=abc-def",
|
||||
"bytes=100-50", // End before start
|
||||
"characters=0-100"
|
||||
})
|
||||
void parseRange_invalidFormats_returnsNull(String rangeHeader) {
|
||||
var result = fileStreamingService.parseRange(rangeHeader, 1000);
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRange_startBeyondFileSize_returnsNull() {
|
||||
var result = fileStreamingService.parseRange("bytes=2000-3000", 1000);
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRange_multipleRanges_usesFirstOnly() {
|
||||
var result = fileStreamingService.parseRange("bytes=0-99, 200-299", 1000);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(0, result.start());
|
||||
assertEquals(99, result.end());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRange_withLeadingTrailingWhitespace_parsesCorrectly() {
|
||||
// Leading/trailing whitespace around the range spec is trimmed
|
||||
var result = fileStreamingService.parseRange("bytes=100-199", 1000);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(100, result.start());
|
||||
assertEquals(199, result.end());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRange_withWhitespaceAroundComma_parsesFirstRange() {
|
||||
var result = fileStreamingService.parseRange("bytes= 100-199 , 300-399", 1000);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(100, result.start());
|
||||
assertEquals(199, result.end());
|
||||
}
|
||||
|
||||
// ==================== isClientDisconnect tests ====================
|
||||
|
||||
@Test
|
||||
void isClientDisconnect_socketTimeoutException_returnsTrue() {
|
||||
assertTrue(fileStreamingService.isClientDisconnect(new SocketTimeoutException("timeout")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"Connection reset",
|
||||
"Broken pipe",
|
||||
"connection was aborted",
|
||||
"An established connection was aborted",
|
||||
"SocketTimeout occurred",
|
||||
"Connection timed out"
|
||||
})
|
||||
void isClientDisconnect_knownMessages_returnsTrue(String message) {
|
||||
assertTrue(fileStreamingService.isClientDisconnect(new IOException(message)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isClientDisconnect_unknownMessage_returnsFalse() {
|
||||
assertFalse(fileStreamingService.isClientDisconnect(new IOException("Unknown error")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isClientDisconnect_nullMessage_checksClassName() {
|
||||
// Create an IOException with null message but class name containing "Timeout"
|
||||
IOException timeoutException = new SocketTimeoutException();
|
||||
assertTrue(fileStreamingService.isClientDisconnect(timeoutException));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isClientDisconnect_regularIOException_returnsFalse() {
|
||||
assertFalse(fileStreamingService.isClientDisconnect(new IOException("Read failed")));
|
||||
}
|
||||
|
||||
// ==================== Edge cases ====================
|
||||
|
||||
@Test
|
||||
void streamWithRangeSupport_emptyFile_handlesCorrectly() throws IOException {
|
||||
Path emptyFile = tempDir.resolve("empty.bin");
|
||||
Files.createFile(emptyFile);
|
||||
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
||||
|
||||
when(request.getHeader("Range")).thenReturn(null);
|
||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||
|
||||
// This should handle empty file gracefully - the stream will be empty
|
||||
fileStreamingService.streamWithRangeSupport(emptyFile, "audio/mp4", request, response);
|
||||
|
||||
verify(response).setStatus(HttpServletResponse.SC_OK);
|
||||
verify(response).setContentLengthLong(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamWithRangeSupport_singleByteRange_streamsOneByte() throws IOException {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
||||
|
||||
when(request.getHeader("Range")).thenReturn("bytes=50-50");
|
||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||
|
||||
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||
|
||||
verify(response).setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
|
||||
verify(response).setContentLengthLong(1);
|
||||
assertEquals(1, outputStream.size());
|
||||
assertEquals(testContent[50], outputStream.toByteArray()[0]);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"0, 0",
|
||||
"0, 9999",
|
||||
"5000, 5000",
|
||||
"9999, 9999"
|
||||
})
|
||||
void streamWithRangeSupport_variousValidRanges_streamsCorrectContent(int start, int end) throws IOException {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
||||
|
||||
when(request.getHeader("Range")).thenReturn("bytes=" + start + "-" + end);
|
||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||
|
||||
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||
|
||||
int expectedLength = end - start + 1;
|
||||
assertEquals(expectedLength, outputStream.size());
|
||||
|
||||
byte[] expected = new byte[expectedLength];
|
||||
System.arraycopy(testContent, start, expected, 0, expectedLength);
|
||||
assertArrayEquals(expected, outputStream.toByteArray());
|
||||
}
|
||||
|
||||
// Helper method to create a mock ServletOutputStream
|
||||
private ServletOutputStream createServletOutputStream(ByteArrayOutputStream outputStream) {
|
||||
return new ServletOutputStream() {
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setWriteListener(jakarta.servlet.WriteListener writeListener) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(int b) throws IOException {
|
||||
outputStream.write(b);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] b, int off, int len) throws IOException {
|
||||
outputStream.write(b, off, len);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+13
-11
@@ -11,7 +11,7 @@ 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.service.progress.ReadingProgressService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -63,7 +63,7 @@ class BookServiceTest {
|
||||
@Mock
|
||||
private BookQueryService bookQueryService;
|
||||
@Mock
|
||||
private UserProgressService userProgressService;
|
||||
private ReadingProgressService readingProgressService;
|
||||
@Mock
|
||||
private BookDownloadService bookDownloadService;
|
||||
@Mock
|
||||
@@ -89,9 +89,9 @@ class BookServiceTest {
|
||||
|
||||
@Test
|
||||
void getBookDTOs_adminUser_returnsBooksWithProgress() {
|
||||
Book book = Book.builder().id(1L).bookType(BookFileType.PDF).shelves(Set.of()).build();
|
||||
Book book = Book.builder().id(1L).primaryFile(BookFile.builder().bookType(BookFileType.PDF).build()).shelves(Set.of()).build();
|
||||
when(bookQueryService.getAllBooks(anyBoolean())).thenReturn(List.of(book));
|
||||
when(userProgressService.fetchUserProgress(anyLong(), anySet())).thenReturn(Map.of(1L, new UserBookProgressEntity()));
|
||||
when(readingProgressService.fetchUserProgress(anyLong(), anySet())).thenReturn(Map.of(1L, new UserBookProgressEntity()));
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
|
||||
List<Book> result = bookService.getBookDTOs(true);
|
||||
@@ -114,8 +114,8 @@ class BookServiceTest {
|
||||
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(readingProgressService.fetchUserProgress(anyLong(), anySet())).thenReturn(Map.of(2L, new UserBookProgressEntity()));
|
||||
Book mappedBook = Book.builder().id(2L).primaryFile(BookFile.builder().bookType(BookFileType.EPUB).build()).metadata(BookMetadata.builder().build()).build();
|
||||
when(bookMapper.toBook(entity)).thenReturn(mappedBook);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
|
||||
@@ -143,7 +143,7 @@ class BookServiceTest {
|
||||
entity.setLibrary(library);
|
||||
when(bookRepository.findByIdWithBookFiles(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();
|
||||
Book mappedBook = Book.builder().id(3L).primaryFile(BookFile.builder().bookType(BookFileType.PDF).build()).metadata(BookMetadata.builder().build()).shelves(Set.of()).build();
|
||||
when(bookMapper.toBook(entity)).thenReturn(mappedBook);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
|
||||
@@ -167,6 +167,7 @@ class BookServiceTest {
|
||||
BookEntity entity = new BookEntity();
|
||||
entity.setId(4L);
|
||||
BookFileEntity primaryFile = new BookFileEntity();
|
||||
primaryFile.setId(1L);
|
||||
primaryFile.setBook(entity);
|
||||
primaryFile.setBookType(BookFileType.EPUB);
|
||||
entity.setBookFiles(List.of(primaryFile));
|
||||
@@ -186,7 +187,7 @@ class BookServiceTest {
|
||||
when(ebookViewerPreferenceRepository.findByBookIdAndUserId(4L, testUser.getId())).thenReturn(Optional.of(epubPref));
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
|
||||
BookViewerSettings settings = bookService.getBookViewerSetting(4L);
|
||||
BookViewerSettings settings = bookService.getBookViewerSetting(4L, 1L);
|
||||
|
||||
assertNotNull(settings.getEbookSettings());
|
||||
assertEquals("Arial", settings.getEbookSettings().getFontFamily());
|
||||
@@ -207,12 +208,13 @@ class BookServiceTest {
|
||||
BookEntity entity = new BookEntity();
|
||||
entity.setId(5L);
|
||||
BookFileEntity primaryFile = new BookFileEntity();
|
||||
primaryFile.setId(1L);
|
||||
primaryFile.setBook(entity);
|
||||
primaryFile.setBookType(null);
|
||||
entity.setBookFiles(List.of(primaryFile));
|
||||
when(bookRepository.findByIdWithBookFiles(5L)).thenReturn(Optional.of(entity));
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
assertThrows(APIException.class, () -> bookService.getBookViewerSetting(5L));
|
||||
assertThrows(APIException.class, () -> bookService.getBookViewerSetting(5L, 1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -223,10 +225,10 @@ class BookServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateReadProgress_delegatesToUpdateService() {
|
||||
void updateReadProgress_delegatesToReadingProgressService() {
|
||||
ReadProgressRequest req = new ReadProgressRequest();
|
||||
bookService.updateReadProgress(req);
|
||||
verify(bookUpdateService).updateReadProgress(req);
|
||||
verify(readingProgressService).updateReadProgress(req);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+5
-130
@@ -4,18 +4,13 @@ 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 com.adityachandel.booklore.service.progress.ReadingProgressService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
@@ -50,9 +45,7 @@ class BookUpdateServiceTest {
|
||||
@Mock
|
||||
private BookQueryService bookQueryService;
|
||||
@Mock
|
||||
private UserProgressService userProgressService;
|
||||
@Mock
|
||||
private KoboReadingStateService koboReadingStateService;
|
||||
private ReadingProgressService readingProgressService;
|
||||
@Mock
|
||||
private EbookViewerPreferenceRepository ebookViewerPreferenceRepository;
|
||||
|
||||
@@ -73,8 +66,7 @@ class BookUpdateServiceTest {
|
||||
userBookProgressRepository,
|
||||
authenticationService,
|
||||
bookQueryService,
|
||||
userProgressService,
|
||||
koboReadingStateService,
|
||||
readingProgressService,
|
||||
ebookViewerPreferenceRepository
|
||||
);
|
||||
}
|
||||
@@ -175,70 +167,6 @@ class BookUpdateServiceTest {
|
||||
assertThrows(APIException.class, () -> bookUpdateService.updateBookViewerSetting(bookId, settings));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateReadProgress_epub_shouldUpdateProgress() {
|
||||
long bookId = 1L;
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(bookId);
|
||||
BookFileEntity primaryFile = new BookFileEntity();
|
||||
primaryFile.setBook(book);
|
||||
primaryFile.setBookType(BookFileType.EPUB);
|
||||
book.setBookFiles(List.of(primaryFile));
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(bookRepository.findByIdWithBookFiles(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);
|
||||
BookFileEntity primaryFile = new BookFileEntity();
|
||||
primaryFile.setBook(book);
|
||||
primaryFile.setBookType(BookFileType.PDF);
|
||||
book.setBookFiles(List.of(primaryFile));
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(bookRepository.findByIdWithBookFiles(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);
|
||||
@@ -280,60 +208,6 @@ class BookUpdateServiceTest {
|
||||
assertThrows(APIException.class, () -> bookUpdateService.updateReadStatus(bookIds, "READ"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetProgress_shouldCallBulkReset() {
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
when(user.getId()).thenReturn(1L);
|
||||
|
||||
BookLoreUser.UserPermissions permissions = mock(BookLoreUser.UserPermissions.class);
|
||||
when(user.getPermissions()).thenReturn(permissions);
|
||||
when(permissions.isCanBulkResetBookloreReadProgress()).thenReturn(true);
|
||||
|
||||
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 resetProgress_shouldThrowIfNoBulkPermission() {
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
when(user.getId()).thenReturn(1L);
|
||||
|
||||
BookLoreUser.UserPermissions permissions = mock(BookLoreUser.UserPermissions.class);
|
||||
when(user.getPermissions()).thenReturn(permissions);
|
||||
when(permissions.isCanBulkResetBookloreReadProgress()).thenReturn(false);
|
||||
|
||||
List<Long> bookIds = Arrays.asList(1L, 2L);
|
||||
when(bookRepository.countByIdIn(bookIds)).thenReturn(2L);
|
||||
|
||||
assertThrows(APIException.class, () -> bookUpdateService.resetProgress(bookIds, ResetProgressType.BOOKLORE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetProgress_shouldAllowSingleBookWithoutPermission() {
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
when(user.getId()).thenReturn(1L);
|
||||
|
||||
BookLoreUser.UserPermissions permissions = mock(BookLoreUser.UserPermissions.class);
|
||||
when(user.getPermissions()).thenReturn(permissions);
|
||||
when(permissions.isCanBulkResetBookloreReadProgress()).thenReturn(false);
|
||||
|
||||
List<Long> bookIds = Collections.singletonList(1L);
|
||||
when(bookRepository.countByIdIn(bookIds)).thenReturn(1L);
|
||||
Set<Long> existing = new HashSet<>(bookIds);
|
||||
when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing);
|
||||
|
||||
assertDoesNotThrow(() -> bookUpdateService.resetProgress(bookIds, ResetProgressType.BOOKLORE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateReadStatus_shouldAllowSingleBookWithoutPermission() {
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
@@ -442,7 +316,8 @@ class BookUpdateServiceTest {
|
||||
Book mockBook = mock(Book.class);
|
||||
when(bookMapper.toBook(any())).thenReturn(mockBook);
|
||||
|
||||
when(userProgressService.fetchUserProgress(eq(1L), anySet())).thenReturn(Collections.emptyMap());
|
||||
when(readingProgressService.fetchUserProgress(eq(1L), anySet())).thenReturn(Collections.emptyMap());
|
||||
when(readingProgressService.fetchUserFileProgress(eq(1L), anySet())).thenReturn(Collections.emptyMap());
|
||||
|
||||
List<Book> result = bookUpdateService.assignShelvesToBooks(bookIds, assignIds, unassignIds);
|
||||
verify(bookRepository).saveAll(anyList());
|
||||
|
||||
+245
-138
@@ -1,12 +1,15 @@
|
||||
package com.adityachandel.booklore.service.file;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.LibraryMapper;
|
||||
import com.adityachandel.booklore.model.dto.FileMoveResult;
|
||||
import com.adityachandel.booklore.model.dto.Library;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
@@ -14,191 +17,295 @@ import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import jakarta.persistence.EntityManager;
|
||||
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.InOrder;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anySet;
|
||||
import static org.mockito.Mockito.doNothing;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class FileMoveServiceOrderingTest {
|
||||
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
@Mock
|
||||
private BookAdditionalFileRepository bookFileRepository;
|
||||
@Mock
|
||||
private LibraryRepository libraryRepository;
|
||||
@Mock
|
||||
private FileMoveHelper fileMoveHelper;
|
||||
@Mock
|
||||
private MonitoringRegistrationService monitoringRegistrationService;
|
||||
@Mock
|
||||
private LibraryMapper libraryMapper;
|
||||
@Mock
|
||||
private BookMapper bookMapper;
|
||||
@Mock
|
||||
private NotificationService notificationService;
|
||||
@Mock
|
||||
private EntityManager entityManager;
|
||||
@Mock private AppProperties appProperties;
|
||||
@Mock private BookRepository bookRepository;
|
||||
@Mock private BookAdditionalFileRepository bookFileRepository;
|
||||
@Mock private LibraryRepository libraryRepository;
|
||||
@Mock private FileMoveHelper fileMoveHelper;
|
||||
@Mock private MonitoringRegistrationService monitoringRegistrationService;
|
||||
@Mock private LibraryMapper libraryMapper;
|
||||
@Mock private BookMapper bookMapper;
|
||||
@Mock private NotificationService notificationService;
|
||||
@Mock private EntityManager entityManager;
|
||||
|
||||
private TestableFileMoveService fileMoveService;
|
||||
private FileMoveService service;
|
||||
private LibraryEntity library;
|
||||
private LibraryPathEntity libraryPath;
|
||||
|
||||
private BookEntity bookEntity;
|
||||
private Path expectedFilePath;
|
||||
|
||||
// Subclass to mock sleep
|
||||
static class TestableFileMoveService extends FileMoveService {
|
||||
public TestableFileMoveService(BookRepository bookRepository, BookAdditionalFileRepository bookFileRepository, LibraryRepository libraryRepository, FileMoveHelper fileMoveHelper, MonitoringRegistrationService monitoringRegistrationService, LibraryMapper libraryMapper, BookMapper bookMapper, NotificationService notificationService, EntityManager entityManager) {
|
||||
super(bookRepository, bookFileRepository, libraryRepository, fileMoveHelper, monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager);
|
||||
TestableFileMoveService(AppProperties appProperties, BookRepository bookRepository, BookAdditionalFileRepository bookFileRepository,
|
||||
LibraryRepository libraryRepository, FileMoveHelper fileMoveHelper,
|
||||
MonitoringRegistrationService monitoringRegistrationService, LibraryMapper libraryMapper,
|
||||
BookMapper bookMapper, NotificationService notificationService, EntityManager entityManager) {
|
||||
super(appProperties, bookRepository, bookFileRepository, libraryRepository, fileMoveHelper,
|
||||
monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void sleep(long millis) {
|
||||
// No-op for test, but can be verified by spy
|
||||
// No-op
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
fileMoveService = spy(new TestableFileMoveService(
|
||||
bookRepository, bookFileRepository, libraryRepository, fileMoveHelper, monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager));
|
||||
void setUp() {
|
||||
when(appProperties.getDiskType()).thenReturn("LOCAL");
|
||||
service = spy(new TestableFileMoveService(appProperties, bookRepository, bookFileRepository, libraryRepository,
|
||||
fileMoveHelper, monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager));
|
||||
|
||||
LibraryEntity library = new LibraryEntity();
|
||||
library.setId(42L);
|
||||
library = new LibraryEntity();
|
||||
library.setId(1L);
|
||||
|
||||
LibraryPathEntity libraryPath = new LibraryPathEntity();
|
||||
libraryPath.setId(77L);
|
||||
libraryPath.setPath("/library/root");
|
||||
libraryPath = new LibraryPathEntity();
|
||||
libraryPath.setId(10L);
|
||||
libraryPath.setPath("/library");
|
||||
libraryPath.setLibrary(library);
|
||||
library.setLibraryPaths(List.of(libraryPath));
|
||||
}
|
||||
|
||||
bookEntity = new BookEntity();
|
||||
bookEntity.setId(999L);
|
||||
bookEntity.setLibrary(library);
|
||||
bookEntity.setLibraryPath(libraryPath);
|
||||
var primaryFile = new com.adityachandel.booklore.model.entity.BookFileEntity();
|
||||
primaryFile.setBook(bookEntity);
|
||||
primaryFile.setFileSubPath("SciFi");
|
||||
primaryFile.setFileName("Original.epub");
|
||||
bookEntity.setBookFiles(java.util.List.of(primaryFile));
|
||||
private BookEntity createBook() {
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(100L);
|
||||
book.setLibrary(library);
|
||||
book.setLibraryPath(libraryPath);
|
||||
|
||||
expectedFilePath = Paths.get(libraryPath.getPath(), primaryFile.getFileSubPath(), "Renamed.epub");
|
||||
BookFileEntity file = new BookFileEntity();
|
||||
file.setId(1L);
|
||||
file.setBook(book);
|
||||
file.setFileName("Book.epub");
|
||||
file.setFileSubPath("path");
|
||||
file.setBookFormat(true);
|
||||
file.setBookType(BookFileType.EPUB);
|
||||
|
||||
when(fileMoveHelper.getFileNamingPattern(library)).thenReturn("{title}");
|
||||
when(fileMoveHelper.generateNewFilePath(bookEntity, libraryPath, "{title}")).thenReturn(expectedFilePath);
|
||||
when(fileMoveHelper.extractSubPath(expectedFilePath, libraryPath)).thenReturn(primaryFile.getFileSubPath());
|
||||
doNothing().when(fileMoveHelper).moveFile(any(Path.class), any(Path.class));
|
||||
doNothing().when(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(Path.class), anySet());
|
||||
book.setBookFiles(new ArrayList<>(List.of(file)));
|
||||
return book;
|
||||
}
|
||||
|
||||
private void mockStandardBehavior(BookEntity book, Path targetPath) throws IOException {
|
||||
when(fileMoveHelper.getFileNamingPattern(any())).thenReturn("{title}");
|
||||
when(fileMoveHelper.generateNewFilePath(eq(book), any(LibraryPathEntity.class), anyString())).thenReturn(targetPath);
|
||||
when(fileMoveHelper.generateNewFilePath(eq(book), any(BookFileEntity.class), any(LibraryPathEntity.class), anyString()))
|
||||
.thenReturn(targetPath);
|
||||
when(fileMoveHelper.extractSubPath(any(), any())).thenReturn("new/path");
|
||||
when(fileMoveHelper.validateSourceExists(any(), anyBoolean())).thenReturn(true);
|
||||
when(fileMoveHelper.moveFileWithBackup(any())).thenAnswer(inv -> ((Path) inv.getArgument(0)).resolveSibling("temp"));
|
||||
doNothing().when(fileMoveHelper).commitMove(any(), any());
|
||||
doNothing().when(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(), anySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
void moveSingleFile_guaranteesCorrectOrderOfOperations_WhenMonitored() throws Exception {
|
||||
// Arrange
|
||||
when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(true);
|
||||
when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Set.of(Paths.get("/library/root")));
|
||||
|
||||
Library libraryDto = Library.builder().watch(true).build();
|
||||
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(libraryDto);
|
||||
@DisplayName("moveSingleFile: commits files before updating database")
|
||||
void commitsBeforeDatabaseUpdate() throws IOException {
|
||||
BookEntity book = createBook();
|
||||
Path target = Paths.get("/library/new/path/NewName.epub");
|
||||
|
||||
// Act
|
||||
FileMoveResult result = fileMoveService.moveSingleFile(bookEntity);
|
||||
mockStandardBehavior(book, target);
|
||||
when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false);
|
||||
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet());
|
||||
|
||||
// Assert
|
||||
assertTrue(result.isMoved());
|
||||
FileMoveResult result = service.moveSingleFile(book);
|
||||
|
||||
InOrder inOrder = inOrder(monitoringRegistrationService, fileMoveHelper, fileMoveService);
|
||||
assertThat(result.isMoved()).isTrue();
|
||||
|
||||
// 1. Unregister library
|
||||
inOrder.verify(fileMoveHelper).unregisterLibrary(42L);
|
||||
InOrder inOrder = inOrder(fileMoveHelper, bookFileRepository);
|
||||
inOrder.verify(fileMoveHelper).moveFileWithBackup(any());
|
||||
inOrder.verify(fileMoveHelper).commitMove(any(), any());
|
||||
inOrder.verify(bookFileRepository).updateFileNameAndSubPath(anyLong(), anyString(), anyString());
|
||||
}
|
||||
|
||||
// 2. Wait for initial events to drain (before move)
|
||||
@Test
|
||||
@DisplayName("moveSingleFile: validates sources before staging")
|
||||
void validatesBeforeStaging() throws IOException {
|
||||
BookEntity book = createBook();
|
||||
Path target = Paths.get("/library/new/path/NewName.epub");
|
||||
|
||||
mockStandardBehavior(book, target);
|
||||
when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false);
|
||||
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet());
|
||||
|
||||
service.moveSingleFile(book);
|
||||
|
||||
InOrder inOrder = inOrder(fileMoveHelper);
|
||||
inOrder.verify(fileMoveHelper).validateSourceExists(any(), anyBoolean());
|
||||
inOrder.verify(fileMoveHelper).moveFileWithBackup(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("moveSingleFile: when monitored - unregisters before move, registers after")
|
||||
void monitoredOrderUnregisterMoveRegister() throws IOException {
|
||||
BookEntity book = createBook();
|
||||
Path target = Paths.get("/library/new/path/NewName.epub");
|
||||
|
||||
mockStandardBehavior(book, target);
|
||||
when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true);
|
||||
when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library")));
|
||||
Library dto = Library.builder().build();
|
||||
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto);
|
||||
|
||||
FileMoveResult result = service.moveSingleFile(book);
|
||||
|
||||
assertThat(result.isMoved()).isTrue();
|
||||
|
||||
InOrder inOrder = inOrder(fileMoveHelper, monitoringRegistrationService, service);
|
||||
inOrder.verify(fileMoveHelper).unregisterLibrary(1L);
|
||||
inOrder.verify(monitoringRegistrationService).waitForEventsDrainedByPaths(anySet(), anyLong());
|
||||
|
||||
// 3. Perform the move
|
||||
inOrder.verify(fileMoveHelper).moveFile(any(Path.class), any(Path.class));
|
||||
|
||||
// 4. Perform cleanup
|
||||
inOrder.verify(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(Path.class), anySet());
|
||||
|
||||
// 5. CRITICAL: Sleep/Wait for events generated by move/cleanup to drain *before* re-registering
|
||||
inOrder.verify(fileMoveService).sleep(anyLong());
|
||||
|
||||
// 6. Register library *last*
|
||||
inOrder.verify(monitoringRegistrationService).registerLibrary(libraryDto);
|
||||
}
|
||||
|
||||
@Test
|
||||
void moveSingleFile_guaranteesCorrectOrderOfOperations_WhenStatusNotMonitoredButHasPaths() throws Exception {
|
||||
// Arrange: status says FALSE, but getPaths returns paths. Should still unregister.
|
||||
when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(false);
|
||||
when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Set.of(Paths.get("/library/root")));
|
||||
|
||||
Library libraryDto = Library.builder().watch(true).build();
|
||||
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(libraryDto);
|
||||
|
||||
// Act
|
||||
FileMoveResult result = fileMoveService.moveSingleFile(bookEntity);
|
||||
|
||||
// Assert
|
||||
assertTrue(result.isMoved());
|
||||
|
||||
InOrder inOrder = inOrder(monitoringRegistrationService, fileMoveHelper, fileMoveService);
|
||||
|
||||
// 1. Unregister library
|
||||
inOrder.verify(fileMoveHelper).unregisterLibrary(42L);
|
||||
|
||||
// 2. Wait for initial events to drain
|
||||
inOrder.verify(monitoringRegistrationService).waitForEventsDrainedByPaths(anySet(), anyLong());
|
||||
|
||||
// 3. Move
|
||||
inOrder.verify(fileMoveHelper).moveFile(any(Path.class), any(Path.class));
|
||||
|
||||
// 4. Sleep
|
||||
inOrder.verify(fileMoveService).sleep(anyLong());
|
||||
|
||||
// 5. Register
|
||||
inOrder.verify(monitoringRegistrationService).registerLibrary(libraryDto);
|
||||
inOrder.verify(fileMoveHelper).moveFileWithBackup(any());
|
||||
inOrder.verify(fileMoveHelper).commitMove(any(), any());
|
||||
inOrder.verify(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(), anySet());
|
||||
inOrder.verify(service).sleep(anyLong());
|
||||
inOrder.verify(monitoringRegistrationService).registerLibrary(dto);
|
||||
}
|
||||
|
||||
@Test
|
||||
void moveSingleFile_skipsMonitoringOps_WhenNotMonitoredAndNoPaths() throws Exception {
|
||||
// Arrange
|
||||
when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(false);
|
||||
when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Collections.emptySet());
|
||||
@DisplayName("moveSingleFile: when not monitored - no monitoring calls")
|
||||
void notMonitoredSkipsMonitoringCalls() throws IOException {
|
||||
BookEntity book = createBook();
|
||||
Path target = Paths.get("/library/new/path/NewName.epub");
|
||||
|
||||
// Act
|
||||
FileMoveResult result = fileMoveService.moveSingleFile(bookEntity);
|
||||
mockStandardBehavior(book, target);
|
||||
when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false);
|
||||
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet());
|
||||
|
||||
// Assert
|
||||
assertTrue(result.isMoved());
|
||||
FileMoveResult result = service.moveSingleFile(book);
|
||||
|
||||
// Verify NO unregister/register happens
|
||||
assertThat(result.isMoved()).isTrue();
|
||||
verify(fileMoveHelper, never()).unregisterLibrary(anyLong());
|
||||
verify(monitoringRegistrationService, never()).waitForEventsDrainedByPaths(anySet(), anyLong());
|
||||
|
||||
// Move happens
|
||||
verify(fileMoveHelper).moveFile(any(Path.class), any(Path.class));
|
||||
|
||||
// NO sleep
|
||||
verify(fileMoveService, never()).sleep(anyLong());
|
||||
|
||||
// NO register
|
||||
verify(monitoringRegistrationService, never()).registerLibrary(any());
|
||||
verify(service, never()).sleep(anyLong());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("moveSingleFile: cleans up directories after database update")
|
||||
void cleansUpAfterDatabaseUpdate() throws IOException {
|
||||
BookEntity book = createBook();
|
||||
Path target = Paths.get("/library/new/path/NewName.epub");
|
||||
|
||||
mockStandardBehavior(book, target);
|
||||
when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false);
|
||||
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet());
|
||||
|
||||
service.moveSingleFile(book);
|
||||
|
||||
InOrder inOrder = inOrder(bookFileRepository, fileMoveHelper);
|
||||
inOrder.verify(bookFileRepository).updateFileNameAndSubPath(anyLong(), anyString(), anyString());
|
||||
inOrder.verify(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(), anySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("moveSingleFile: all files staged before any commits")
|
||||
void allFilesStagedBeforeCommits() throws IOException {
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(100L);
|
||||
book.setLibrary(library);
|
||||
book.setLibraryPath(libraryPath);
|
||||
|
||||
BookFileEntity file1 = new BookFileEntity();
|
||||
file1.setId(1L);
|
||||
file1.setBook(book);
|
||||
file1.setFileName("Book.epub");
|
||||
file1.setFileSubPath("path");
|
||||
file1.setBookFormat(true);
|
||||
|
||||
BookFileEntity file2 = new BookFileEntity();
|
||||
file2.setId(2L);
|
||||
file2.setBook(book);
|
||||
file2.setFileName("Book.pdf");
|
||||
file2.setFileSubPath("path");
|
||||
file2.setBookFormat(true);
|
||||
file2.setBookType(BookFileType.PDF);
|
||||
|
||||
book.setBookFiles(new ArrayList<>(List.of(file1, file2)));
|
||||
|
||||
Path target = Paths.get("/library/new/path/NewName.epub");
|
||||
mockStandardBehavior(book, target);
|
||||
when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false);
|
||||
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet());
|
||||
|
||||
service.moveSingleFile(book);
|
||||
|
||||
InOrder inOrder = inOrder(fileMoveHelper);
|
||||
// Both files staged first
|
||||
inOrder.verify(fileMoveHelper, times(2)).moveFileWithBackup(any());
|
||||
// Then both committed
|
||||
inOrder.verify(fileMoveHelper, times(2)).commitMove(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("moveSingleFile: rollback happens on commit failure")
|
||||
void rollbackOnCommitFailure() throws IOException {
|
||||
BookEntity book = createBook();
|
||||
Path target = Paths.get("/library/new/path/NewName.epub");
|
||||
|
||||
mockStandardBehavior(book, target);
|
||||
doThrow(new IOException("fail")).when(fileMoveHelper).commitMove(any(), any());
|
||||
when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false);
|
||||
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet());
|
||||
|
||||
service.moveSingleFile(book);
|
||||
|
||||
InOrder inOrder = inOrder(fileMoveHelper);
|
||||
inOrder.verify(fileMoveHelper).moveFileWithBackup(any());
|
||||
inOrder.verify(fileMoveHelper).commitMove(any(), any());
|
||||
inOrder.verify(fileMoveHelper).rollbackMove(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("moveSingleFile: database not updated when commit fails")
|
||||
void noDatabaseUpdateOnCommitFailure() throws IOException {
|
||||
BookEntity book = createBook();
|
||||
Path target = Paths.get("/library/new/path/NewName.epub");
|
||||
|
||||
mockStandardBehavior(book, target);
|
||||
doThrow(new IOException("fail")).when(fileMoveHelper).commitMove(any(), any());
|
||||
when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false);
|
||||
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet());
|
||||
|
||||
service.moveSingleFile(book);
|
||||
|
||||
verify(bookFileRepository, never()).updateFileNameAndSubPath(anyLong(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("moveSingleFile: library re-registered even on failure")
|
||||
void libraryReRegisteredOnFailure() throws IOException {
|
||||
BookEntity book = createBook();
|
||||
Path target = Paths.get("/library/new/path/NewName.epub");
|
||||
|
||||
mockStandardBehavior(book, target);
|
||||
doThrow(new IOException("fail")).when(fileMoveHelper).commitMove(any(), any());
|
||||
when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true);
|
||||
when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library")));
|
||||
Library dto = Library.builder().build();
|
||||
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto);
|
||||
|
||||
service.moveSingleFile(book);
|
||||
|
||||
verify(fileMoveHelper).unregisterLibrary(1L);
|
||||
verify(monitoringRegistrationService).registerLibrary(dto);
|
||||
}
|
||||
}
|
||||
|
||||
+1041
-216
File diff suppressed because it is too large
Load Diff
+88
-235
@@ -1,24 +1,33 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.enums.FileProcessStatus;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookFile;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.FileProcessStatus;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
|
||||
import com.adityachandel.booklore.service.file.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||
import com.adityachandel.booklore.service.kobo.KoboAutoShelfService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.*;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class FileAsBookProcessorTest {
|
||||
@@ -29,36 +38,63 @@ class FileAsBookProcessorTest {
|
||||
@Mock
|
||||
private BookFileProcessorRegistry processorRegistry;
|
||||
|
||||
@Mock
|
||||
private KoboAutoShelfService koboAutoShelfService;
|
||||
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
|
||||
@Mock
|
||||
private BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
|
||||
@Mock
|
||||
private BookFileProcessor bookFileProcessor;
|
||||
|
||||
@InjectMocks
|
||||
private FileAsBookProcessor fileAsBookProcessor;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<Book> bookCaptor;
|
||||
|
||||
private AutoCloseable mocks;
|
||||
private MockedStatic<FileFingerprint> fileFingerprintMock;
|
||||
private MockedStatic<FileUtils> fileUtilsMock;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mocks = MockitoAnnotations.openMocks(this);
|
||||
fileAsBookProcessor = new FileAsBookProcessor(
|
||||
bookEventBroadcaster,
|
||||
processorRegistry,
|
||||
koboAutoShelfService,
|
||||
bookRepository,
|
||||
bookAdditionalFileRepository
|
||||
);
|
||||
fileFingerprintMock = mockStatic(FileFingerprint.class);
|
||||
fileFingerprintMock.when(() -> FileFingerprint.generateHash(any(Path.class))).thenReturn("testhash");
|
||||
fileUtilsMock = mockStatic(FileUtils.class);
|
||||
fileUtilsMock.when(() -> FileUtils.getFileSizeInKb(any(Path.class))).thenReturn(100L);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
if (mocks != null) {
|
||||
mocks.close();
|
||||
}
|
||||
if (fileFingerprintMock != null) fileFingerprintMock.close();
|
||||
if (fileUtilsMock != null) fileUtilsMock.close();
|
||||
if (mocks != null) mocks.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldProcessAllValidFiles() {
|
||||
// Given
|
||||
void staticMocksShouldWork() {
|
||||
// Verify static mocks are working
|
||||
Path testPath = Path.of("/test/path");
|
||||
String hash = FileFingerprint.generateHash(testPath);
|
||||
Long size = FileUtils.getFileSizeInKb(testPath);
|
||||
assert hash.equals("testhash") : "Expected 'testhash' but got: " + hash;
|
||||
assert size.equals(100L) : "Expected 100L but got: " + size;
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldProcessDifferentNamedFilesSeparately() {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setId(1L);
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
|
||||
LibraryFile file1 = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
@@ -76,54 +112,36 @@ class FileAsBookProcessorTest {
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
libraryFiles.add(file1);
|
||||
libraryFiles.add(file2);
|
||||
|
||||
Book book1 = Book.builder()
|
||||
.fileName("book1.epub")
|
||||
.title("Book 1")
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Book book2 = Book.builder()
|
||||
.fileName("book2.pdf")
|
||||
.title("Book 2")
|
||||
.bookType(BookFileType.PDF)
|
||||
.build();
|
||||
Book book1 = Book.builder().id(1L).primaryFile(BookFile.builder().fileName("book1.epub").bookType(BookFileType.EPUB).build()).build();
|
||||
Book book2 = Book.builder().id(2L).primaryFile(BookFile.builder().fileName("book2.pdf").bookType(BookFileType.PDF).build()).build();
|
||||
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor);
|
||||
when(bookFileProcessor.processFile(file1))
|
||||
.thenReturn(new FileProcessResult(book1, FileProcessStatus.NEW));
|
||||
when(bookFileProcessor.processFile(file2))
|
||||
.thenReturn(new FileProcessResult(book2, FileProcessStatus.NEW));
|
||||
when(bookFileProcessor.processFile(file1)).thenReturn(new FileProcessResult(book1, FileProcessStatus.NEW));
|
||||
when(bookFileProcessor.processFile(file2)).thenReturn(new FileProcessResult(book2, FileProcessStatus.NEW));
|
||||
|
||||
// When
|
||||
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
fileAsBookProcessor.processLibraryFiles(List.of(file1, file2), libraryEntity);
|
||||
|
||||
// Then
|
||||
verify(bookEventBroadcaster, times(2)).broadcastBookAddEvent(bookCaptor.capture());
|
||||
|
||||
List<Book> capturedBooks = bookCaptor.getAllValues();
|
||||
assertThat(capturedBooks).hasSize(2);
|
||||
assertThat(capturedBooks).containsExactly(book1, book2);
|
||||
verify(bookEventBroadcaster, times(2)).broadcastBookAddEvent(any());
|
||||
verify(bookFileProcessor, times(2)).processFile(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldSkipFilesWithUnsupportedExtensions() {
|
||||
// Given
|
||||
void processLibraryFiles_shouldHandleEmptyList() {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
|
||||
fileAsBookProcessor.processLibraryFiles(new ArrayList<>(), libraryEntity);
|
||||
|
||||
verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any());
|
||||
verify(processorRegistry, never()).getProcessorOrThrow(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldSkipFilesWithNullBookFileType() {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setId(1L);
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
|
||||
LibraryFile validFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
.fileName("book.epub")
|
||||
.fileSubPath("books")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile invalidFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
@@ -133,133 +151,19 @@ class FileAsBookProcessorTest {
|
||||
.bookFileType(null)
|
||||
.build();
|
||||
|
||||
libraryFiles.add(validFile);
|
||||
libraryFiles.add(invalidFile);
|
||||
fileAsBookProcessor.processLibraryFiles(List.of(invalidFile), libraryEntity);
|
||||
|
||||
Book book = Book.builder()
|
||||
.fileName("book.epub")
|
||||
.title("Valid Book")
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
|
||||
when(bookFileProcessor.processFile(validFile))
|
||||
.thenReturn(new FileProcessResult(book, FileProcessStatus.NEW));
|
||||
|
||||
// When
|
||||
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
// Then
|
||||
verify(bookEventBroadcaster, times(1)).broadcastBookAddEvent(book);
|
||||
verify(processorRegistry, times(1)).getProcessorOrThrow(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldHandleEmptyList() {
|
||||
// Given
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
|
||||
// When
|
||||
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
// Then
|
||||
verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any());
|
||||
verify(processorRegistry, never()).getProcessorOrThrow(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFile_shouldReturnNullForUnsupportedFileType() {
|
||||
// Given
|
||||
void processLibraryFiles_shouldNotBroadcastWhenProcessorReturnsNull() {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setId(1L);
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
.fileName("document.txt")
|
||||
.fileSubPath("docs")
|
||||
.bookFileType(null)
|
||||
.build();
|
||||
|
||||
// When
|
||||
FileProcessResult result = fileAsBookProcessor.processLibraryFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result).isNull();
|
||||
verify(processorRegistry, never()).getProcessorOrThrow(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFile_shouldProcessSupportedFileTypes() {
|
||||
// Given
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
.fileName("book.epub")
|
||||
.fileSubPath("books")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Book expectedBook = Book.builder()
|
||||
.fileName("book.epub")
|
||||
.title("Test Book")
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
|
||||
when(bookFileProcessor.processFile(libraryFile))
|
||||
.thenReturn(new FileProcessResult(expectedBook, FileProcessStatus.NEW));
|
||||
|
||||
// When
|
||||
FileProcessResult result = fileAsBookProcessor.processLibraryFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result).isNotNull();
|
||||
assertThat(result.getBook()).isEqualTo(expectedBook);
|
||||
|
||||
verify(processorRegistry).getProcessorOrThrow(BookFileType.EPUB);
|
||||
verify(bookFileProcessor).processFile(libraryFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFile_shouldHandleNullReturnFromProcessor() {
|
||||
// Given
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
.fileName("book.pdf")
|
||||
.fileSubPath("books")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor);
|
||||
when(bookFileProcessor.processFile(libraryFile)).thenReturn(null);
|
||||
|
||||
// When
|
||||
FileProcessResult result = fileAsBookProcessor.processLibraryFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldNotSendNotificationWhenProcessorReturnsNull() {
|
||||
// Given
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
|
||||
LibraryFile file = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -268,100 +172,49 @@ class FileAsBookProcessorTest {
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
libraryFiles.add(file);
|
||||
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
|
||||
when(bookFileProcessor.processFile(file)).thenReturn(null);
|
||||
|
||||
// When
|
||||
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
fileAsBookProcessor.processLibraryFiles(List.of(file), libraryEntity);
|
||||
|
||||
// Then
|
||||
verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldProcessAllSupportedFileExtensions() {
|
||||
// Given
|
||||
void processLibraryFiles_shouldNotGroupFilesInDifferentDirectories() {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setId(1L);
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
|
||||
LibraryFile epubFile = LibraryFile.builder()
|
||||
LibraryFile file1 = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
.fileName("book.epub")
|
||||
.fileSubPath("books")
|
||||
.fileSubPath("dir1")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile pdfFile = LibraryFile.builder()
|
||||
LibraryFile file2 = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
.fileName("book.pdf")
|
||||
.fileSubPath("books")
|
||||
.fileSubPath("dir2")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
LibraryFile cbzFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
.fileName("comic.cbz")
|
||||
.fileSubPath("comics")
|
||||
.bookFileType(BookFileType.CBX)
|
||||
.build();
|
||||
|
||||
LibraryFile cbrFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
.fileName("comic.cbr")
|
||||
.fileSubPath("comics")
|
||||
.bookFileType(BookFileType.CBX)
|
||||
.build();
|
||||
|
||||
libraryFiles.add(epubFile);
|
||||
libraryFiles.add(pdfFile);
|
||||
libraryFiles.add(cbzFile);
|
||||
libraryFiles.add(cbrFile);
|
||||
|
||||
Book epubBook = Book.builder()
|
||||
.fileName("book.epub")
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Book pdfBook = Book.builder()
|
||||
.fileName("book.pdf")
|
||||
.bookType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
Book cbzBook = Book.builder()
|
||||
.fileName("comic.cbz")
|
||||
.bookType(BookFileType.CBX)
|
||||
.build();
|
||||
|
||||
Book cbrBook = Book.builder()
|
||||
.fileName("comic.cbr")
|
||||
.bookType(BookFileType.CBX)
|
||||
.build();
|
||||
Book book1 = Book.builder().id(1L).primaryFile(BookFile.builder().fileName("book.epub").bookType(BookFileType.EPUB).build()).build();
|
||||
Book book2 = Book.builder().id(2L).primaryFile(BookFile.builder().fileName("book.pdf").bookType(BookFileType.PDF).build()).build();
|
||||
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor);
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.CBX)).thenReturn(bookFileProcessor);
|
||||
when(bookFileProcessor.processFile(file1)).thenReturn(new FileProcessResult(book1, FileProcessStatus.NEW));
|
||||
when(bookFileProcessor.processFile(file2)).thenReturn(new FileProcessResult(book2, FileProcessStatus.NEW));
|
||||
|
||||
when(bookFileProcessor.processFile(epubFile))
|
||||
.thenReturn(new FileProcessResult(epubBook, FileProcessStatus.NEW));
|
||||
when(bookFileProcessor.processFile(pdfFile))
|
||||
.thenReturn(new FileProcessResult(pdfBook, FileProcessStatus.NEW));
|
||||
when(bookFileProcessor.processFile(cbzFile))
|
||||
.thenReturn(new FileProcessResult(cbzBook, FileProcessStatus.NEW));
|
||||
when(bookFileProcessor.processFile(cbrFile))
|
||||
.thenReturn(new FileProcessResult(cbrBook, FileProcessStatus.NEW));
|
||||
fileAsBookProcessor.processLibraryFiles(List.of(file1, file2), libraryEntity);
|
||||
|
||||
// When
|
||||
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
// Then
|
||||
verify(bookEventBroadcaster, times(4)).broadcastBookAddEvent(any(Book.class));
|
||||
// Both should be processed as separate books
|
||||
verify(bookFileProcessor, times(2)).processFile(any());
|
||||
verify(bookEventBroadcaster, times(2)).broadcastBookAddEvent(any());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-320
@@ -1,320 +0,0 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.file.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.event.AdminEventBroadcaster;
|
||||
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.adityachandel.booklore.util.builder.LibraryTestBuilder;
|
||||
import static com.adityachandel.booklore.util.builder.LibraryTestBuilderAssert.assertThat;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.*;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class FolderAsBookFileProcessorExampleTest {
|
||||
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
|
||||
@Mock
|
||||
private BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
|
||||
@Mock
|
||||
private BookEventBroadcaster bookEventBroadcaster;
|
||||
|
||||
@Mock
|
||||
private AdminEventBroadcaster adminEventBroadcaster;
|
||||
|
||||
@Mock
|
||||
private BookFileProcessorRegistry bookFileProcessorRegistry;
|
||||
|
||||
@Mock
|
||||
private BookFileProcessor mockBookFileProcessor;
|
||||
|
||||
@InjectMocks
|
||||
private FolderAsBookFileProcessor processor;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<BookFileEntity> additionalFileCaptor;
|
||||
|
||||
private MockedStatic<FileUtils> fileUtilsMock;
|
||||
private MockedStatic<FileFingerprint> fileFingerprintMock;
|
||||
private LibraryTestBuilder libraryTestBuilder;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
fileUtilsMock = mockStatic(FileUtils.class);
|
||||
fileFingerprintMock = mockStatic(FileFingerprint.class);
|
||||
libraryTestBuilder = new LibraryTestBuilder(fileUtilsMock, fileFingerprintMock, bookFileProcessorRegistry, mockBookFileProcessor, bookRepository, bookAdditionalFileRepository);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
fileUtilsMock.close();
|
||||
fileFingerprintMock.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldCreateNewBookFromDirectory() {
|
||||
// Given
|
||||
libraryTestBuilder
|
||||
.addDefaultLibrary()
|
||||
.addLibraryFile("/101/Accounting", "Accounting 101.pdf")
|
||||
.addLibraryFile("/101/Anatomy", "Anatomy 101.pdf");
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity());
|
||||
|
||||
// Then
|
||||
assertThat(libraryTestBuilder)
|
||||
.hasBooks("Accounting 101", "Anatomy 101")
|
||||
.hasNoAdditionalFiles();
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldCreateNewBookFromDirectoryWithAdditionalBookFormats() {
|
||||
// Given
|
||||
libraryTestBuilder
|
||||
.addDefaultLibrary()
|
||||
.addLibraryFile("/101/Accounting", "Accounting 101.pdf")
|
||||
.addLibraryFile("/101/Accounting", "Accounting 101.epub")
|
||||
.addLibraryFile("/101/Anatomy", "Anatomy 101.pdf");
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity());
|
||||
|
||||
// Then
|
||||
assertThat(libraryTestBuilder)
|
||||
.hasBooks("Accounting 101", "Anatomy 101")
|
||||
.bookHasAdditionalFormats("Accounting 101", BookFileType.PDF)
|
||||
.bookHasNoSupplementaryFiles("Accounting 101")
|
||||
.bookHasNoAdditionalFiles("Anatomy 101");
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldCreateNewBookFromDirectoryWithAdditionalBookFormatsAndSupplementaryFiles() {
|
||||
// Given
|
||||
libraryTestBuilder
|
||||
.addDefaultLibrary()
|
||||
.addLibraryFile("/101/Accounting", "Accounting 101.pdf")
|
||||
.addLibraryFile("/101/Accounting", "Accounting 101.epub")
|
||||
.addLibraryFile("/101/Accounting", "Accounting 101.zip")
|
||||
.addLibraryFile("/101/Anatomy", "Anatomy 101.pdf");
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity());
|
||||
|
||||
// Then
|
||||
assertThat(libraryTestBuilder)
|
||||
.hasBooks("Accounting 101", "Anatomy 101")
|
||||
.bookHasAdditionalFormats("Accounting 101", BookFileType.PDF)
|
||||
.bookHasSupplementaryFiles("Accounting 101", "Accounting 101.zip")
|
||||
.bookHasNoAdditionalFiles("Anatomy 101");
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldCreateNewBookFromDirectoryWithSameSupplementaryFilesByHash() {
|
||||
// Given
|
||||
String supplementaryFileHash = "hash-accounting-101";
|
||||
libraryTestBuilder
|
||||
.addDefaultLibrary()
|
||||
.addLibraryFile("/101/Accounting", "Accounting 101.pdf")
|
||||
.addLibraryFile(
|
||||
"/101/Accounting",
|
||||
"Accounting 101.zip",
|
||||
supplementaryFileHash)
|
||||
.addLibraryFile("/101/Accounting 2nd Edition", "Accounting 101 2nd Edition.pdf")
|
||||
.addLibraryFile(
|
||||
"/101/Accounting 2nd Edition",
|
||||
"Accounting 101 2nd Edition.zip",
|
||||
supplementaryFileHash);
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity());
|
||||
|
||||
// Then
|
||||
assertThat(libraryTestBuilder)
|
||||
.hasBooks("Accounting 101", "Accounting 101 2nd Edition")
|
||||
.bookHasSupplementaryFiles("Accounting 101", "Accounting 101.zip")
|
||||
.bookHasSupplementaryFiles("Accounting 101 2nd Edition", "Accounting 101 2nd Edition.zip");
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldIgnoreAdditionalFormatWithTheSameHashUsedInOtherBook() {
|
||||
// Given
|
||||
String additionalFormatHash = "hash-accounting-101";
|
||||
libraryTestBuilder
|
||||
.addDefaultLibrary()
|
||||
.addLibraryFile("/101/Accounting", "Accounting 101.epub")
|
||||
.addLibraryFile(
|
||||
"/101/Accounting",
|
||||
"Accounting 101.pdf",
|
||||
additionalFormatHash)
|
||||
.addLibraryFile("/101/Accounting 2nd Edition", "Accounting 101 2nd Edition.epub")
|
||||
.addLibraryFile(
|
||||
"/101/Accounting 2nd Edition",
|
||||
"Accounting 101 2nd Edition.pdf",
|
||||
additionalFormatHash);
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity());
|
||||
|
||||
// Then
|
||||
assertThat(libraryTestBuilder)
|
||||
.hasBooks("Accounting 101", "Accounting 101 2nd Edition")
|
||||
.bookHasAdditionalFormats("Accounting 101", BookFileType.PDF)
|
||||
.bookHasNoAdditionalFiles("Accounting 101 2nd Edition");
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldAddAdditionalFormatsToExistingBook() {
|
||||
// Given
|
||||
libraryTestBuilder
|
||||
.addDefaultLibrary()
|
||||
.addBook("/101/Accounting", "Accounting 101.pdf")
|
||||
.addLibraryFile("/101/Accounting", "Accounting 101.epub");
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity());
|
||||
|
||||
// Then
|
||||
assertThat(libraryTestBuilder)
|
||||
.hasBooks("Accounting 101")
|
||||
.bookHasAdditionalFormats("Accounting 101", BookFileType.EPUB)
|
||||
.bookHasNoSupplementaryFiles("Accounting 101");
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldAddSupplementaryFilesToExistingBook() {
|
||||
// Given
|
||||
libraryTestBuilder
|
||||
.addDefaultLibrary()
|
||||
.addBook("/101/Accounting", "Accounting 101.pdf")
|
||||
.addLibraryFile("/101/Accounting", "sources.zip");
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity());
|
||||
|
||||
// Then
|
||||
assertThat(libraryTestBuilder)
|
||||
.hasBooks("Accounting 101")
|
||||
.bookHasNoAdditionalFormats("Accounting 101")
|
||||
.bookHasSupplementaryFiles("Accounting 101", "sources.zip");
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldAddAdditionalFilesToExistingBook() {
|
||||
// Given
|
||||
libraryTestBuilder
|
||||
.addDefaultLibrary()
|
||||
.addBook("/101/Accounting", "Accounting 101.pdf")
|
||||
.addLibraryFile("/101/Accounting", "Accounting 101.epub")
|
||||
.addLibraryFile("/101/Accounting", "sources.zip");
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity());
|
||||
|
||||
// Then
|
||||
assertThat(libraryTestBuilder)
|
||||
.hasBooks("Accounting 101")
|
||||
.bookHasAdditionalFormats("Accounting 101", BookFileType.EPUB)
|
||||
.bookHasSupplementaryFiles("Accounting 101", "sources.zip");
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldProcessDeepSubfolders() {
|
||||
var javaSourcesSameHash = "hash-java-sources";
|
||||
|
||||
libraryTestBuilder
|
||||
.addDefaultLibrary()
|
||||
// Basic books
|
||||
.addLibraryFile("/Basic/101/Accounting", "Accounting 101.epub")
|
||||
.addLibraryFile("/Basic/101/Accounting", "Accounting 101.pdf")
|
||||
.addLibraryFile("/Basic/101/Anatomy", "Anatomy 101.pdf")
|
||||
.addLibraryFile("/Basic/How-To/Repair", "How to Repair.epub")
|
||||
.addLibraryFile("/Basic/How-To/Repair", "How to Repair.pdf")
|
||||
// Software Engineering books
|
||||
.addLibraryFile("/Software Engineering/Java/Design Patterns", "Design Patterns.pdf")
|
||||
.addLibraryFile("/Software Engineering/Java/Design Patterns", "Design Patterns.epub")
|
||||
.addLibraryFile("/Software Engineering/Java/Design Patterns", "Design Patterns.zip", javaSourcesSameHash)
|
||||
.addLibraryFile("/Software Engineering/Java/Effective Java", "Effective Java.pdf")
|
||||
.addLibraryFile("/Software Engineering/Java/Effective Java", "Effective Java.epub")
|
||||
.addLibraryFile("/Software Engineering/Java/Effective Java", "Effective Java.zip", javaSourcesSameHash)
|
||||
.addLibraryFile("/Software Engineering/Python/AI/Machine Learning/Pytorch", "PyTorch for Machine Learning.pdf")
|
||||
.addLibraryFile("/Software Engineering/Python/AI/Machine Learning/Pytorch", "PyTorch for Machine Learning.epub")
|
||||
.addLibraryFile("/Software Engineering/Python/AI/Machine Learning/Pytorch", "sources.zip")
|
||||
.addLibraryFile("/Software Engineering/Python/AI/Machine Learning/TensorFlow", "TensorFlow for Machine Learning.pdf")
|
||||
.addLibraryFile("/Software Engineering/Python/AI/Machine Learning/TensorFlow", "TensorFlow for Machine Learning.epub")
|
||||
.addLibraryFile("/Software Engineering/Python/AI/Machine Learning/TensorFlow", "sources.zip")
|
||||
.addLibraryFile("/Software Engineering/Python/Flask/Flask Web Development", "Flask Web Development.pdf")
|
||||
.addLibraryFile("/Software Engineering/Python/Flask/Flask Web Development", "Flask Web Development.epub")
|
||||
// Comics Marvel
|
||||
.addLibraryFile("/Comics/Marvel/Batman/Volume 1", "Batman v1.cbr")
|
||||
.addLibraryFile("/Comics/Marvel/Batman/Volume 2", "Batman v2.cbr")
|
||||
.addLibraryFile("/Comics/Marvel/Spiderman/Volume 1", "Spiderman v1.cbz")
|
||||
.addLibraryFile("/Comics/Marvel/Spiderman/Volume 2", "Spiderman v2.cbz")
|
||||
// Comics DC
|
||||
.addLibraryFile("/Comics/DC/Superman/Volume 1", "Superman v1.cbr")
|
||||
.addLibraryFile("/Comics/DC/Superman/Volume 1", "Poster.jpg")
|
||||
.addLibraryFile("/Comics/DC/Superman/Volume 2", "Superman v2.cbr")
|
||||
// Manga
|
||||
.addLibraryFile("/Manga/One Piece/Volume 1", "One Piece v1.cbz")
|
||||
.addLibraryFile("/Manga/One Piece/Volume 2", "One Piece v2.cbz")
|
||||
.addLibraryFile("/Manga/Naruto/Volume 1", "Naruto v1.cbr")
|
||||
.addLibraryFile("/Manga/Naruto/Volume 2", "Naruto v2.cbr");
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity());
|
||||
|
||||
// Then
|
||||
assertThat(libraryTestBuilder)
|
||||
.hasBooks(
|
||||
"Accounting 101", "Anatomy 101", "How to Repair",
|
||||
"Design Patterns", "Effective Java",
|
||||
"PyTorch for Machine Learning", "TensorFlow for Machine Learning",
|
||||
"Flask Web Development",
|
||||
"Batman v1", "Batman v2",
|
||||
"Spiderman v1", "Spiderman v2",
|
||||
"Superman v1", "Superman v2",
|
||||
"One Piece v1", "One Piece v2",
|
||||
"Naruto v1", "Naruto v2")
|
||||
// Basic books
|
||||
.bookHasAdditionalFormats("Accounting 101", BookFileType.PDF)
|
||||
.bookHasNoSupplementaryFiles("Anatomy 101")
|
||||
.bookHasAdditionalFormats("How to Repair", BookFileType.PDF)
|
||||
// Software Engineering books
|
||||
.bookHasAdditionalFormats("Design Patterns", BookFileType.PDF)
|
||||
.bookHasSupplementaryFiles("Design Patterns", "Design Patterns.zip")
|
||||
.bookHasAdditionalFormats("Effective Java", BookFileType.PDF)
|
||||
.bookHasSupplementaryFiles("Effective Java", "Effective Java.zip")
|
||||
.bookHasAdditionalFormats("PyTorch for Machine Learning", BookFileType.PDF)
|
||||
.bookHasSupplementaryFiles("PyTorch for Machine Learning", "sources.zip")
|
||||
.bookHasAdditionalFormats("TensorFlow for Machine Learning", BookFileType.PDF)
|
||||
.bookHasSupplementaryFiles("TensorFlow for Machine Learning", "sources.zip")
|
||||
.bookHasAdditionalFormats("Flask Web Development", BookFileType.PDF)
|
||||
// Comics Marvel
|
||||
.bookHasNoAdditionalFiles("Batman v1")
|
||||
.bookHasNoAdditionalFiles("Batman v2")
|
||||
.bookHasNoAdditionalFiles("Spiderman v1")
|
||||
.bookHasNoAdditionalFiles("Spiderman v2")
|
||||
// Comics DC
|
||||
.bookHasSupplementaryFiles("Superman v1", "Poster.jpg")
|
||||
.bookHasNoAdditionalFiles("Superman v2")
|
||||
// Manga
|
||||
.bookHasNoAdditionalFiles("One Piece v1")
|
||||
.bookHasNoAdditionalFiles("One Piece v2")
|
||||
.bookHasNoAdditionalFiles("Naruto v1")
|
||||
.bookHasNoAdditionalFiles("Naruto v2");
|
||||
}
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.event.AdminEventBroadcaster;
|
||||
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
class FolderAsBookFileProcessorSimpleTest {
|
||||
|
||||
@Test
|
||||
void getScanMode_shouldReturnFolderAsBook() {
|
||||
BookRepository bookRepository = mock(BookRepository.class);
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository = mock(BookAdditionalFileRepository.class);
|
||||
AdminEventBroadcaster adminEventBroadcaster = mock(AdminEventBroadcaster.class);
|
||||
BookEventBroadcaster bookEventBroadcaster = mock(BookEventBroadcaster.class);
|
||||
BookFileProcessorRegistry bookFileProcessorRegistry = mock(BookFileProcessorRegistry.class);
|
||||
|
||||
FolderAsBookFileProcessor processor = new FolderAsBookFileProcessor(
|
||||
bookRepository, bookAdditionalFileRepository, bookEventBroadcaster, adminEventBroadcaster, bookFileProcessorRegistry);
|
||||
|
||||
assertThat(processor.getScanMode()).isEqualTo(LibraryScanMode.FOLDER_AS_BOOK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void supportsSupplementaryFiles_shouldReturnTrue() {
|
||||
BookRepository bookRepository = mock(BookRepository.class);
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository = mock(BookAdditionalFileRepository.class);
|
||||
AdminEventBroadcaster adminEventBroadcaster = mock(AdminEventBroadcaster.class);
|
||||
BookEventBroadcaster bookEventBroadcaster = mock(BookEventBroadcaster.class);
|
||||
BookFileProcessorRegistry bookFileProcessorRegistry = mock(BookFileProcessorRegistry.class);
|
||||
|
||||
FolderAsBookFileProcessor processor = new FolderAsBookFileProcessor(
|
||||
bookRepository, bookAdditionalFileRepository, bookEventBroadcaster, adminEventBroadcaster, bookFileProcessorRegistry);
|
||||
|
||||
assertThat(processor.supportsSupplementaryFiles()).isTrue();
|
||||
}
|
||||
}
|
||||
-439
@@ -1,439 +0,0 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.FileProcessStatus;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
|
||||
import com.adityachandel.booklore.service.event.AdminEventBroadcaster;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.file.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.*;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class FolderAsBookFileProcessorTest {
|
||||
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
|
||||
@Mock
|
||||
private BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
|
||||
@Mock
|
||||
private BookEventBroadcaster bookEventBroadcaster;
|
||||
|
||||
@Mock
|
||||
private AdminEventBroadcaster adminEventBroadcaster;
|
||||
|
||||
@Mock
|
||||
private BookFileProcessorRegistry bookFileProcessorRegistry;
|
||||
|
||||
@Mock
|
||||
private BookFileProcessor mockBookFileProcessor;
|
||||
|
||||
@InjectMocks
|
||||
private FolderAsBookFileProcessor processor;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<BookFileEntity> additionalFileCaptor;
|
||||
|
||||
private MockedStatic<FileUtils> fileUtilsMock;
|
||||
private MockedStatic<FileFingerprint> fileFingerprintMock;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
fileUtilsMock = mockStatic(FileUtils.class);
|
||||
fileFingerprintMock = mockStatic(FileFingerprint.class);
|
||||
// Setup common FileUtils mocks for all tests
|
||||
fileUtilsMock.when(() -> FileUtils.getFileSizeInKb(any(Path.class))).thenReturn(100L);
|
||||
fileFingerprintMock.when(() -> FileFingerprint.generateHash(any(Path.class)))
|
||||
.then(invocation -> {
|
||||
MessageDigest digest = MessageDigest.getInstance("MD5");
|
||||
Path path = invocation.getArgument(0);
|
||||
byte[] hash = digest.digest(path.toString().getBytes());
|
||||
StringBuilder hexString = new StringBuilder();
|
||||
for (byte b : hash) {
|
||||
String hex = Integer.toHexString(0xff & b);
|
||||
if (hex.length() == 1) hexString.append('0');
|
||||
hexString.append(hex);
|
||||
}
|
||||
return hexString.toString();
|
||||
});
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
fileUtilsMock.close();
|
||||
fileFingerprintMock.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getScanMode_shouldReturnFolderAsBook() {
|
||||
assertThat(processor.getScanMode()).isEqualTo(LibraryScanMode.FOLDER_AS_BOOK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void supportsSupplementaryFiles_shouldReturnTrue() {
|
||||
assertThat(processor.supportsSupplementaryFiles()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldCreateNewBookFromDirectory() {
|
||||
// Given
|
||||
LibraryEntity libraryEntity = createLibraryEntity();
|
||||
List<LibraryFile> libraryFiles = createLibraryFilesInSameDirectory();
|
||||
|
||||
Book createdBook = Book.builder()
|
||||
.id(1L)
|
||||
.fileName("book.pdf")
|
||||
.bookType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
BookEntity bookEntity = createBookEntity(1L, "book.pdf", "books");
|
||||
|
||||
when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), anyString()))
|
||||
.thenReturn(new ArrayList<>());
|
||||
when(bookFileProcessorRegistry.getProcessorOrThrow(BookFileType.PDF))
|
||||
.thenReturn(mockBookFileProcessor);
|
||||
when(mockBookFileProcessor.processFile(any(LibraryFile.class)))
|
||||
.thenReturn(new FileProcessResult(createdBook, FileProcessStatus.NEW));
|
||||
when(bookRepository.getReferenceById(createdBook.getId()))
|
||||
.thenReturn(bookEntity);
|
||||
when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), anyString(), anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
// Then
|
||||
verify(mockBookFileProcessor).processFile(any(LibraryFile.class));
|
||||
verify(bookEventBroadcaster).broadcastBookAddEvent(createdBook);
|
||||
verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString());
|
||||
verify(bookAdditionalFileRepository, times(2)).save(additionalFileCaptor.capture());
|
||||
|
||||
List<BookFileEntity> capturedFiles = additionalFileCaptor.getAllValues();
|
||||
assertThat(capturedFiles).hasSize(2);
|
||||
assertThat(capturedFiles).extracting(BookFileEntity::getFileName)
|
||||
.containsExactlyInAnyOrder("book.epub", "cover.jpg");
|
||||
assertThat(capturedFiles).extracting(BookFileEntity::isBookFormat)
|
||||
.containsExactlyInAnyOrder(true, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldProcessExistingBook() {
|
||||
// Given
|
||||
LibraryEntity libraryEntity = createLibraryEntity();
|
||||
List<LibraryFile> libraryFiles = createLibraryFilesInSameDirectory()
|
||||
.stream()
|
||||
.filter(f -> !f.getFileName().equals("book.pdf"))
|
||||
.toList();
|
||||
|
||||
BookEntity existingBook = createBookEntity(1L, "book.pdf", "books");
|
||||
|
||||
when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), eq("books")))
|
||||
.thenReturn(List.of(existingBook));
|
||||
when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), anyString(), anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
// Then
|
||||
verify(mockBookFileProcessor, never()).processFile(any());
|
||||
verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any());
|
||||
verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString());
|
||||
verify(bookAdditionalFileRepository, times(2)).save(additionalFileCaptor.capture());
|
||||
|
||||
List<BookFileEntity> capturedFiles = additionalFileCaptor.getAllValues();
|
||||
assertThat(capturedFiles).hasSize(2);
|
||||
assertThat(capturedFiles).extracting(BookFileEntity::getFileName)
|
||||
.containsExactlyInAnyOrder("book.epub", "cover.jpg");
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldProcessFilesWithParentBook() {
|
||||
// Given
|
||||
LibraryEntity libraryEntity = createLibraryEntity();
|
||||
List<LibraryFile> libraryFiles = List.of(
|
||||
createLibraryFile("file1.txt", "books/chapter1"),
|
||||
createLibraryFile("file2.txt", "books/chapter1")
|
||||
);
|
||||
|
||||
BookEntity parentBook = createBookEntity(1L, "book.pdf", "books");
|
||||
|
||||
when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), eq("books/chapter1")))
|
||||
.thenReturn(new ArrayList<>());
|
||||
when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), eq("books")))
|
||||
.thenReturn(List.of(parentBook));
|
||||
when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), anyString(), anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
// Then
|
||||
verify(mockBookFileProcessor, never()).processFile(any());
|
||||
verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any());
|
||||
verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString());
|
||||
verify(bookAdditionalFileRepository, times(2)).save(additionalFileCaptor.capture());
|
||||
|
||||
List<BookFileEntity> capturedFiles = additionalFileCaptor.getAllValues();
|
||||
assertThat(capturedFiles).hasSize(2);
|
||||
assertThat(capturedFiles).extracting(BookFileEntity::isBookFormat)
|
||||
.containsOnly(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldRespectDefaultBookFormat() {
|
||||
// Given
|
||||
LibraryEntity libraryEntity = createLibraryEntity();
|
||||
libraryEntity.setDefaultBookFormat(BookFileType.EPUB);
|
||||
|
||||
List<LibraryFile> libraryFiles = List.of(
|
||||
createLibraryFile("book.pdf", "books", BookFileType.PDF),
|
||||
createLibraryFile("book.epub", "books", BookFileType.EPUB),
|
||||
createLibraryFile("book.cbz", "books", BookFileType.CBX)
|
||||
);
|
||||
|
||||
Book createdBook = Book.builder()
|
||||
.id(1L)
|
||||
.fileName("book.epub")
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
BookEntity bookEntity = createBookEntity(1L, "book.epub", "books");
|
||||
|
||||
when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), anyString()))
|
||||
.thenReturn(new ArrayList<>());
|
||||
when(bookFileProcessorRegistry.getProcessorOrThrow(BookFileType.EPUB))
|
||||
.thenReturn(mockBookFileProcessor);
|
||||
when(mockBookFileProcessor.processFile(argThat(file -> file.getFileName().equals("book.epub"))))
|
||||
.thenReturn(new FileProcessResult(createdBook, FileProcessStatus.NEW));
|
||||
when(bookRepository.getReferenceById(createdBook.getId()))
|
||||
.thenReturn(bookEntity);
|
||||
when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), anyString(), anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
// Then
|
||||
verify(mockBookFileProcessor).processFile(argThat(file -> file.getFileName().equals("book.epub")));
|
||||
verify(bookEventBroadcaster).broadcastBookAddEvent(createdBook);
|
||||
verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString());
|
||||
verify(bookAdditionalFileRepository, times(2)).save(additionalFileCaptor.capture());
|
||||
|
||||
List<BookFileEntity> capturedFiles = additionalFileCaptor.getAllValues();
|
||||
assertThat(capturedFiles).extracting(BookFileEntity::getFileName)
|
||||
.containsExactlyInAnyOrder("book.pdf", "book.cbz");
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldUseDefaultPriorityWhenNoDefaultFormat() {
|
||||
// Given
|
||||
LibraryEntity libraryEntity = createLibraryEntity();
|
||||
libraryEntity.setDefaultBookFormat(null);
|
||||
|
||||
List<LibraryFile> libraryFiles = List.of(
|
||||
createLibraryFile("book.epub", "books", BookFileType.EPUB),
|
||||
createLibraryFile("book.cbz", "books", BookFileType.CBX),
|
||||
createLibraryFile("book.pdf", "books", BookFileType.PDF)
|
||||
);
|
||||
|
||||
Book createdBook = Book.builder()
|
||||
.id(1L)
|
||||
.fileName("book.pdf")
|
||||
.bookType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
BookEntity bookEntity = createBookEntity(1L, "book.pdf", "books");
|
||||
|
||||
when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), anyString()))
|
||||
.thenReturn(new ArrayList<>());
|
||||
when(bookFileProcessorRegistry.getProcessorOrThrow(BookFileType.PDF))
|
||||
.thenReturn(mockBookFileProcessor);
|
||||
when(mockBookFileProcessor.processFile(argThat(file -> file.getFileName().equals("book.pdf"))))
|
||||
.thenReturn(new FileProcessResult(createdBook, FileProcessStatus.NEW));
|
||||
when(bookRepository.getReferenceById(createdBook.getId()))
|
||||
.thenReturn(bookEntity);
|
||||
when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), anyString(), anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
// Then
|
||||
verify(mockBookFileProcessor).processFile(argThat(file -> file.getFileName().equals("book.pdf")));
|
||||
verify(bookEventBroadcaster).broadcastBookAddEvent(createdBook);
|
||||
verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldSkipExistingAdditionalFiles() {
|
||||
// Given
|
||||
LibraryEntity libraryEntity = createLibraryEntity();
|
||||
List<LibraryFile> libraryFiles = createLibraryFilesInSameDirectory()
|
||||
.stream()
|
||||
.filter(f -> !f.getFileName().equals("book.pdf"))
|
||||
.toList();
|
||||
|
||||
BookEntity existingBook = createBookEntity(1L, "book.pdf", "books");
|
||||
BookFileEntity existingAdditionalFile = BookFileEntity.builder()
|
||||
.id(1L)
|
||||
.book(existingBook)
|
||||
.fileName("book.epub")
|
||||
.fileSubPath("books")
|
||||
.isBookFormat(true)
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), eq("books")))
|
||||
.thenReturn(List.of(existingBook));
|
||||
when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), eq("books"), eq("book.epub")))
|
||||
.thenReturn(Optional.of(existingAdditionalFile));
|
||||
when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), eq("books"), eq("cover.jpg")))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
// Then
|
||||
verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any());
|
||||
verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString());
|
||||
verify(bookAdditionalFileRepository, times(1)).save(additionalFileCaptor.capture());
|
||||
|
||||
BookFileEntity capturedFile = additionalFileCaptor.getValue();
|
||||
assertThat(capturedFile.getFileName()).isEqualTo("cover.jpg");
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldHandleEmptyDirectory() {
|
||||
// Given
|
||||
LibraryEntity libraryEntity = createLibraryEntity();
|
||||
List<LibraryFile> libraryFiles = List.of(
|
||||
createLibraryFile("readme.txt", "docs"),
|
||||
createLibraryFile("notes.txt", "docs")
|
||||
);
|
||||
|
||||
when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), anyString()))
|
||||
.thenReturn(new ArrayList<>());
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
// Then
|
||||
verify(mockBookFileProcessor, never()).processFile(any());
|
||||
verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any());
|
||||
verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString());
|
||||
verify(bookAdditionalFileRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLibraryFiles_shouldHandleProcessorError() {
|
||||
// Given
|
||||
LibraryEntity libraryEntity = createLibraryEntity();
|
||||
List<LibraryFile> libraryFiles = List.of(
|
||||
createLibraryFile("book.pdf", "books", BookFileType.PDF)
|
||||
);
|
||||
|
||||
when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), anyString()))
|
||||
.thenReturn(new ArrayList<>());
|
||||
when(bookFileProcessorRegistry.getProcessorOrThrow(BookFileType.PDF))
|
||||
.thenReturn(mockBookFileProcessor);
|
||||
when(mockBookFileProcessor.processFile(any(LibraryFile.class)))
|
||||
.thenThrow(new RuntimeException("Processing error"));
|
||||
|
||||
// When
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
// Then
|
||||
verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any());
|
||||
verify(bookAdditionalFileRepository, never()).save(any());
|
||||
verify(adminEventBroadcaster).broadcastAdminEvent(anyString());
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
private LibraryEntity createLibraryEntity() {
|
||||
LibraryEntity library = new LibraryEntity();
|
||||
library.setId(1L);
|
||||
library.setName("Test Library");
|
||||
library.setScanMode(LibraryScanMode.FOLDER_AS_BOOK);
|
||||
|
||||
LibraryPathEntity path = new LibraryPathEntity();
|
||||
path.setId(1L);
|
||||
path.setPath("/test/library");
|
||||
library.setLibraryPaths(List.of(path));
|
||||
|
||||
return library;
|
||||
}
|
||||
|
||||
private List<LibraryFile> createLibraryFilesInSameDirectory() {
|
||||
return List.of(
|
||||
createLibraryFile("book.pdf", "books", BookFileType.PDF),
|
||||
createLibraryFile("book.epub", "books", BookFileType.EPUB),
|
||||
createLibraryFile("cover.jpg", "books")
|
||||
);
|
||||
}
|
||||
|
||||
private LibraryFile createLibraryFile(String fileName, String subPath) {
|
||||
return createLibraryFile(fileName, subPath, null);
|
||||
}
|
||||
|
||||
private LibraryFile createLibraryFile(String fileName, String subPath, BookFileType bookFileType) {
|
||||
LibraryPathEntity libraryPath = new LibraryPathEntity();
|
||||
libraryPath.setId(1L);
|
||||
libraryPath.setPath("/test/library");
|
||||
|
||||
return LibraryFile.builder()
|
||||
.libraryEntity(new LibraryEntity())
|
||||
.libraryPathEntity(libraryPath)
|
||||
.fileName(fileName)
|
||||
.fileSubPath(subPath)
|
||||
.bookFileType(bookFileType)
|
||||
.build();
|
||||
}
|
||||
|
||||
private BookEntity createBookEntity(Long id, String fileName, String subPath) {
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(id);
|
||||
book.setAddedOn(Instant.parse("2025-01-01T12:00:00Z"));
|
||||
|
||||
book.setBookFiles(new ArrayList<>());
|
||||
|
||||
LibraryPathEntity libraryPath = new LibraryPathEntity();
|
||||
libraryPath.setId(1L);
|
||||
libraryPath.setPath("/test/library");
|
||||
book.setLibraryPath(libraryPath);
|
||||
|
||||
BookFileEntity primaryFile = new BookFileEntity();
|
||||
primaryFile.setBook(book);
|
||||
primaryFile.setFileName(fileName);
|
||||
primaryFile.setFileSubPath(subPath);
|
||||
primaryFile.setBookType(BookFileType.PDF);
|
||||
book.getBookFiles().add(primaryFile);
|
||||
|
||||
return book;
|
||||
}
|
||||
}
|
||||
+2
-14
@@ -1,25 +1,17 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.LibraryPath;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.FileAttribute;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
@@ -29,9 +21,6 @@ class LibraryFileHelperTest {
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Mock
|
||||
private LibraryFileProcessor processor;
|
||||
|
||||
@Test
|
||||
void testGetLibraryFiles_HandlesInaccessibleDirectories() throws IOException {
|
||||
LibraryFileHelper libraryFileHelper = new LibraryFileHelper();
|
||||
@@ -47,12 +36,11 @@ class LibraryFileHelperTest {
|
||||
LibraryEntity testLibrary = LibraryEntity.builder()
|
||||
.name("Test Library")
|
||||
.icon("book")
|
||||
.scanMode(LibraryScanMode.FILE_AS_BOOK)
|
||||
.watch(false)
|
||||
.libraryPaths(List.of(libraryPath))
|
||||
.build();
|
||||
|
||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(testLibrary, processor);
|
||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(testLibrary);
|
||||
assertEquals(libraryFiles.stream().map(LibraryFile::getFileName).sorted().toList(), List.of("happy.epub", "zzzz_happ.epub"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+20
-22
@@ -3,7 +3,6 @@ package com.adityachandel.booklore.service.library;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
@@ -21,6 +20,7 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -36,7 +36,7 @@ class LibraryProcessingServiceRegressionTest {
|
||||
@Mock
|
||||
private BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
@Mock
|
||||
private LibraryFileProcessorRegistry fileProcessorRegistry;
|
||||
private FileAsBookProcessor fileAsBookProcessor;
|
||||
@Mock
|
||||
private BookRestorationService bookRestorationService;
|
||||
@Mock
|
||||
@@ -44,9 +44,9 @@ class LibraryProcessingServiceRegressionTest {
|
||||
@Mock
|
||||
private LibraryFileHelper libraryFileHelper;
|
||||
@Mock
|
||||
private EntityManager entityManager;
|
||||
private BookGroupingService bookGroupingService;
|
||||
@Mock
|
||||
private LibraryFileProcessor libraryFileProcessor;
|
||||
private EntityManager entityManager;
|
||||
|
||||
private LibraryProcessingService libraryProcessingService;
|
||||
|
||||
@@ -56,16 +56,17 @@ class LibraryProcessingServiceRegressionTest {
|
||||
libraryRepository,
|
||||
notificationService,
|
||||
bookAdditionalFileRepository,
|
||||
fileProcessorRegistry,
|
||||
fileAsBookProcessor,
|
||||
bookRestorationService,
|
||||
bookDeletionService,
|
||||
libraryFileHelper,
|
||||
bookGroupingService,
|
||||
entityManager
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rescanLibrary_shouldThrowException_whenBookHasNoFiles(@TempDir Path tempDir) throws IOException {
|
||||
void rescanLibrary_shouldNotDeleteFilelessBooks(@TempDir Path tempDir) throws IOException {
|
||||
long libraryId = 1L;
|
||||
Path accessiblePath = tempDir.resolve("accessible");
|
||||
Files.createDirectory(accessiblePath);
|
||||
@@ -73,40 +74,37 @@ class LibraryProcessingServiceRegressionTest {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
libraryEntity.setId(libraryId);
|
||||
libraryEntity.setName("Test Library");
|
||||
libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK);
|
||||
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(10L);
|
||||
pathEntity.setPath(accessiblePath.toString());
|
||||
libraryEntity.setLibraryPaths(List.of(pathEntity));
|
||||
|
||||
BookEntity bookWithNoFiles = new BookEntity();
|
||||
bookWithNoFiles.setId(1L);
|
||||
bookWithNoFiles.setLibraryPath(pathEntity);
|
||||
bookWithNoFiles.setBookFiles(Collections.emptyList()); // Empty files list
|
||||
|
||||
libraryEntity.setBookEntities(List.of(bookWithNoFiles));
|
||||
// Create a fileless book (e.g., physical book)
|
||||
BookEntity filelessBook = new BookEntity();
|
||||
filelessBook.setId(1L);
|
||||
filelessBook.setLibraryPath(pathEntity);
|
||||
filelessBook.setBookFiles(Collections.emptyList());
|
||||
|
||||
libraryEntity.setBookEntities(List.of(filelessBook));
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor);
|
||||
// We need at least one file so it doesn't think the library is offline
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(
|
||||
com.adityachandel.booklore.model.dto.settings.LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileName("other.epub")
|
||||
.fileSubPath("")
|
||||
.build()
|
||||
));
|
||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
||||
when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class)))
|
||||
.thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap()));
|
||||
|
||||
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
||||
|
||||
// Should not throw exception anymore
|
||||
libraryProcessingService.rescanLibrary(context);
|
||||
|
||||
// Verify that the book with no files (ID 1) was detected as deleted
|
||||
verify(bookDeletionService).processDeletedLibraryFiles(
|
||||
argThat(list -> list.contains(1L)),
|
||||
any()
|
||||
);
|
||||
// Fileless books should NOT be marked as deleted - they are intentionally without files
|
||||
verify(bookDeletionService, never()).processDeletedLibraryFiles(any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
+68
-55
@@ -6,7 +6,6 @@ import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
@@ -24,7 +23,9 @@ import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -42,7 +43,7 @@ class LibraryProcessingServiceTest {
|
||||
@Mock
|
||||
private BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
@Mock
|
||||
private LibraryFileProcessorRegistry fileProcessorRegistry;
|
||||
private FileAsBookProcessor fileAsBookProcessor;
|
||||
@Mock
|
||||
private BookRestorationService bookRestorationService;
|
||||
@Mock
|
||||
@@ -50,9 +51,9 @@ class LibraryProcessingServiceTest {
|
||||
@Mock
|
||||
private LibraryFileHelper libraryFileHelper;
|
||||
@Mock
|
||||
private EntityManager entityManager;
|
||||
private BookGroupingService bookGroupingService;
|
||||
@Mock
|
||||
private LibraryFileProcessor libraryFileProcessor;
|
||||
private EntityManager entityManager;
|
||||
|
||||
private LibraryProcessingService libraryProcessingService;
|
||||
|
||||
@@ -62,10 +63,11 @@ class LibraryProcessingServiceTest {
|
||||
libraryRepository,
|
||||
notificationService,
|
||||
bookAdditionalFileRepository,
|
||||
fileProcessorRegistry,
|
||||
fileAsBookProcessor,
|
||||
bookRestorationService,
|
||||
bookDeletionService,
|
||||
libraryFileHelper,
|
||||
bookGroupingService,
|
||||
entityManager
|
||||
);
|
||||
}
|
||||
@@ -76,7 +78,6 @@ class LibraryProcessingServiceTest {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
libraryEntity.setId(libraryId);
|
||||
libraryEntity.setName("Test Library");
|
||||
libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK);
|
||||
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(10L);
|
||||
@@ -92,9 +93,7 @@ class LibraryProcessingServiceTest {
|
||||
libraryEntity.setBookEntities(List.of(existingBook));
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor);
|
||||
|
||||
// Library files found on disk (1 existing, 1 new)
|
||||
LibraryFile existingFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
@@ -109,13 +108,24 @@ class LibraryProcessingServiceTest {
|
||||
.fileName("book2.epub")
|
||||
.build();
|
||||
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(existingFile, newFile));
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(existingFile, newFile));
|
||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
||||
|
||||
// Mock grouping service to pass through the files
|
||||
when(bookGroupingService.groupForInitialScan(anyList(), eq(libraryEntity)))
|
||||
.thenAnswer(invocation -> {
|
||||
List<LibraryFile> files = invocation.getArgument(0);
|
||||
Map<String, List<LibraryFile>> result = new LinkedHashMap<>();
|
||||
for (LibraryFile f : files) {
|
||||
result.put(f.getFileName(), List.of(f));
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
libraryProcessingService.processLibrary(libraryId);
|
||||
|
||||
ArgumentCaptor<List<LibraryFile>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(libraryFileProcessor).processLibraryFiles(captor.capture(), eq(libraryEntity));
|
||||
verify(bookGroupingService).groupForInitialScan(captor.capture(), eq(libraryEntity));
|
||||
|
||||
List<LibraryFile> processedFiles = captor.getValue();
|
||||
|
||||
@@ -129,7 +139,6 @@ class LibraryProcessingServiceTest {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
libraryEntity.setId(libraryId);
|
||||
libraryEntity.setName("Test Library");
|
||||
libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK);
|
||||
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(10L);
|
||||
@@ -145,7 +154,6 @@ class LibraryProcessingServiceTest {
|
||||
libraryEntity.setBookEntities(List.of(existingBook));
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor);
|
||||
|
||||
LibraryFile existingFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
@@ -154,13 +162,14 @@ class LibraryProcessingServiceTest {
|
||||
.fileName("book1.epub")
|
||||
.build();
|
||||
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(existingFile));
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(existingFile));
|
||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
||||
when(bookGroupingService.groupForInitialScan(anyList(), eq(libraryEntity))).thenReturn(Collections.emptyMap());
|
||||
|
||||
libraryProcessingService.processLibrary(libraryId);
|
||||
|
||||
ArgumentCaptor<List<LibraryFile>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(libraryFileProcessor).processLibraryFiles(captor.capture(), eq(libraryEntity));
|
||||
verify(bookGroupingService).groupForInitialScan(captor.capture(), eq(libraryEntity));
|
||||
|
||||
assertThat(captor.getValue()).isEmpty();
|
||||
}
|
||||
@@ -171,15 +180,13 @@ class LibraryProcessingServiceTest {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
libraryEntity.setId(libraryId);
|
||||
libraryEntity.setName("Test Library");
|
||||
libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK);
|
||||
libraryEntity.setBookEntities(Collections.emptyList()); // No existing books
|
||||
libraryEntity.setBookEntities(Collections.emptyList());
|
||||
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(10L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor);
|
||||
|
||||
LibraryFile newFile1 = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
@@ -194,13 +201,22 @@ class LibraryProcessingServiceTest {
|
||||
.fileName("book2.epub")
|
||||
.build();
|
||||
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(newFile1, newFile2));
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(newFile1, newFile2));
|
||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
||||
when(bookGroupingService.groupForInitialScan(anyList(), eq(libraryEntity)))
|
||||
.thenAnswer(invocation -> {
|
||||
List<LibraryFile> files = invocation.getArgument(0);
|
||||
Map<String, List<LibraryFile>> result = new LinkedHashMap<>();
|
||||
for (LibraryFile f : files) {
|
||||
result.put(f.getFileName(), List.of(f));
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
libraryProcessingService.processLibrary(libraryId);
|
||||
|
||||
ArgumentCaptor<List<LibraryFile>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(libraryFileProcessor).processLibraryFiles(captor.capture(), eq(libraryEntity));
|
||||
verify(bookGroupingService).groupForInitialScan(captor.capture(), eq(libraryEntity));
|
||||
|
||||
assertThat(captor.getValue()).hasSize(2);
|
||||
}
|
||||
@@ -211,7 +227,6 @@ class LibraryProcessingServiceTest {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
libraryEntity.setId(libraryId);
|
||||
libraryEntity.setName("Test Library");
|
||||
libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK);
|
||||
libraryEntity.setBookEntities(Collections.emptyList());
|
||||
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
@@ -219,7 +234,6 @@ class LibraryProcessingServiceTest {
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor);
|
||||
|
||||
LibraryFile newFileInSub = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
@@ -228,13 +242,22 @@ class LibraryProcessingServiceTest {
|
||||
.fileName("book1.epub")
|
||||
.build();
|
||||
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(newFileInSub));
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(newFileInSub));
|
||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
||||
when(bookGroupingService.groupForInitialScan(anyList(), eq(libraryEntity)))
|
||||
.thenAnswer(invocation -> {
|
||||
List<LibraryFile> files = invocation.getArgument(0);
|
||||
Map<String, List<LibraryFile>> result = new LinkedHashMap<>();
|
||||
for (LibraryFile f : files) {
|
||||
result.put(f.getFileName(), List.of(f));
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
libraryProcessingService.processLibrary(libraryId);
|
||||
|
||||
ArgumentCaptor<List<LibraryFile>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(libraryFileProcessor).processLibraryFiles(captor.capture(), eq(libraryEntity));
|
||||
verify(bookGroupingService).groupForInitialScan(captor.capture(), eq(libraryEntity));
|
||||
|
||||
List<LibraryFile> processedFiles = captor.getValue();
|
||||
assertThat(processedFiles).hasSize(1);
|
||||
@@ -248,7 +271,6 @@ class LibraryProcessingServiceTest {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
libraryEntity.setId(libraryId);
|
||||
libraryEntity.setName("Test Library");
|
||||
libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK);
|
||||
libraryEntity.setBookEntities(Collections.emptyList());
|
||||
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
@@ -256,9 +278,7 @@ class LibraryProcessingServiceTest {
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor);
|
||||
|
||||
// A file that exists as an additional file (e.g. cover.jpg, or a misidentified book)
|
||||
LibraryFile additionalFileAsLibraryFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
@@ -268,25 +288,26 @@ class LibraryProcessingServiceTest {
|
||||
|
||||
BookEntity parentBook = new BookEntity();
|
||||
parentBook.setLibraryPath(pathEntity);
|
||||
|
||||
|
||||
BookFileEntity additionalFileEntity = new BookFileEntity();
|
||||
additionalFileEntity.setBook(parentBook); // Links to library path
|
||||
additionalFileEntity.setBook(parentBook);
|
||||
additionalFileEntity.setFileSubPath("");
|
||||
additionalFileEntity.setFileName("extra.pdf");
|
||||
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(additionalFileAsLibraryFile));
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(additionalFileAsLibraryFile));
|
||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(List.of(additionalFileEntity));
|
||||
when(bookGroupingService.groupForInitialScan(anyList(), eq(libraryEntity))).thenReturn(Collections.emptyMap());
|
||||
|
||||
libraryProcessingService.processLibrary(libraryId);
|
||||
|
||||
ArgumentCaptor<List<LibraryFile>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(libraryFileProcessor).processLibraryFiles(captor.capture(), eq(libraryEntity));
|
||||
verify(bookGroupingService).groupForInitialScan(captor.capture(), eq(libraryEntity));
|
||||
|
||||
assertThat(captor.getValue()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rescanLibrary_shouldNotDeleteNonBookFiles_whenProcessorDoesNotSupportSupplementaryFiles(@TempDir Path tempDir) throws IOException {
|
||||
void rescanLibrary_shouldDeleteRemovedBookFormatAdditionalFiles(@TempDir Path tempDir) throws IOException {
|
||||
long libraryId = 1L;
|
||||
Path accessiblePath = tempDir.resolve("library");
|
||||
Files.createDirectory(accessiblePath);
|
||||
@@ -294,7 +315,6 @@ class LibraryProcessingServiceTest {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
libraryEntity.setId(libraryId);
|
||||
libraryEntity.setName("Test Library");
|
||||
libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK);
|
||||
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(10L);
|
||||
@@ -331,9 +351,8 @@ class LibraryProcessingServiceTest {
|
||||
libraryEntity.setBookEntities(List.of(book));
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor);
|
||||
when(libraryFileProcessor.supportsSupplementaryFiles()).thenReturn(false);
|
||||
|
||||
// Only epub exists on disk, pdf was removed
|
||||
LibraryFile epubOnDisk = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
@@ -341,30 +360,27 @@ class LibraryProcessingServiceTest {
|
||||
.fileName("book.epub")
|
||||
.build();
|
||||
|
||||
LibraryFile pdfOnDisk = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("author/title")
|
||||
.fileName("book.pdf")
|
||||
.build();
|
||||
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(epubOnDisk, pdfOnDisk));
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(epubOnDisk));
|
||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(List.of(epub, pdf, image));
|
||||
when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity)))
|
||||
.thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap()));
|
||||
|
||||
libraryProcessingService.rescanLibrary(RescanLibraryContext.builder().libraryId(libraryId).build());
|
||||
|
||||
verify(bookDeletionService, never()).deleteRemovedAdditionalFiles(any());
|
||||
// pdf (book format) should be deleted; image (non-book format) should NOT be deleted
|
||||
ArgumentCaptor<List<Long>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(bookDeletionService).deleteRemovedAdditionalFiles(captor.capture());
|
||||
assertThat(captor.getValue()).containsExactly(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rescanLibrary_shouldAbortWhenPathNotAccessible(@TempDir Path tempDir) throws IOException {
|
||||
void rescanLibrary_shouldAbortWhenPathNotAccessible(@TempDir Path tempDir) {
|
||||
long libraryId = 1L;
|
||||
Path nonExistentPath = tempDir.resolve("non_existent_path");
|
||||
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
libraryEntity.setId(libraryId);
|
||||
libraryEntity.setName("Test Library");
|
||||
libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK);
|
||||
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(10L);
|
||||
@@ -373,7 +389,6 @@ class LibraryProcessingServiceTest {
|
||||
libraryEntity.setBookEntities(Collections.emptyList());
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor);
|
||||
|
||||
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
||||
|
||||
@@ -394,7 +409,6 @@ class LibraryProcessingServiceTest {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
libraryEntity.setId(libraryId);
|
||||
libraryEntity.setName("Test Library");
|
||||
libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK);
|
||||
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(10L);
|
||||
@@ -412,8 +426,7 @@ class LibraryProcessingServiceTest {
|
||||
libraryEntity.setBookEntities(List.of(existingBook));
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor);
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(Collections.emptyList());
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList());
|
||||
|
||||
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
||||
|
||||
@@ -434,7 +447,6 @@ class LibraryProcessingServiceTest {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
libraryEntity.setId(libraryId);
|
||||
libraryEntity.setName("Test Library");
|
||||
libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK);
|
||||
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(10L);
|
||||
@@ -459,9 +471,10 @@ class LibraryProcessingServiceTest {
|
||||
.build();
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor);
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(fileOnDisk));
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(fileOnDisk));
|
||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
||||
when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity)))
|
||||
.thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap()));
|
||||
|
||||
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
||||
|
||||
@@ -479,7 +492,6 @@ class LibraryProcessingServiceTest {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
libraryEntity.setId(libraryId);
|
||||
libraryEntity.setName("Test Library");
|
||||
libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK);
|
||||
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(10L);
|
||||
@@ -488,9 +500,10 @@ class LibraryProcessingServiceTest {
|
||||
libraryEntity.setBookEntities(Collections.emptyList());
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor);
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(Collections.emptyList());
|
||||
when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList());
|
||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
||||
when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity)))
|
||||
.thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap()));
|
||||
|
||||
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
||||
|
||||
|
||||
+19
-9
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.service.opds;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookFile;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.LibraryPath;
|
||||
import com.adityachandel.booklore.model.dto.OpdsUserV2;
|
||||
@@ -190,27 +191,36 @@ class OpdsFeedServiceMimeTypeTest {
|
||||
|
||||
@Test
|
||||
void testMimeTypeFromCachedArchiveType() {
|
||||
Book book = createBook(BookFileType.CBX, "whatever.cbz");
|
||||
book.setArchiveType(ArchiveUtils.ArchiveType.RAR); // Simulate mismatched but cached type
|
||||
|
||||
Book book = createBookWithArchiveType(BookFileType.CBX, "whatever.cbz", ArchiveUtils.ArchiveType.RAR);
|
||||
|
||||
mockBooksPage(book);
|
||||
|
||||
String xml = opdsFeedService.generateCatalogFeed(request);
|
||||
|
||||
|
||||
// Should use cached type (RAR) even if filename is .cbz and no file exists (mocked logic)
|
||||
// Note: The logic in OpdsFeedService prioritizes cached type.
|
||||
// However, my test creates a real file in other tests, but here I can skip file creation
|
||||
// However, my test creates a real file in other tests, but here I can skip file creation
|
||||
// because the cached type check happens first.
|
||||
|
||||
|
||||
assertThat(xml).contains("type=\"application/vnd.comicbook-rar\"");
|
||||
}
|
||||
|
||||
private Book createBook(BookFileType type, String fileName) {
|
||||
return createBookWithArchiveType(type, fileName, null);
|
||||
}
|
||||
|
||||
private Book createBookWithArchiveType(BookFileType type, String fileName, ArchiveUtils.ArchiveType archiveType) {
|
||||
String filePath = tempDir.resolve(fileName).toString();
|
||||
return Book.builder()
|
||||
.id(1L)
|
||||
.bookType(type)
|
||||
.fileName(fileName)
|
||||
.fileSubPath("")
|
||||
.primaryFile(BookFile.builder()
|
||||
.id(1L)
|
||||
.bookType(type)
|
||||
.fileName(fileName)
|
||||
.filePath(filePath)
|
||||
.fileSubPath("")
|
||||
.archiveType(archiveType)
|
||||
.build())
|
||||
.libraryPath(LibraryPath.builder().path(tempDir.toString()).build())
|
||||
.addedOn(Instant.now())
|
||||
.metadata(BookMetadata.builder().title("Test Book").build())
|
||||
|
||||
+7
-6
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.service.opds;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookFile;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.Library;
|
||||
import com.adityachandel.booklore.model.dto.OpdsUserV2;
|
||||
@@ -139,7 +140,7 @@ class OpdsFeedServiceTest {
|
||||
|
||||
Book book = Book.builder()
|
||||
.id(10L)
|
||||
.bookType(BookFileType.EPUB)
|
||||
.primaryFile(BookFile.builder().id(1L).bookType(BookFileType.EPUB).build())
|
||||
.addedOn(FIXED_INSTANT)
|
||||
.metadata(BookMetadata.builder()
|
||||
.title("Book Title")
|
||||
@@ -193,7 +194,7 @@ class OpdsFeedServiceTest {
|
||||
|
||||
Book book = Book.builder()
|
||||
.id(11L)
|
||||
.bookType(BookFileType.PDF)
|
||||
.primaryFile(BookFile.builder().id(1L).bookType(BookFileType.PDF).build())
|
||||
.addedOn(FIXED_INSTANT)
|
||||
.metadata(BookMetadata.builder().title("Recent Book").build())
|
||||
.build();
|
||||
@@ -231,7 +232,7 @@ class OpdsFeedServiceTest {
|
||||
|
||||
Book book = Book.builder()
|
||||
.id(12L)
|
||||
.bookType(BookFileType.EPUB)
|
||||
.primaryFile(BookFile.builder().id(1L).bookType(BookFileType.EPUB).build())
|
||||
.addedOn(FIXED_INSTANT)
|
||||
.metadata(BookMetadata.builder().title("Surprise Book").build())
|
||||
.build();
|
||||
@@ -391,7 +392,7 @@ class OpdsFeedServiceTest {
|
||||
|
||||
Book book = Book.builder()
|
||||
.id(1L)
|
||||
.bookType(BookFileType.EPUB)
|
||||
.primaryFile(BookFile.builder().id(1L).bookType(BookFileType.EPUB).build())
|
||||
.addedOn(FIXED_INSTANT)
|
||||
.metadata(BookMetadata.builder().title("Shelf Book").build())
|
||||
.build();
|
||||
@@ -426,7 +427,7 @@ class OpdsFeedServiceTest {
|
||||
|
||||
Book book = Book.builder()
|
||||
.id(1L)
|
||||
.bookType(BookFileType.EPUB)
|
||||
.primaryFile(BookFile.builder().id(1L).bookType(BookFileType.EPUB).build())
|
||||
.addedOn(FIXED_INSTANT)
|
||||
.metadata(BookMetadata.builder().title("Multi Shelf Book").build())
|
||||
.build();
|
||||
@@ -460,7 +461,7 @@ class OpdsFeedServiceTest {
|
||||
|
||||
Book book = Book.builder()
|
||||
.id(1L)
|
||||
.bookType(BookFileType.EPUB)
|
||||
.primaryFile(BookFile.builder().id(1L).bookType(BookFileType.EPUB).build())
|
||||
.addedOn(FIXED_INSTANT)
|
||||
.metadata(BookMetadata.builder().title("Fantasy Book").build())
|
||||
.build();
|
||||
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
package com.adityachandel.booklore.service.progress;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.APIException;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
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.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 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.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class ReadingProgressServiceTest {
|
||||
|
||||
@Mock
|
||||
private UserBookProgressRepository userBookProgressRepository;
|
||||
@Mock
|
||||
private UserBookFileProgressRepository userBookFileProgressRepository;
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
@Mock
|
||||
private BookFileRepository bookFileRepository;
|
||||
@Mock
|
||||
private UserRepository userRepository;
|
||||
@Mock
|
||||
private AuthenticationService authenticationService;
|
||||
@Mock
|
||||
private KoboReadingStateService koboReadingStateService;
|
||||
|
||||
@InjectMocks
|
||||
private ReadingProgressService readingProgressService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchUserProgress_shouldReturnProgressMap() {
|
||||
Long userId = 1L;
|
||||
Set<Long> bookIds = Set.of(1L, 2L);
|
||||
|
||||
BookEntity book1 = new BookEntity();
|
||||
book1.setId(1L);
|
||||
BookEntity book2 = new BookEntity();
|
||||
book2.setId(2L);
|
||||
|
||||
UserBookProgressEntity progress1 = new UserBookProgressEntity();
|
||||
progress1.setBook(book1);
|
||||
UserBookProgressEntity progress2 = new UserBookProgressEntity();
|
||||
progress2.setBook(book2);
|
||||
|
||||
when(userBookProgressRepository.findByUserIdAndBookIdIn(userId, bookIds))
|
||||
.thenReturn(List.of(progress1, progress2));
|
||||
|
||||
Map<Long, UserBookProgressEntity> result = readingProgressService.fetchUserProgress(userId, bookIds);
|
||||
|
||||
assertEquals(2, result.size());
|
||||
assertEquals(progress1, result.get(1L));
|
||||
assertEquals(progress2, result.get(2L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchUserFileProgress_emptyBookIds_shouldReturnEmptyMap() {
|
||||
Map<Long, UserBookFileProgressEntity> result =
|
||||
readingProgressService.fetchUserFileProgress(1L, Collections.emptySet());
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
verify(userBookFileProgressRepository, never()).findByUserIdAndBookFileBookIdIn(anyLong(), anySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchUserFileProgress_shouldReturnMostRecentPerBook() {
|
||||
Long userId = 1L;
|
||||
Set<Long> bookIds = Set.of(1L);
|
||||
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(1L);
|
||||
|
||||
BookFileEntity bookFile1 = new BookFileEntity();
|
||||
bookFile1.setBook(book);
|
||||
|
||||
BookFileEntity bookFile2 = new BookFileEntity();
|
||||
bookFile2.setBook(book);
|
||||
|
||||
UserBookFileProgressEntity progress1 = new UserBookFileProgressEntity();
|
||||
progress1.setBookFile(bookFile1);
|
||||
progress1.setLastReadTime(Instant.now().minusSeconds(100));
|
||||
|
||||
UserBookFileProgressEntity progress2 = new UserBookFileProgressEntity();
|
||||
progress2.setBookFile(bookFile2);
|
||||
progress2.setLastReadTime(Instant.now());
|
||||
|
||||
when(userBookFileProgressRepository.findByUserIdAndBookFileBookIdIn(userId, bookIds))
|
||||
.thenReturn(List.of(progress1, progress2));
|
||||
|
||||
Map<Long, UserBookFileProgressEntity> result =
|
||||
readingProgressService.fetchUserFileProgress(userId, bookIds);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(progress2, result.get(1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void enrichBookWithProgress_shouldSetProgressFields() {
|
||||
Book book = Book.builder().id(1L).build();
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setReadStatus(ReadStatus.READING);
|
||||
progress.setEpubProgress("cfi");
|
||||
progress.setEpubProgressPercent(50.0f);
|
||||
progress.setLastReadTime(Instant.now());
|
||||
|
||||
readingProgressService.enrichBookWithProgress(book, progress);
|
||||
|
||||
assertEquals("READING", book.getReadStatus());
|
||||
assertNotNull(book.getEpubProgress());
|
||||
assertEquals("cfi", book.getEpubProgress().getCfi());
|
||||
assertEquals(50.0f, book.getEpubProgress().getPercentage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enrichBookWithProgress_withFileProgress_shouldOverlayFileProgress() {
|
||||
Book book = Book.builder().id(1L).build();
|
||||
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setReadStatus(ReadStatus.READING);
|
||||
progress.setEpubProgress("old-cfi");
|
||||
progress.setEpubProgressPercent(30.0f);
|
||||
progress.setLastReadTime(Instant.now().minusSeconds(100));
|
||||
|
||||
BookFileEntity bookFile = new BookFileEntity();
|
||||
bookFile.setBookType(BookFileType.EPUB);
|
||||
|
||||
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
|
||||
fileProgress.setBookFile(bookFile);
|
||||
fileProgress.setPositionData("new-cfi");
|
||||
fileProgress.setProgressPercent(50.0f);
|
||||
fileProgress.setLastReadTime(Instant.now());
|
||||
|
||||
readingProgressService.enrichBookWithProgress(book, progress, fileProgress);
|
||||
|
||||
assertEquals("new-cfi", book.getEpubProgress().getCfi());
|
||||
assertEquals(50.0f, book.getEpubProgress().getPercentage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateReadProgress_epub_shouldSaveProgress() {
|
||||
long bookId = 1L;
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(bookId);
|
||||
BookFileEntity primaryFile = new BookFileEntity();
|
||||
primaryFile.setId(1L);
|
||||
primaryFile.setBook(book);
|
||||
primaryFile.setBookType(BookFileType.EPUB);
|
||||
book.setBookFiles(List.of(primaryFile));
|
||||
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(user.getId()).thenReturn(2L);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.of(book));
|
||||
|
||||
BookLoreUserEntity userEntity = new BookLoreUserEntity();
|
||||
userEntity.setId(2L);
|
||||
when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity));
|
||||
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress));
|
||||
|
||||
when(userBookFileProgressRepository.findByUserIdAndBookFileId(2L, 1L)).thenReturn(Optional.empty());
|
||||
|
||||
ReadProgressRequest req = new ReadProgressRequest();
|
||||
req.setBookId(bookId);
|
||||
EpubProgress epubProgress = EpubProgress.builder().cfi("cfi").percentage(100f).build();
|
||||
req.setEpubProgress(epubProgress);
|
||||
|
||||
readingProgressService.updateReadProgress(req);
|
||||
|
||||
verify(userBookProgressRepository).save(progress);
|
||||
assertEquals("cfi", progress.getEpubProgress());
|
||||
assertEquals(ReadStatus.READ, progress.getReadStatus());
|
||||
assertEquals(100f, progress.getEpubProgressPercent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateReadProgress_pdf_shouldSaveProgress() {
|
||||
long bookId = 1L;
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(bookId);
|
||||
BookFileEntity primaryFile = new BookFileEntity();
|
||||
primaryFile.setId(1L);
|
||||
primaryFile.setBook(book);
|
||||
primaryFile.setBookType(BookFileType.PDF);
|
||||
book.setBookFiles(List.of(primaryFile));
|
||||
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(user.getId()).thenReturn(2L);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.of(book));
|
||||
|
||||
BookLoreUserEntity userEntity = new BookLoreUserEntity();
|
||||
userEntity.setId(2L);
|
||||
when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity));
|
||||
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress));
|
||||
|
||||
when(userBookFileProgressRepository.findByUserIdAndBookFileId(2L, 1L)).thenReturn(Optional.empty());
|
||||
|
||||
ReadProgressRequest req = new ReadProgressRequest();
|
||||
req.setBookId(bookId);
|
||||
PdfProgress pdfProgress = PdfProgress.builder().page(5).percentage(50f).build();
|
||||
req.setPdfProgress(pdfProgress);
|
||||
|
||||
readingProgressService.updateReadProgress(req);
|
||||
|
||||
verify(userBookProgressRepository).save(progress);
|
||||
assertEquals(5, progress.getPdfProgress());
|
||||
assertEquals(ReadStatus.READING, progress.getReadStatus());
|
||||
assertEquals(50f, progress.getPdfProgressPercent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetProgress_booklore_shouldCallBulkReset() {
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
when(user.getId()).thenReturn(1L);
|
||||
|
||||
BookLoreUser.UserPermissions permissions = mock(BookLoreUser.UserPermissions.class);
|
||||
when(user.getPermissions()).thenReturn(permissions);
|
||||
when(permissions.isCanBulkResetBookloreReadProgress()).thenReturn(true);
|
||||
|
||||
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 = readingProgressService.resetProgress(bookIds, ResetProgressType.BOOKLORE);
|
||||
|
||||
verify(userBookProgressRepository).bulkResetBookloreProgress(eq(1L), eq(new ArrayList<>(bookIds)), any());
|
||||
assertEquals(2, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetProgress_shouldAllowSingleBookWithoutPermission() {
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
when(user.getId()).thenReturn(1L);
|
||||
|
||||
BookLoreUser.UserPermissions permissions = mock(BookLoreUser.UserPermissions.class);
|
||||
when(user.getPermissions()).thenReturn(permissions);
|
||||
when(permissions.isCanBulkResetBookloreReadProgress()).thenReturn(false);
|
||||
|
||||
List<Long> bookIds = Collections.singletonList(1L);
|
||||
when(bookRepository.countByIdIn(bookIds)).thenReturn(1L);
|
||||
Set<Long> existing = new HashSet<>(bookIds);
|
||||
when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing);
|
||||
|
||||
assertDoesNotThrow(() -> readingProgressService.resetProgress(bookIds, ResetProgressType.BOOKLORE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetProgress_shouldThrowIfNoBulkPermission() {
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
when(user.getId()).thenReturn(1L);
|
||||
|
||||
BookLoreUser.UserPermissions permissions = mock(BookLoreUser.UserPermissions.class);
|
||||
when(user.getPermissions()).thenReturn(permissions);
|
||||
when(permissions.isCanBulkResetBookloreReadProgress()).thenReturn(false);
|
||||
|
||||
List<Long> bookIds = Arrays.asList(1L, 2L);
|
||||
when(bookRepository.countByIdIn(bookIds)).thenReturn(2L);
|
||||
|
||||
assertThrows(APIException.class, () -> readingProgressService.resetProgress(bookIds, ResetProgressType.BOOKLORE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetProgress_kobo_shouldCallKoboService() {
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
when(user.getId()).thenReturn(1L);
|
||||
|
||||
List<Long> bookIds = Collections.singletonList(1L);
|
||||
when(bookRepository.countByIdIn(bookIds)).thenReturn(1L);
|
||||
Set<Long> existing = new HashSet<>(bookIds);
|
||||
when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing);
|
||||
|
||||
readingProgressService.resetProgress(bookIds, ResetProgressType.KOBO);
|
||||
|
||||
verify(userBookProgressRepository).bulkResetKoboProgress(eq(1L), anyList());
|
||||
verify(koboReadingStateService).deleteReadingState(1L);
|
||||
}
|
||||
}
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
package com.adityachandel.booklore.service.reader;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AudioFileUtilityServiceTest {
|
||||
|
||||
private AudioFileUtilityService audioFileUtility;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
audioFileUtility = new AudioFileUtilityService();
|
||||
}
|
||||
|
||||
// ==================== listAudioFiles tests ====================
|
||||
|
||||
@Test
|
||||
void listAudioFiles_returnsEmptyListForEmptyFolder() {
|
||||
List<Path> result = audioFileUtility.listAudioFiles(tempDir);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAudioFiles_returnsOnlyAudioFiles() throws IOException {
|
||||
// Create audio files
|
||||
Files.createFile(tempDir.resolve("track1.mp3"));
|
||||
Files.createFile(tempDir.resolve("track2.m4b"));
|
||||
Files.createFile(tempDir.resolve("track3.flac"));
|
||||
|
||||
// Create non-audio files
|
||||
Files.createFile(tempDir.resolve("readme.txt"));
|
||||
Files.createFile(tempDir.resolve("cover.jpg"));
|
||||
Files.createFile(tempDir.resolve("metadata.xml"));
|
||||
|
||||
List<Path> result = audioFileUtility.listAudioFiles(tempDir);
|
||||
|
||||
assertEquals(3, result.size());
|
||||
assertTrue(result.stream().anyMatch(p -> p.getFileName().toString().equals("track1.mp3")));
|
||||
assertTrue(result.stream().anyMatch(p -> p.getFileName().toString().equals("track2.m4b")));
|
||||
assertTrue(result.stream().anyMatch(p -> p.getFileName().toString().equals("track3.flac")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAudioFiles_sortsNaturally() throws IOException {
|
||||
// Create files in non-natural order
|
||||
Files.createFile(tempDir.resolve("Track 10.mp3"));
|
||||
Files.createFile(tempDir.resolve("Track 2.mp3"));
|
||||
Files.createFile(tempDir.resolve("Track 1.mp3"));
|
||||
Files.createFile(tempDir.resolve("Track 20.mp3"));
|
||||
Files.createFile(tempDir.resolve("Track 3.mp3"));
|
||||
|
||||
List<Path> result = audioFileUtility.listAudioFiles(tempDir);
|
||||
|
||||
assertEquals(5, result.size());
|
||||
assertEquals("Track 1.mp3", result.get(0).getFileName().toString());
|
||||
assertEquals("Track 2.mp3", result.get(1).getFileName().toString());
|
||||
assertEquals("Track 3.mp3", result.get(2).getFileName().toString());
|
||||
assertEquals("Track 10.mp3", result.get(3).getFileName().toString());
|
||||
assertEquals("Track 20.mp3", result.get(4).getFileName().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAudioFiles_handlesNumericPrefixes() throws IOException {
|
||||
Files.createFile(tempDir.resolve("01 - Introduction.mp3"));
|
||||
Files.createFile(tempDir.resolve("02 - Chapter One.mp3"));
|
||||
Files.createFile(tempDir.resolve("10 - Chapter Nine.mp3"));
|
||||
Files.createFile(tempDir.resolve("11 - Epilogue.mp3"));
|
||||
|
||||
List<Path> result = audioFileUtility.listAudioFiles(tempDir);
|
||||
|
||||
assertEquals(4, result.size());
|
||||
assertEquals("01 - Introduction.mp3", result.get(0).getFileName().toString());
|
||||
assertEquals("02 - Chapter One.mp3", result.get(1).getFileName().toString());
|
||||
assertEquals("10 - Chapter Nine.mp3", result.get(2).getFileName().toString());
|
||||
assertEquals("11 - Epilogue.mp3", result.get(3).getFileName().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAudioFiles_excludesDirectories() throws IOException {
|
||||
Files.createFile(tempDir.resolve("track1.mp3"));
|
||||
Files.createDirectory(tempDir.resolve("subfolder.mp3")); // Directory with mp3 extension
|
||||
|
||||
List<Path> result = audioFileUtility.listAudioFiles(tempDir);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("track1.mp3", result.get(0).getFileName().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAudioFiles_returnsEmptyListForNonexistentFolder() {
|
||||
Path nonexistent = tempDir.resolve("nonexistent");
|
||||
List<Path> result = audioFileUtility.listAudioFiles(nonexistent);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAudioFiles_handlesAllSupportedExtensions() throws IOException {
|
||||
Files.createFile(tempDir.resolve("track.mp3"));
|
||||
Files.createFile(tempDir.resolve("track.m4a"));
|
||||
Files.createFile(tempDir.resolve("track.m4b"));
|
||||
Files.createFile(tempDir.resolve("track.aac"));
|
||||
Files.createFile(tempDir.resolve("track.flac"));
|
||||
Files.createFile(tempDir.resolve("track.ogg"));
|
||||
Files.createFile(tempDir.resolve("track.opus"));
|
||||
|
||||
List<Path> result = audioFileUtility.listAudioFiles(tempDir);
|
||||
|
||||
assertEquals(7, result.size());
|
||||
}
|
||||
|
||||
// ==================== isAudioFile tests ====================
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"track.mp3", "book.m4b", "audio.m4a", "sound.aac", "music.flac", "song.ogg", "voice.opus"})
|
||||
void isAudioFile_returnsTrueForAudioExtensions(String filename) throws IOException {
|
||||
Path file = tempDir.resolve(filename);
|
||||
Files.createFile(file);
|
||||
assertTrue(audioFileUtility.isAudioFile(file));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"TRACK.MP3", "Book.M4B", "Audio.M4A", "SOUND.AAC", "Music.FLAC", "Song.OGG", "Voice.OPUS"})
|
||||
void isAudioFile_isCaseInsensitive(String filename) throws IOException {
|
||||
Path file = tempDir.resolve(filename);
|
||||
Files.createFile(file);
|
||||
assertTrue(audioFileUtility.isAudioFile(file));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"image.jpg", "document.pdf", "video.mp4", "text.txt", "archive.zip", "cover.png"})
|
||||
void isAudioFile_returnsFalseForNonAudioExtensions(String filename) throws IOException {
|
||||
Path file = tempDir.resolve(filename);
|
||||
Files.createFile(file);
|
||||
assertFalse(audioFileUtility.isAudioFile(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isAudioFile_returnsFalseForFileWithoutExtension() throws IOException {
|
||||
Path file = tempDir.resolve("noextension");
|
||||
Files.createFile(file);
|
||||
assertFalse(audioFileUtility.isAudioFile(file));
|
||||
}
|
||||
|
||||
// ==================== getContentType tests ====================
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"track.m4b, audio/mp4",
|
||||
"track.m4a, audio/mp4",
|
||||
"track.mp3, audio/mpeg",
|
||||
"track.aac, audio/aac",
|
||||
"track.flac, audio/flac",
|
||||
"track.ogg, audio/ogg",
|
||||
"track.opus, audio/opus"
|
||||
})
|
||||
void getContentType_returnsCorrectMimeType(String filename, String expectedMimeType) {
|
||||
Path file = tempDir.resolve(filename);
|
||||
assertEquals(expectedMimeType, audioFileUtility.getContentType(file));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"TRACK.M4B, audio/mp4",
|
||||
"TRACK.MP3, audio/mpeg",
|
||||
"Track.Flac, audio/flac"
|
||||
})
|
||||
void getContentType_isCaseInsensitive(String filename, String expectedMimeType) {
|
||||
Path file = tempDir.resolve(filename);
|
||||
assertEquals(expectedMimeType, audioFileUtility.getContentType(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getContentType_returnsOctetStreamForUnknownExtension() {
|
||||
Path file = tempDir.resolve("unknown.xyz");
|
||||
assertEquals("application/octet-stream", audioFileUtility.getContentType(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getContentType_returnsOctetStreamForNoExtension() {
|
||||
Path file = tempDir.resolve("noextension");
|
||||
assertEquals("application/octet-stream", audioFileUtility.getContentType(file));
|
||||
}
|
||||
|
||||
// ==================== getTrackTitleFromFilename tests ====================
|
||||
|
||||
@Test
|
||||
void getTrackTitleFromFilename_removesExtension() {
|
||||
assertEquals("Track Title", audioFileUtility.getTrackTitleFromFilename("Track Title.mp3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTrackTitleFromFilename_replacesUnderscoresWithSpaces() {
|
||||
assertEquals("Chapter One Introduction", audioFileUtility.getTrackTitleFromFilename("Chapter_One_Introduction.mp3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTrackTitleFromFilename_replacesHyphensWithSpaces() {
|
||||
assertEquals("Chapter One Introduction", audioFileUtility.getTrackTitleFromFilename("Chapter-One-Introduction.mp3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTrackTitleFromFilename_replacesMultipleUnderscoresAndHyphens() {
|
||||
assertEquals("Chapter One", audioFileUtility.getTrackTitleFromFilename("Chapter___One---.mp3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTrackTitleFromFilename_trimsWhitespace() {
|
||||
assertEquals("Track", audioFileUtility.getTrackTitleFromFilename(" Track .mp3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTrackTitleFromFilename_handlesNoExtension() {
|
||||
assertEquals("Track Title", audioFileUtility.getTrackTitleFromFilename("Track_Title"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTrackTitleFromFilename_handlesMultipleDots() {
|
||||
assertEquals("Track.v2", audioFileUtility.getTrackTitleFromFilename("Track.v2.mp3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTrackTitleFromFilename_preservesNumbers() {
|
||||
assertEquals("01 Chapter One", audioFileUtility.getTrackTitleFromFilename("01_Chapter_One.mp3"));
|
||||
}
|
||||
|
||||
// ==================== getSupportedExtensions tests ====================
|
||||
|
||||
@Test
|
||||
void getSupportedExtensions_returnsAllExpectedExtensions() {
|
||||
var extensions = audioFileUtility.getSupportedExtensions();
|
||||
|
||||
assertEquals(7, extensions.size());
|
||||
assertTrue(extensions.contains(".mp3"));
|
||||
assertTrue(extensions.contains(".m4a"));
|
||||
assertTrue(extensions.contains(".m4b"));
|
||||
assertTrue(extensions.contains(".aac"));
|
||||
assertTrue(extensions.contains(".flac"));
|
||||
assertTrue(extensions.contains(".ogg"));
|
||||
assertTrue(extensions.contains(".opus"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSupportedExtensions_returnsUnmodifiableSet() {
|
||||
var extensions = audioFileUtility.getSupportedExtensions();
|
||||
assertThrows(UnsupportedOperationException.class, () -> extensions.add(".wav"));
|
||||
}
|
||||
|
||||
// ==================== Natural sorting edge cases ====================
|
||||
|
||||
@Test
|
||||
void listAudioFiles_handlesMixedAlphanumericNames() throws IOException {
|
||||
Files.createFile(tempDir.resolve("a1.mp3"));
|
||||
Files.createFile(tempDir.resolve("a10.mp3"));
|
||||
Files.createFile(tempDir.resolve("a2.mp3"));
|
||||
Files.createFile(tempDir.resolve("b1.mp3"));
|
||||
|
||||
List<Path> result = audioFileUtility.listAudioFiles(tempDir);
|
||||
|
||||
assertEquals(4, result.size());
|
||||
assertEquals("a1.mp3", result.get(0).getFileName().toString());
|
||||
assertEquals("a2.mp3", result.get(1).getFileName().toString());
|
||||
assertEquals("a10.mp3", result.get(2).getFileName().toString());
|
||||
assertEquals("b1.mp3", result.get(3).getFileName().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAudioFiles_handlesLeadingZeros() throws IOException {
|
||||
Files.createFile(tempDir.resolve("001.mp3"));
|
||||
Files.createFile(tempDir.resolve("002.mp3"));
|
||||
Files.createFile(tempDir.resolve("010.mp3"));
|
||||
Files.createFile(tempDir.resolve("100.mp3"));
|
||||
|
||||
List<Path> result = audioFileUtility.listAudioFiles(tempDir);
|
||||
|
||||
assertEquals(4, result.size());
|
||||
assertEquals("001.mp3", result.get(0).getFileName().toString());
|
||||
assertEquals("002.mp3", result.get(1).getFileName().toString());
|
||||
assertEquals("010.mp3", result.get(2).getFileName().toString());
|
||||
assertEquals("100.mp3", result.get(3).getFileName().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAudioFiles_sortsCaseInsensitively() throws IOException {
|
||||
Files.createFile(tempDir.resolve("Alpha.mp3"));
|
||||
Files.createFile(tempDir.resolve("beta.mp3"));
|
||||
Files.createFile(tempDir.resolve("GAMMA.mp3"));
|
||||
|
||||
List<Path> result = audioFileUtility.listAudioFiles(tempDir);
|
||||
|
||||
assertEquals(3, result.size());
|
||||
assertEquals("Alpha.mp3", result.get(0).getFileName().toString());
|
||||
assertEquals("beta.mp3", result.get(1).getFileName().toString());
|
||||
assertEquals("GAMMA.mp3", result.get(2).getFileName().toString());
|
||||
}
|
||||
}
|
||||
+556
@@ -0,0 +1,556 @@
|
||||
package com.adityachandel.booklore.service.reader;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.response.AudiobookChapter;
|
||||
import com.adityachandel.booklore.model.dto.response.AudiobookInfo;
|
||||
import com.adityachandel.booklore.model.dto.response.AudiobookTrack;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import org.jaudiotagger.audio.AudioFile;
|
||||
import org.jaudiotagger.audio.AudioFileIO;
|
||||
import org.jaudiotagger.audio.AudioHeader;
|
||||
import org.jaudiotagger.tag.FieldKey;
|
||||
import org.jaudiotagger.tag.Tag;
|
||||
import org.jaudiotagger.tag.images.Artwork;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class AudioMetadataServiceTest {
|
||||
|
||||
@Mock
|
||||
AudioFileUtilityService audioFileUtility;
|
||||
|
||||
@InjectMocks
|
||||
AudioMetadataService audioMetadataService;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
BookEntity bookEntity;
|
||||
BookFileEntity bookFileEntity;
|
||||
Path audioPath;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
bookEntity = new BookEntity();
|
||||
bookEntity.setId(1L);
|
||||
|
||||
bookFileEntity = new BookFileEntity();
|
||||
bookFileEntity.setId(10L);
|
||||
bookFileEntity.setBook(bookEntity);
|
||||
bookFileEntity.setFolderBased(false);
|
||||
|
||||
audioPath = tempDir.resolve("audiobook.m4b");
|
||||
Files.createFile(audioPath);
|
||||
}
|
||||
|
||||
// ==================== getMetadata tests for single file ====================
|
||||
|
||||
@Test
|
||||
void getMetadata_singleFile_extractsBasicInfo() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
AudioHeader header = mock(AudioHeader.class);
|
||||
Tag tag = mock(Tag.class);
|
||||
|
||||
when(audioFile.getAudioHeader()).thenReturn(header);
|
||||
when(audioFile.getTag()).thenReturn(tag);
|
||||
when(header.getPreciseTrackLength()).thenReturn(3600.0); // 1 hour
|
||||
when(header.getBitRateAsNumber()).thenReturn(128L);
|
||||
when(header.getEncodingType()).thenReturn("AAC");
|
||||
when(header.getSampleRateAsNumber()).thenReturn(44100);
|
||||
when(header.getChannels()).thenReturn("Stereo");
|
||||
|
||||
when(tag.getFirst(FieldKey.TITLE)).thenReturn("Test Audiobook");
|
||||
when(tag.getFirst(FieldKey.ARTIST)).thenReturn("Test Author");
|
||||
when(tag.getFirst(FieldKey.COMPOSER)).thenReturn("Test Narrator");
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
|
||||
|
||||
assertNotNull(info);
|
||||
assertEquals(1L, info.getBookId());
|
||||
assertEquals(10L, info.getBookFileId());
|
||||
assertFalse(info.isFolderBased());
|
||||
assertEquals(3600000L, info.getDurationMs()); // 1 hour in ms
|
||||
assertEquals(128, info.getBitrate());
|
||||
assertEquals("AAC", info.getCodec());
|
||||
assertEquals(44100, info.getSampleRate());
|
||||
assertEquals(2, info.getChannels()); // Stereo = 2
|
||||
assertEquals("Test Audiobook", info.getTitle());
|
||||
assertEquals("Test Author", info.getAuthor());
|
||||
assertEquals("Test Narrator", info.getNarrator());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMetadata_singleFile_handlesNullTag() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
AudioHeader header = mock(AudioHeader.class);
|
||||
|
||||
when(audioFile.getAudioHeader()).thenReturn(header);
|
||||
when(audioFile.getTag()).thenReturn(null);
|
||||
when(header.getPreciseTrackLength()).thenReturn(1800.0);
|
||||
when(header.getBitRateAsNumber()).thenReturn(256L);
|
||||
when(header.getEncodingType()).thenReturn("MP3");
|
||||
when(header.getSampleRateAsNumber()).thenReturn(48000);
|
||||
when(header.getChannels()).thenReturn("Mono");
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
|
||||
|
||||
assertNotNull(info);
|
||||
assertEquals(1800000L, info.getDurationMs());
|
||||
assertEquals(1, info.getChannels()); // Mono = 1
|
||||
assertNull(info.getTitle());
|
||||
assertNull(info.getAuthor());
|
||||
assertNull(info.getNarrator());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMetadata_singleFile_createsDefaultChapterWhenNoChapters() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
AudioHeader header = mock(AudioHeader.class);
|
||||
|
||||
when(audioFile.getAudioHeader()).thenReturn(header);
|
||||
when(audioFile.getTag()).thenReturn(null);
|
||||
when(header.getPreciseTrackLength()).thenReturn(7200.0); // 2 hours
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
|
||||
|
||||
assertNotNull(info.getChapters());
|
||||
assertEquals(1, info.getChapters().size());
|
||||
AudiobookChapter chapter = info.getChapters().get(0);
|
||||
assertEquals(0, chapter.getIndex());
|
||||
assertEquals("Full Audiobook", chapter.getTitle());
|
||||
assertEquals(0L, chapter.getStartTimeMs());
|
||||
assertEquals(7200000L, chapter.getEndTimeMs());
|
||||
assertEquals(7200000L, chapter.getDurationMs());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMetadata_cachesResult() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
AudioHeader header = mock(AudioHeader.class);
|
||||
|
||||
when(audioFile.getAudioHeader()).thenReturn(header);
|
||||
when(audioFile.getTag()).thenReturn(null);
|
||||
when(header.getPreciseTrackLength()).thenReturn(100.0);
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
// First call
|
||||
AudiobookInfo info1 = audioMetadataService.getMetadata(bookFileEntity, audioPath);
|
||||
// Second call should use cache
|
||||
AudiobookInfo info2 = audioMetadataService.getMetadata(bookFileEntity, audioPath);
|
||||
|
||||
assertSame(info1, info2);
|
||||
// AudioFileIO.read should only be called once
|
||||
audioFileIOMock.verify(() -> AudioFileIO.read(audioPath.toFile()), times(1));
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== getMetadata tests for folder-based ====================
|
||||
|
||||
@Test
|
||||
void getMetadata_folderBased_extractsTracksInfo() throws Exception {
|
||||
bookFileEntity.setFolderBased(true);
|
||||
Path folderPath = tempDir.resolve("audiobook_folder");
|
||||
Files.createDirectory(folderPath);
|
||||
|
||||
Path track1 = folderPath.resolve("01 - Chapter One.mp3");
|
||||
Path track2 = folderPath.resolve("02 - Chapter Two.mp3");
|
||||
Files.createFile(track1);
|
||||
Files.createFile(track2);
|
||||
|
||||
when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1, track2));
|
||||
when(audioFileUtility.getTrackTitleFromFilename("01 - Chapter One.mp3")).thenReturn("01 - Chapter One");
|
||||
when(audioFileUtility.getTrackTitleFromFilename("02 - Chapter Two.mp3")).thenReturn("02 - Chapter Two");
|
||||
when(audioFileUtility.isAudioFile(any())).thenReturn(true);
|
||||
|
||||
AudioFile audioFile1 = mock(AudioFile.class);
|
||||
AudioFile audioFile2 = mock(AudioFile.class);
|
||||
AudioHeader header1 = mock(AudioHeader.class);
|
||||
AudioHeader header2 = mock(AudioHeader.class);
|
||||
Tag tag1 = mock(Tag.class);
|
||||
|
||||
when(audioFile1.getAudioHeader()).thenReturn(header1);
|
||||
when(audioFile1.getTag()).thenReturn(tag1);
|
||||
when(header1.getPreciseTrackLength()).thenReturn(1800.0); // 30 min
|
||||
when(header1.getBitRateAsNumber()).thenReturn(192L);
|
||||
when(header1.getEncodingType()).thenReturn("MP3");
|
||||
when(header1.getSampleRateAsNumber()).thenReturn(44100);
|
||||
when(header1.getChannels()).thenReturn("Stereo");
|
||||
when(tag1.getFirst(FieldKey.ALBUM)).thenReturn("Test Album");
|
||||
when(tag1.getFirst(FieldKey.ALBUM_ARTIST)).thenReturn("Test Author");
|
||||
when(tag1.getFirst(FieldKey.TITLE)).thenReturn("Chapter One");
|
||||
|
||||
when(audioFile2.getAudioHeader()).thenReturn(header2);
|
||||
when(audioFile2.getTag()).thenReturn(null);
|
||||
when(header2.getPreciseTrackLength()).thenReturn(2400.0); // 40 min
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(track1.toFile())).thenReturn(audioFile1);
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(track2.toFile())).thenReturn(audioFile2);
|
||||
|
||||
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, folderPath);
|
||||
|
||||
assertNotNull(info);
|
||||
assertTrue(info.isFolderBased());
|
||||
assertEquals(4200000L, info.getDurationMs()); // 30 + 40 min = 70 min
|
||||
assertEquals("Test Album", info.getTitle());
|
||||
assertEquals("Test Author", info.getAuthor());
|
||||
|
||||
List<AudiobookTrack> tracks = info.getTracks();
|
||||
assertNotNull(tracks);
|
||||
assertEquals(2, tracks.size());
|
||||
|
||||
assertEquals(0, tracks.get(0).getIndex());
|
||||
assertEquals("Chapter One", tracks.get(0).getTitle());
|
||||
assertEquals(1800000L, tracks.get(0).getDurationMs());
|
||||
assertEquals(0L, tracks.get(0).getCumulativeStartMs());
|
||||
|
||||
assertEquals(1, tracks.get(1).getIndex());
|
||||
assertEquals(2400000L, tracks.get(1).getDurationMs());
|
||||
assertEquals(1800000L, tracks.get(1).getCumulativeStartMs());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMetadata_folderBased_throwsExceptionForEmptyFolder() throws Exception {
|
||||
bookFileEntity.setFolderBased(true);
|
||||
Path folderPath = tempDir.resolve("empty_folder");
|
||||
Files.createDirectory(folderPath);
|
||||
|
||||
when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of());
|
||||
when(audioFileUtility.isAudioFile(any())).thenReturn(false);
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> audioMetadataService.getMetadata(bookFileEntity, folderPath));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMetadata_folderBased_usesFallbackTitleFromFilename() throws Exception {
|
||||
bookFileEntity.setFolderBased(true);
|
||||
Path folderPath = tempDir.resolve("audiobook_folder2");
|
||||
Files.createDirectory(folderPath);
|
||||
|
||||
Path track1 = folderPath.resolve("track.mp3");
|
||||
Files.createFile(track1);
|
||||
|
||||
when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1));
|
||||
when(audioFileUtility.getTrackTitleFromFilename("track.mp3")).thenReturn("track");
|
||||
when(audioFileUtility.isAudioFile(any())).thenReturn(true);
|
||||
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
AudioHeader header = mock(AudioHeader.class);
|
||||
Tag tag = mock(Tag.class);
|
||||
|
||||
when(audioFile.getAudioHeader()).thenReturn(header);
|
||||
when(audioFile.getTag()).thenReturn(tag);
|
||||
when(header.getPreciseTrackLength()).thenReturn(600.0);
|
||||
when(tag.getFirst(FieldKey.TITLE)).thenReturn(""); // Empty title
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(track1.toFile())).thenReturn(audioFile);
|
||||
|
||||
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, folderPath);
|
||||
|
||||
assertEquals("track", info.getTracks().get(0).getTitle());
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== getEmbeddedCoverArt tests ====================
|
||||
|
||||
@Test
|
||||
void getEmbeddedCoverArt_returnsArtworkData() throws Exception {
|
||||
byte[] expectedData = new byte[]{(byte) 0xFF, (byte) 0xD8, 0x00, 0x01};
|
||||
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
Tag tag = mock(Tag.class);
|
||||
Artwork artwork = mock(Artwork.class);
|
||||
|
||||
when(audioFile.getTag()).thenReturn(tag);
|
||||
when(tag.getFirstArtwork()).thenReturn(artwork);
|
||||
when(artwork.getBinaryData()).thenReturn(expectedData);
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
byte[] result = audioMetadataService.getEmbeddedCoverArt(audioPath);
|
||||
|
||||
assertArrayEquals(expectedData, result);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getEmbeddedCoverArt_returnsNullWhenNoArtwork() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
Tag tag = mock(Tag.class);
|
||||
|
||||
when(audioFile.getTag()).thenReturn(tag);
|
||||
when(tag.getFirstArtwork()).thenReturn(null);
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
byte[] result = audioMetadataService.getEmbeddedCoverArt(audioPath);
|
||||
|
||||
assertNull(result);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getEmbeddedCoverArt_returnsNullWhenNoTag() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
when(audioFile.getTag()).thenReturn(null);
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
byte[] result = audioMetadataService.getEmbeddedCoverArt(audioPath);
|
||||
|
||||
assertNull(result);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getEmbeddedCoverArt_returnsNullOnException() {
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenThrow(new RuntimeException("Read error"));
|
||||
|
||||
byte[] result = audioMetadataService.getEmbeddedCoverArt(audioPath);
|
||||
|
||||
assertNull(result);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== getCoverArtMimeType tests ====================
|
||||
|
||||
@Test
|
||||
void getCoverArtMimeType_returnsMimeTypeFromArtwork() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
Tag tag = mock(Tag.class);
|
||||
Artwork artwork = mock(Artwork.class);
|
||||
|
||||
when(audioFile.getTag()).thenReturn(tag);
|
||||
when(tag.getFirstArtwork()).thenReturn(artwork);
|
||||
when(artwork.getMimeType()).thenReturn("image/png");
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
String result = audioMetadataService.getCoverArtMimeType(audioPath);
|
||||
|
||||
assertEquals("image/png", result);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCoverArtMimeType_detectsJpegFromMagicBytes() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
Tag tag = mock(Tag.class);
|
||||
Artwork artwork = mock(Artwork.class);
|
||||
|
||||
when(audioFile.getTag()).thenReturn(tag);
|
||||
when(tag.getFirstArtwork()).thenReturn(artwork);
|
||||
when(artwork.getMimeType()).thenReturn(null);
|
||||
when(artwork.getBinaryData()).thenReturn(new byte[]{(byte) 0xFF, (byte) 0xD8, 0x00});
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
String result = audioMetadataService.getCoverArtMimeType(audioPath);
|
||||
|
||||
assertEquals("image/jpeg", result);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCoverArtMimeType_detectsPngFromMagicBytes() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
Tag tag = mock(Tag.class);
|
||||
Artwork artwork = mock(Artwork.class);
|
||||
|
||||
when(audioFile.getTag()).thenReturn(tag);
|
||||
when(tag.getFirstArtwork()).thenReturn(artwork);
|
||||
when(artwork.getMimeType()).thenReturn("");
|
||||
when(artwork.getBinaryData()).thenReturn(new byte[]{(byte) 0x89, (byte) 0x50, 0x4E, 0x47});
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
String result = audioMetadataService.getCoverArtMimeType(audioPath);
|
||||
|
||||
assertEquals("image/png", result);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCoverArtMimeType_returnsDefaultJpegWhenCannotDetermine() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
Tag tag = mock(Tag.class);
|
||||
Artwork artwork = mock(Artwork.class);
|
||||
|
||||
when(audioFile.getTag()).thenReturn(tag);
|
||||
when(tag.getFirstArtwork()).thenReturn(artwork);
|
||||
when(artwork.getMimeType()).thenReturn(null);
|
||||
when(artwork.getBinaryData()).thenReturn(new byte[]{0x00, 0x01});
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
String result = audioMetadataService.getCoverArtMimeType(audioPath);
|
||||
|
||||
assertEquals("image/jpeg", result);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCoverArtMimeType_returnsJpegOnException() {
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
String result = audioMetadataService.getCoverArtMimeType(audioPath);
|
||||
|
||||
assertEquals("image/jpeg", result);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Channel parsing tests ====================
|
||||
|
||||
@Test
|
||||
void getMetadata_parsesStereoChannels() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
AudioHeader header = mock(AudioHeader.class);
|
||||
|
||||
when(audioFile.getAudioHeader()).thenReturn(header);
|
||||
when(audioFile.getTag()).thenReturn(null);
|
||||
when(header.getPreciseTrackLength()).thenReturn(100.0);
|
||||
when(header.getChannels()).thenReturn("Stereo");
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
|
||||
assertEquals(2, info.getChannels());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMetadata_parsesMonoChannels() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
AudioHeader header = mock(AudioHeader.class);
|
||||
|
||||
when(audioFile.getAudioHeader()).thenReturn(header);
|
||||
when(audioFile.getTag()).thenReturn(null);
|
||||
when(header.getPreciseTrackLength()).thenReturn(100.0);
|
||||
when(header.getChannels()).thenReturn("Mono");
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
|
||||
assertEquals(1, info.getChannels());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMetadata_parsesNumericChannels() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
AudioHeader header = mock(AudioHeader.class);
|
||||
|
||||
when(audioFile.getAudioHeader()).thenReturn(header);
|
||||
when(audioFile.getTag()).thenReturn(null);
|
||||
when(header.getPreciseTrackLength()).thenReturn(100.0);
|
||||
when(header.getChannels()).thenReturn("6 channels");
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
|
||||
assertEquals(6, info.getChannels());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMetadata_handlesNullChannels() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
AudioHeader header = mock(AudioHeader.class);
|
||||
|
||||
when(audioFile.getAudioHeader()).thenReturn(header);
|
||||
when(audioFile.getTag()).thenReturn(null);
|
||||
when(header.getPreciseTrackLength()).thenReturn(100.0);
|
||||
when(header.getChannels()).thenReturn(null);
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
|
||||
assertNull(info.getChannels());
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Bitrate handling ====================
|
||||
|
||||
@Test
|
||||
void getMetadata_handlesZeroBitrate() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
AudioHeader header = mock(AudioHeader.class);
|
||||
|
||||
when(audioFile.getAudioHeader()).thenReturn(header);
|
||||
when(audioFile.getTag()).thenReturn(null);
|
||||
when(header.getPreciseTrackLength()).thenReturn(100.0);
|
||||
when(header.getBitRateAsNumber()).thenReturn(0L);
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
|
||||
assertNull(info.getBitrate());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMetadata_handlesNegativeBitrate() throws Exception {
|
||||
AudioFile audioFile = mock(AudioFile.class);
|
||||
AudioHeader header = mock(AudioHeader.class);
|
||||
|
||||
when(audioFile.getAudioHeader()).thenReturn(header);
|
||||
when(audioFile.getTag()).thenReturn(null);
|
||||
when(header.getPreciseTrackLength()).thenReturn(100.0);
|
||||
when(header.getBitRateAsNumber()).thenReturn(-1L);
|
||||
|
||||
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
|
||||
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
|
||||
|
||||
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
|
||||
assertNull(info.getBitrate());
|
||||
}
|
||||
}
|
||||
}
|
||||
+423
@@ -0,0 +1,423 @@
|
||||
package com.adityachandel.booklore.service.reader;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.response.AudiobookInfo;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.FileStreamingService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class AudiobookReaderServiceTest {
|
||||
|
||||
@Mock
|
||||
BookRepository bookRepository;
|
||||
|
||||
@Mock
|
||||
AudioMetadataService audioMetadataService;
|
||||
|
||||
@Mock
|
||||
AudioFileUtilityService audioFileUtility;
|
||||
|
||||
@Mock
|
||||
FileStreamingService fileStreamingService;
|
||||
|
||||
@InjectMocks
|
||||
AudiobookReaderService audiobookReaderService;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
BookEntity bookEntity;
|
||||
BookFileEntity audiobookFileEntity;
|
||||
BookFileEntity folderAudiobookFileEntity;
|
||||
Path audioPath;
|
||||
Path folderPath;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
audioPath = tempDir.resolve("audiobook.m4b");
|
||||
Files.createFile(audioPath);
|
||||
|
||||
folderPath = tempDir.resolve("audiobook_folder");
|
||||
Files.createDirectory(folderPath);
|
||||
|
||||
bookEntity = mock(BookEntity.class);
|
||||
when(bookEntity.getId()).thenReturn(1L);
|
||||
|
||||
audiobookFileEntity = mock(BookFileEntity.class);
|
||||
when(audiobookFileEntity.getId()).thenReturn(10L);
|
||||
when(audiobookFileEntity.getBook()).thenReturn(bookEntity);
|
||||
when(audiobookFileEntity.getBookType()).thenReturn(BookFileType.AUDIOBOOK);
|
||||
when(audiobookFileEntity.isFolderBased()).thenReturn(false);
|
||||
when(audiobookFileEntity.isBookFormat()).thenReturn(true);
|
||||
when(audiobookFileEntity.getFullFilePath()).thenReturn(audioPath);
|
||||
when(audiobookFileEntity.getFirstAudioFile()).thenReturn(audioPath);
|
||||
|
||||
folderAudiobookFileEntity = mock(BookFileEntity.class);
|
||||
when(folderAudiobookFileEntity.getId()).thenReturn(20L);
|
||||
when(folderAudiobookFileEntity.getBook()).thenReturn(bookEntity);
|
||||
when(folderAudiobookFileEntity.getBookType()).thenReturn(BookFileType.AUDIOBOOK);
|
||||
when(folderAudiobookFileEntity.isFolderBased()).thenReturn(true);
|
||||
when(folderAudiobookFileEntity.isBookFormat()).thenReturn(true);
|
||||
when(folderAudiobookFileEntity.getFullFilePath()).thenReturn(folderPath);
|
||||
|
||||
List<BookFileEntity> bookFiles = new ArrayList<>();
|
||||
bookFiles.add(audiobookFileEntity);
|
||||
when(bookEntity.getBookFiles()).thenReturn(bookFiles);
|
||||
}
|
||||
|
||||
// ==================== getAudiobookInfo tests ====================
|
||||
|
||||
@Test
|
||||
void getAudiobookInfo_returnsInfoFromMetadataService() throws Exception {
|
||||
AudiobookInfo expectedInfo = AudiobookInfo.builder()
|
||||
.bookId(1L)
|
||||
.bookFileId(10L)
|
||||
.title("Test Audiobook")
|
||||
.author("Test Author")
|
||||
.durationMs(3600000L)
|
||||
.build();
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioMetadataService.getMetadata(audiobookFileEntity, audioPath)).thenReturn(expectedInfo);
|
||||
|
||||
AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, null);
|
||||
|
||||
assertEquals(expectedInfo, result);
|
||||
verify(audioMetadataService).getMetadata(audiobookFileEntity, audioPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAudiobookInfo_withBookType_selectsCorrectFile() throws Exception {
|
||||
BookFileEntity epubFile = mock(BookFileEntity.class);
|
||||
when(epubFile.getId()).thenReturn(30L);
|
||||
when(epubFile.getBookType()).thenReturn(BookFileType.EPUB);
|
||||
|
||||
List<BookFileEntity> bookFiles = new ArrayList<>();
|
||||
bookFiles.add(audiobookFileEntity);
|
||||
bookFiles.add(epubFile);
|
||||
when(bookEntity.getBookFiles()).thenReturn(bookFiles);
|
||||
|
||||
AudiobookInfo expectedInfo = AudiobookInfo.builder().bookId(1L).build();
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioMetadataService.getMetadata(audiobookFileEntity, audioPath)).thenReturn(expectedInfo);
|
||||
|
||||
AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, "AUDIOBOOK");
|
||||
|
||||
assertEquals(expectedInfo, result);
|
||||
verify(audioMetadataService).getMetadata(eq(audiobookFileEntity), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAudiobookInfo_throwsExceptionWhenBookNotFound() {
|
||||
when(bookRepository.findByIdWithBookFiles(999L)).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(ApiError.BOOK_NOT_FOUND.createException().getClass(),
|
||||
() -> audiobookReaderService.getAudiobookInfo(999L, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAudiobookInfo_throwsExceptionWhenNoAudiobookFile() {
|
||||
BookFileEntity epubFile = mock(BookFileEntity.class);
|
||||
when(epubFile.getBookType()).thenReturn(BookFileType.EPUB);
|
||||
|
||||
List<BookFileEntity> bookFiles = new ArrayList<>();
|
||||
bookFiles.add(epubFile);
|
||||
when(bookEntity.getBookFiles()).thenReturn(bookFiles);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
|
||||
assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(),
|
||||
() -> audiobookReaderService.getAudiobookInfo(1L, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAudiobookInfo_throwsExceptionWhenRequestedTypeNotFound() {
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
|
||||
assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(),
|
||||
() -> audiobookReaderService.getAudiobookInfo(1L, "EPUB"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAudiobookInfo_wrapsMetadataServiceException() throws Exception {
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioMetadataService.getMetadata(any(), any())).thenThrow(new RuntimeException("Parse error"));
|
||||
|
||||
assertThrows(ApiError.FILE_READ_ERROR.createException().getClass(),
|
||||
() -> audiobookReaderService.getAudiobookInfo(1L, null));
|
||||
}
|
||||
|
||||
// ==================== getAudioFilePath tests ====================
|
||||
|
||||
@Test
|
||||
void getAudioFilePath_singleFile_returnsFilePath() {
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
|
||||
Path result = audiobookReaderService.getAudioFilePath(1L, null, null);
|
||||
|
||||
assertEquals(audioPath, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAudioFilePath_singleFile_ignoresTrackIndex() {
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
|
||||
Path result = audiobookReaderService.getAudioFilePath(1L, null, 5);
|
||||
|
||||
assertEquals(audioPath, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAudioFilePath_folderBased_returnsTrackPath() throws IOException {
|
||||
List<BookFileEntity> bookFiles = new ArrayList<>();
|
||||
bookFiles.add(folderAudiobookFileEntity);
|
||||
when(bookEntity.getBookFiles()).thenReturn(bookFiles);
|
||||
|
||||
Path track1 = folderPath.resolve("track1.mp3");
|
||||
Path track2 = folderPath.resolve("track2.mp3");
|
||||
Files.createFile(track1);
|
||||
Files.createFile(track2);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1, track2));
|
||||
|
||||
Path result = audiobookReaderService.getAudioFilePath(1L, null, 1);
|
||||
|
||||
assertEquals(track2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAudioFilePath_folderBased_defaultsToFirstTrack() throws IOException {
|
||||
List<BookFileEntity> bookFiles = new ArrayList<>();
|
||||
bookFiles.add(folderAudiobookFileEntity);
|
||||
when(bookEntity.getBookFiles()).thenReturn(bookFiles);
|
||||
|
||||
Path track1 = folderPath.resolve("track1.mp3");
|
||||
Files.createFile(track1);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1));
|
||||
|
||||
Path result = audiobookReaderService.getAudioFilePath(1L, null, null);
|
||||
|
||||
assertEquals(track1, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAudioFilePath_folderBased_throwsExceptionForInvalidIndex() throws IOException {
|
||||
List<BookFileEntity> bookFiles = new ArrayList<>();
|
||||
bookFiles.add(folderAudiobookFileEntity);
|
||||
when(bookEntity.getBookFiles()).thenReturn(bookFiles);
|
||||
|
||||
Path track1 = folderPath.resolve("track1.mp3");
|
||||
Files.createFile(track1);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1));
|
||||
|
||||
assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(),
|
||||
() -> audiobookReaderService.getAudioFilePath(1L, null, 10));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAudioFilePath_folderBased_throwsExceptionForNegativeIndex() throws IOException {
|
||||
List<BookFileEntity> bookFiles = new ArrayList<>();
|
||||
bookFiles.add(folderAudiobookFileEntity);
|
||||
when(bookEntity.getBookFiles()).thenReturn(bookFiles);
|
||||
|
||||
Path track1 = folderPath.resolve("track1.mp3");
|
||||
Files.createFile(track1);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1));
|
||||
|
||||
assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(),
|
||||
() -> audiobookReaderService.getAudioFilePath(1L, null, -1));
|
||||
}
|
||||
|
||||
// ==================== streamWithRangeSupport tests ====================
|
||||
|
||||
@Test
|
||||
void streamWithRangeSupport_delegatesToFileStreamingService() throws IOException {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
|
||||
when(audioFileUtility.getContentType(audioPath)).thenReturn("audio/mp4");
|
||||
|
||||
audiobookReaderService.streamWithRangeSupport(audioPath, request, response);
|
||||
|
||||
verify(audioFileUtility).getContentType(audioPath);
|
||||
verify(fileStreamingService).streamWithRangeSupport(audioPath, "audio/mp4", request, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamWithRangeSupport_usesCorrectContentType() throws IOException {
|
||||
Path mp3Path = tempDir.resolve("audio.mp3");
|
||||
Files.createFile(mp3Path);
|
||||
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
|
||||
when(audioFileUtility.getContentType(mp3Path)).thenReturn("audio/mpeg");
|
||||
|
||||
audiobookReaderService.streamWithRangeSupport(mp3Path, request, response);
|
||||
|
||||
verify(fileStreamingService).streamWithRangeSupport(mp3Path, "audio/mpeg", request, response);
|
||||
}
|
||||
|
||||
// ==================== getEmbeddedCoverArt tests ====================
|
||||
|
||||
@Test
|
||||
void getEmbeddedCoverArt_delegatesToMetadataService() {
|
||||
byte[] expectedData = new byte[]{0x01, 0x02, 0x03};
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioMetadataService.getEmbeddedCoverArt(audioPath)).thenReturn(expectedData);
|
||||
|
||||
byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null);
|
||||
|
||||
assertArrayEquals(expectedData, result);
|
||||
verify(audioMetadataService).getEmbeddedCoverArt(audioPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getEmbeddedCoverArt_folderBased_usesFirstAudioFile() throws IOException {
|
||||
List<BookFileEntity> bookFiles = new ArrayList<>();
|
||||
bookFiles.add(folderAudiobookFileEntity);
|
||||
when(bookEntity.getBookFiles()).thenReturn(bookFiles);
|
||||
|
||||
Path track1 = folderPath.resolve("track1.mp3");
|
||||
Files.createFile(track1);
|
||||
when(folderAudiobookFileEntity.getFirstAudioFile()).thenReturn(track1);
|
||||
|
||||
byte[] expectedData = new byte[]{0x04, 0x05};
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioMetadataService.getEmbeddedCoverArt(track1)).thenReturn(expectedData);
|
||||
|
||||
byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null);
|
||||
|
||||
assertArrayEquals(expectedData, result);
|
||||
verify(audioMetadataService).getEmbeddedCoverArt(track1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getEmbeddedCoverArt_returnsNullWhenNoCoverArt() {
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioMetadataService.getEmbeddedCoverArt(audioPath)).thenReturn(null);
|
||||
|
||||
byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null);
|
||||
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
// ==================== getCoverArtMimeType tests ====================
|
||||
|
||||
@Test
|
||||
void getCoverArtMimeType_delegatesToMetadataService() {
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioMetadataService.getCoverArtMimeType(audioPath)).thenReturn("image/png");
|
||||
|
||||
String result = audiobookReaderService.getCoverArtMimeType(1L, null);
|
||||
|
||||
assertEquals("image/png", result);
|
||||
verify(audioMetadataService).getCoverArtMimeType(audioPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCoverArtMimeType_folderBased_usesFirstAudioFile() throws IOException {
|
||||
List<BookFileEntity> bookFiles = new ArrayList<>();
|
||||
bookFiles.add(folderAudiobookFileEntity);
|
||||
when(bookEntity.getBookFiles()).thenReturn(bookFiles);
|
||||
|
||||
Path track1 = folderPath.resolve("track1.mp3");
|
||||
Files.createFile(track1);
|
||||
when(folderAudiobookFileEntity.getFirstAudioFile()).thenReturn(track1);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioMetadataService.getCoverArtMimeType(track1)).thenReturn("image/jpeg");
|
||||
|
||||
String result = audiobookReaderService.getCoverArtMimeType(1L, null);
|
||||
|
||||
assertEquals("image/jpeg", result);
|
||||
}
|
||||
|
||||
// ==================== getContentType tests ====================
|
||||
|
||||
@Test
|
||||
void getContentType_delegatesToAudioFileUtility() {
|
||||
when(audioFileUtility.getContentType(audioPath)).thenReturn("audio/mp4");
|
||||
|
||||
String result = audiobookReaderService.getContentType(audioPath);
|
||||
|
||||
assertEquals("audio/mp4", result);
|
||||
verify(audioFileUtility).getContentType(audioPath);
|
||||
}
|
||||
|
||||
// ==================== Book file selection tests ====================
|
||||
|
||||
@Test
|
||||
void getAudiobookInfo_selectsAudiobookWithBookFormat() throws Exception {
|
||||
BookFileEntity audiobookWithoutBookFormat = mock(BookFileEntity.class);
|
||||
when(audiobookWithoutBookFormat.getId()).thenReturn(40L);
|
||||
when(audiobookWithoutBookFormat.getBookType()).thenReturn(BookFileType.AUDIOBOOK);
|
||||
when(audiobookWithoutBookFormat.isBookFormat()).thenReturn(false);
|
||||
|
||||
List<BookFileEntity> bookFiles = new ArrayList<>();
|
||||
bookFiles.add(audiobookFileEntity);
|
||||
bookFiles.add(audiobookWithoutBookFormat);
|
||||
when(bookEntity.getBookFiles()).thenReturn(bookFiles);
|
||||
|
||||
AudiobookInfo expectedInfo = AudiobookInfo.builder().bookId(1L).build();
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioMetadataService.getMetadata(eq(audiobookFileEntity), any())).thenReturn(expectedInfo);
|
||||
|
||||
AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, null);
|
||||
|
||||
assertEquals(expectedInfo, result);
|
||||
verify(audioMetadataService).getMetadata(eq(audiobookFileEntity), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAudiobookInfo_bookTypeIsCaseInsensitive() throws Exception {
|
||||
AudiobookInfo expectedInfo = AudiobookInfo.builder().bookId(1L).build();
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
when(audioMetadataService.getMetadata(any(), any())).thenReturn(expectedInfo);
|
||||
|
||||
// Test lowercase
|
||||
audiobookReaderService.getAudiobookInfo(1L, "audiobook");
|
||||
verify(audioMetadataService, times(1)).getMetadata(any(), any());
|
||||
|
||||
// Test mixed case
|
||||
audiobookReaderService.getAudiobookInfo(1L, "AudioBook");
|
||||
verify(audioMetadataService, times(2)).getMetadata(any(), any());
|
||||
}
|
||||
}
|
||||
+684
@@ -0,0 +1,684 @@
|
||||
package com.adityachandel.booklore.util;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class BookFileGroupingUtilsTest {
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldStripExtension() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit.pdf")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit.epub")).isEqualTo("the hobbit");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldStripFormatIndicators() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (PDF).pdf")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (EPUB).epub")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit [pdf].pdf")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit [EPUB].epub")).isEqualTo("the hobbit");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldBeCaseInsensitive() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("THE HOBBIT.pdf"))
|
||||
.isEqualTo(BookFileGroupingUtils.extractGroupingKey("the hobbit.epub"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldNormalizeWhitespace() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit.pdf")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey(" The Hobbit .pdf")).isEqualTo("the hobbit");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldHandleNullAndEmpty() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey(null)).isEqualTo("");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("")).isEqualTo("");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldHandleFileWithNoExtension() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("noextension")).isEqualTo("noextension");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldNotStripDotsThatAreNotExtensions() {
|
||||
// Folder names with dots (like "1. American Gods") should not be stripped
|
||||
// The dot after "1" is NOT a file extension
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("1. American Gods - Neil Gaiman (2011)"))
|
||||
.isEqualTo("1. american gods - neil gaiman (2011)");
|
||||
// Series numbering with dots
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Vol. 1 - Adventures (2020)"))
|
||||
.isEqualTo("vol. 1 - adventures (2020)");
|
||||
// Title with dots
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Dr. Seuss Collection"))
|
||||
.isEqualTo("dr. seuss collection");
|
||||
// Multiple dots that are not extensions
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("U.S.A. History"))
|
||||
.isEqualTo("u.s.a. history");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldHandleMultipleFormatIndicators() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Book (PDF) (EPUB).pdf")).isEqualTo("book");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldNotStripNonFormatParentheses() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Book (Extended Edition).pdf")).isEqualTo("book (extended edition)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateDirectoryGroupKey_shouldCombineSubPathAndGroupingKey() {
|
||||
String key = BookFileGroupingUtils.generateDirectoryGroupKey("fantasy/tolkien", "The Hobbit.pdf");
|
||||
assertThat(key).isEqualTo("fantasy/tolkien:the hobbit");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateDirectoryGroupKey_shouldHandleNullSubPath() {
|
||||
String key = BookFileGroupingUtils.generateDirectoryGroupKey(null, "The Hobbit.pdf");
|
||||
assertThat(key).isEqualTo(":the hobbit");
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupFilesWithSameBaseNameInSameDirectory() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile epub = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("books")
|
||||
.fileName("The Hobbit.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile pdf = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("books")
|
||||
.fileName("The Hobbit.pdf")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, pdf));
|
||||
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, pdf);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldSeparateFilesInDifferentDirectories() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile file1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("dir1")
|
||||
.fileName("book.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile file2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("dir2")
|
||||
.fileName("book.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2));
|
||||
|
||||
assertThat(groups).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldSeparateFilesFromDifferentLibraryPaths() {
|
||||
LibraryPathEntity path1 = new LibraryPathEntity();
|
||||
path1.setId(1L);
|
||||
path1.setPath("/library1");
|
||||
|
||||
LibraryPathEntity path2 = new LibraryPathEntity();
|
||||
path2.setId(2L);
|
||||
path2.setPath("/library2");
|
||||
|
||||
LibraryFile file1 = LibraryFile.builder()
|
||||
.libraryPathEntity(path1)
|
||||
.fileSubPath("books")
|
||||
.fileName("book.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile file2 = LibraryFile.builder()
|
||||
.libraryPathEntity(path2)
|
||||
.fileSubPath("books")
|
||||
.fileName("book.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2));
|
||||
|
||||
assertThat(groups).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupFormatIndicatorVariants() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile epub = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("books")
|
||||
.fileName("The Hobbit.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile pdf = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("books")
|
||||
.fileName("The Hobbit (PDF).pdf")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, pdf));
|
||||
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, pdf);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldConvertUnderscoresToSpaces() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The_Hobbit.pdf")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Lord_of_the_Rings.epub")).isEqualTo("lord of the rings");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldStripTrailingAuthor() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit - J.R.R. Tolkien.pdf")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("1984 - George Orwell.epub")).isEqualTo("1984");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Pride and Prejudice - Jane Austen.pdf")).isEqualTo("pride and prejudice");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldRepositionArticles() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Hobbit, The.pdf")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Tale of Two Cities, A.epub")).isEqualTo("a tale of two cities");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Unexpected Journey, An.pdf")).isEqualTo("an unexpected journey");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldHandleCombinedNormalizations() {
|
||||
// Underscores + author
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The_Hobbit - J.R.R. Tolkien.pdf")).isEqualTo("the hobbit");
|
||||
// Article + author
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Hobbit, The - J.R.R. Tolkien.pdf")).isEqualTo("the hobbit");
|
||||
// Underscores + article
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Hobbit,_The.pdf")).isEqualTo("the hobbit");
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculateSimilarity_shouldReturnHighScoreForSimilarStrings() {
|
||||
double similarity = BookFileGroupingUtils.calculateSimilarity("the hobbit", "the hobit");
|
||||
assertThat(similarity).isGreaterThan(0.8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculateSimilarity_shouldReturnPerfectScoreForIdenticalStrings() {
|
||||
double similarity = BookFileGroupingUtils.calculateSimilarity("the hobbit", "the hobbit");
|
||||
assertThat(similarity).isEqualTo(1.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculateSimilarity_shouldReturnLowScoreForDifferentStrings() {
|
||||
double similarity = BookFileGroupingUtils.calculateSimilarity("the hobbit", "1984");
|
||||
assertThat(similarity).isLessThan(0.5);
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculateSimilarity_shouldHandleNullAndEmptyStrings() {
|
||||
assertThat(BookFileGroupingUtils.calculateSimilarity(null, "test")).isEqualTo(0);
|
||||
assertThat(BookFileGroupingUtils.calculateSimilarity("test", null)).isEqualTo(0);
|
||||
assertThat(BookFileGroupingUtils.calculateSimilarity("", "test")).isEqualTo(0);
|
||||
assertThat(BookFileGroupingUtils.calculateSimilarity("test", "")).isEqualTo(0);
|
||||
}
|
||||
|
||||
// ========== Folder-Centric Grouping Tests ==========
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupExtendedNamesMatchingFolderName() {
|
||||
// The "American Gods" case - files with extended names should group with folder
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile epub = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("American Gods")
|
||||
.fileName("American Gods.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile mobi = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("American Gods")
|
||||
.fileName("American Gods.mobi")
|
||||
.bookFileType(BookFileType.MOBI)
|
||||
.build();
|
||||
|
||||
LibraryFile m4b = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("American Gods")
|
||||
.fileName("American Gods The Tenth Anniversary Edition (A Full Cast Production).m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, mobi, m4b));
|
||||
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, mobi, m4b);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupEditionVariantsWithFolderName() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile regular = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("The Hobbit")
|
||||
.fileName("The Hobbit.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile anniversary = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("The Hobbit")
|
||||
.fileName("The Hobbit 50th Anniversary Edition.pdf")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
LibraryFile unabridged = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("The Hobbit")
|
||||
.fileName("The Hobbit Unabridged.m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(regular, anniversary, unabridged));
|
||||
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(regular, anniversary, unabridged);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldKeepSeriesEntriesSeparate() {
|
||||
// Harry Potter series should remain as separate books
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile book1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Harry Potter")
|
||||
.fileName("Harry Potter Book 1.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile book2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Harry Potter")
|
||||
.fileName("Harry Potter Book 2.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile book3 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Harry Potter")
|
||||
.fileName("Harry Potter Book 3.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(book1, book2, book3));
|
||||
|
||||
assertThat(groups).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldKeepSeriesWithNumbersSeparate() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile vol1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Lord of the Rings")
|
||||
.fileName("Lord of the Rings Vol 1.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile vol2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Lord of the Rings")
|
||||
.fileName("Lord of the Rings Vol 2.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(vol1, vol2));
|
||||
|
||||
assertThat(groups).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupSeriesFormatsWithSameNumber() {
|
||||
// Same series entry in different formats should group
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile book1epub = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Harry Potter")
|
||||
.fileName("Harry Potter Book 1.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile book1pdf = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Harry Potter")
|
||||
.fileName("Harry Potter Book 1.pdf")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
LibraryFile book2epub = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Harry Potter")
|
||||
.fileName("Harry Potter Book 2.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(book1epub, book1pdf, book2epub));
|
||||
|
||||
assertThat(groups).hasSize(2);
|
||||
// Book 1 should have 2 files
|
||||
boolean foundBook1Group = groups.values().stream()
|
||||
.anyMatch(list -> list.size() == 2 && list.containsAll(List.of(book1epub, book1pdf)));
|
||||
assertThat(foundBook1Group).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldSeparateUnrelatedBooksInAuthorFolder() {
|
||||
// Multiple different books by same author should stay separate
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile americanGods = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Neil Gaiman")
|
||||
.fileName("American Gods.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile coraline = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Neil Gaiman")
|
||||
.fileName("Coraline.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile stardust = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Neil Gaiman")
|
||||
.fileName("Stardust.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(americanGods, coraline, stardust));
|
||||
|
||||
assertThat(groups).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldUseExactMatchingForRootLevelFiles() {
|
||||
// Files at root level (no subfolder) should use exact key matching
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile epub = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(null)
|
||||
.fileName("The Hobbit.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile pdf = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(null)
|
||||
.fileName("The Hobbit.pdf")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
LibraryFile other = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(null)
|
||||
.fileName("1984.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, pdf, other));
|
||||
|
||||
assertThat(groups).hasSize(2);
|
||||
// Hobbit files should be grouped
|
||||
boolean foundHobbitGroup = groups.values().stream()
|
||||
.anyMatch(list -> list.size() == 2 && list.containsAll(List.of(epub, pdf)));
|
||||
assertThat(foundHobbitGroup).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupFilesWithAuthorVariationsMatchingFolder() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile basic = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("American Gods")
|
||||
.fileName("American Gods.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile withAuthor = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("American Gods")
|
||||
.fileName("American Gods - Neil Gaiman.mobi")
|
||||
.bookFileType(BookFileType.MOBI)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(basic, withAuthor));
|
||||
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(basic, withAuthor);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldHandleFolderBasedAudiobook() {
|
||||
// Folder-based audiobook (MP3 folder) with ebook files
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile epub = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("American Gods")
|
||||
.fileName("American Gods.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.folderBased(false)
|
||||
.build();
|
||||
|
||||
// Folder-based audiobook appears as "American Gods" subfolder
|
||||
LibraryFile mp3Folder = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("American Gods")
|
||||
.fileName("American Gods")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.folderBased(true)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, mp3Folder));
|
||||
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, mp3Folder);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldHandleNestedFolderPath() {
|
||||
// Files in nested folder like "Neil Gaiman/American Gods"
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile epub = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Neil Gaiman/American Gods")
|
||||
.fileName("American Gods.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile m4b = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Neil Gaiman/American Gods")
|
||||
.fileName("American Gods 10th Anniversary.m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, m4b));
|
||||
|
||||
// Should use last folder component "American Gods" as reference
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, m4b);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupNestedAudiobookFolderWithEbooks() {
|
||||
// Nested audiobook folder should group with ebooks in same parent folder
|
||||
// Book Folder/
|
||||
// ├── Book.pdf
|
||||
// ├── Book.epub
|
||||
// └── Book Audiobook/ (folder-based audiobook)
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile pdf = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Book Folder")
|
||||
.fileName("Book.pdf")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
LibraryFile epub = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Book Folder")
|
||||
.fileName("Book.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
// Folder-based audiobook appears as a file with folderBased=true
|
||||
LibraryFile audiobookFolder = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Book Folder")
|
||||
.fileName("Book Audiobook")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.folderBased(true)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(pdf, epub, audiobookFolder));
|
||||
|
||||
// All should be grouped together
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(pdf, epub, audiobookFolder);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupAudiobookVariantNames() {
|
||||
// Different audiobook naming conventions should all group
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile epub = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("The Hobbit")
|
||||
.fileName("The Hobbit.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile audiobook1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("The Hobbit")
|
||||
.fileName("The Hobbit Audiobook")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.folderBased(true)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, audiobook1));
|
||||
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, audiobook1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupFolderWithDotInName() {
|
||||
// Folder-based audiobook with dot in name like "1. American Gods - Neil Gaiman (2011)"
|
||||
// should group with ebooks in the same folder
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile epub = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Neil Gaiman/American Gods")
|
||||
.fileName("1. American Gods - Neil Gaiman (2011).epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile mobi = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Neil Gaiman/American Gods")
|
||||
.fileName("1. American Gods - Neil Gaiman (2011).mobi")
|
||||
.bookFileType(BookFileType.MOBI)
|
||||
.build();
|
||||
|
||||
LibraryFile m4b = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Neil Gaiman/American Gods")
|
||||
.fileName("1. American Gods - Neil Gaiman (2011).m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
// Folder-based audiobook - note: fileName is folder name without extension
|
||||
LibraryFile mp3Folder = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Neil Gaiman/American Gods")
|
||||
.fileName("1. American Gods - Neil Gaiman (2011)")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.folderBased(true)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, mobi, m4b, mp3Folder));
|
||||
|
||||
// All 4 files should be grouped as one book
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, mobi, m4b, mp3Folder);
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -110,8 +110,7 @@ public class LibraryTestBuilder {
|
||||
LibraryEntity library = new LibraryEntity();
|
||||
library.setId(libraryId++);
|
||||
library.setName(name);
|
||||
library.setScanMode(LibraryScanMode.FOLDER_AS_BOOK);
|
||||
library.setDefaultBookFormat(BookFileType.EPUB);
|
||||
library.setFormatPriority(List.of(BookFileType.EPUB));
|
||||
library.setLibraryPaths(new ArrayList<>());
|
||||
|
||||
libraries.add(library);
|
||||
|
||||
Reference in New Issue
Block a user