Add auto-move option on metadata update and simplify file monitoring (#1137)

- Introduce option to automatically move books when their metadata is updated
- Simplify the file monitoring workflow for improved reliability and clarity
This commit is contained in:
Aditya Chandel
2025-09-12 11:59:36 -06:00
committed by GitHub
parent 7adc2b3f57
commit 6ea2eb58bc
47 changed files with 3749 additions and 2942 deletions
@@ -7,7 +7,7 @@ import com.adityachandel.booklore.service.BookDownloadService;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.BookService;
import com.adityachandel.booklore.service.UserProgressService;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.adityachandel.booklore.util.FileService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -49,7 +49,7 @@ class BookServiceDeleteTests {
BookQueryService bookQueryService = Mockito.mock(BookQueryService.class);
UserProgressService userProgressService = Mockito.mock(UserProgressService.class);
BookDownloadService bookDownloadService = Mockito.mock(BookDownloadService.class);
MonitoringProtectionService monitoringProtectionService = Mockito.mock(MonitoringProtectionService.class);
MonitoringRegistrationService monitoringRegistrationService = Mockito.mock(MonitoringRegistrationService.class);
bookService = new BookService(
bookRepository,
@@ -66,7 +66,7 @@ class BookServiceDeleteTests {
bookQueryService,
userProgressService,
bookDownloadService,
monitoringProtectionService
monitoringRegistrationService
);
}
@@ -1,792 +0,0 @@
package com.adityachandel.booklore;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.request.FileMoveRequest;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.file.FileMoveService;
import com.adityachandel.booklore.service.library.LibraryService;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
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 java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class FileMoveServiceMoveFilesTest {
@Mock
private BookQueryService bookQueryService;
@Mock
private BookRepository bookRepository;
@Mock
private BookAdditionalFileRepository bookAdditionalFileRepository;
@Mock
private BookMapper bookMapper;
@Mock
private NotificationService notificationService;
@Mock
private MonitoringProtectionService monitoringProtectionService;
@Mock
private AppSettingService appSettingService;
@Mock
private LibraryService libraryService;
@InjectMocks
private FileMoveService fileMoveService;
@TempDir
Path tempLibraryRoot;
@BeforeEach
void setUp() {
// Configure the mock to actually execute the Runnable for all tests
doAnswer(invocation -> {
Runnable runnable = invocation.getArgument(0);
runnable.run();
return null;
}).when(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("file move operations"));
}
private BookEntity createBookWithFile(Path libraryRoot, String fileSubPath, String fileName) throws IOException {
LibraryEntity library = LibraryEntity.builder()
.id(42L)
.name("Test Library")
.fileNamingPattern(null)
.build();
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path(libraryRoot.toString())
.library(library)
.build();
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("Test Book")
.authors(new HashSet<>(List.of(new AuthorEntity(1L, "Author Name", new ArrayList<>())))
)
.publishedDate(LocalDate.of(2020, 1, 1))
.build();
BookEntity book = BookEntity.builder()
.id(1L)
.fileName(fileName)
.fileSubPath(fileSubPath)
.metadata(metadata)
.libraryPath(libraryPathEntity)
.build();
Path oldFilePath = book.getFullFilePath();
Files.createDirectories(oldFilePath.getParent());
Files.createFile(oldFilePath);
return book;
}
private BookAdditionalFileEntity createAdditionalFile(BookEntity book, Long id, String fileName,
String fileSubPath, AdditionalFileType type,
boolean createActualFile) throws IOException {
BookAdditionalFileEntity additionalFile = BookAdditionalFileEntity.builder()
.id(id)
.book(book)
.fileName(fileName)
.fileSubPath(fileSubPath)
.additionalFileType(type)
.build();
if (createActualFile) {
Path filePath = Paths.get(book.getLibraryPath().getPath())
.resolve(fileSubPath)
.resolve(fileName);
Files.createDirectories(filePath.getParent());
Files.createFile(filePath);
}
return additionalFile;
}
@Test
void testMoveFiles_skipsNonexistentFile() {
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("NoFile")
.build();
LibraryEntity library = LibraryEntity.builder()
.id(43L)
.name("Test Library")
.fileNamingPattern("Moved/{title}")
.build();
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString())
.library(library)
.build();
BookEntity book = BookEntity.builder()
.id(2L)
.fileName("nofile.epub")
.fileSubPath("subfolder")
.metadata(metadata)
.libraryPath(libraryPathEntity)
.build();
when(bookQueryService.findAllWithMetadataByIds(Set.of(2L))).thenReturn(List.of(book));
AppSettings appSettings = new AppSettings();
appSettings.setUploadPattern("Moved/{title}");
when(appSettingService.getAppSettings()).thenReturn(appSettings);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(Set.of(2L));
fileMoveService.moveFiles(request);
Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("NoFile.epub");
assertThat(Files.exists(expectedNewPath))
.withFailMessage("No file should be created for nonexistent source")
.isFalse();
}
@Test
void testMoveFiles_skipsBookWithoutLibraryPath() throws IOException {
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("MissingLibrary")
.build();
BookEntity book = BookEntity.builder()
.id(3L)
.fileName("missinglibrary.epub")
.fileSubPath("subfolder")
.metadata(metadata)
.libraryPath(null)
.build();
Path fakeOldFile = tempLibraryRoot.resolve("subfolder").resolve("missinglibrary.epub");
Files.createDirectories(fakeOldFile.getParent());
Files.createFile(fakeOldFile);
when(bookQueryService.findAllWithMetadataByIds(Set.of(3L))).thenReturn(List.of(book));
AppSettings appSettings = new AppSettings();
appSettings.setUploadPattern("Moved/{title}");
when(appSettingService.getAppSettings()).thenReturn(appSettings);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(Set.of(3L));
fileMoveService.moveFiles(request);
Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("MissingLibrary.epub");
assertThat(Files.exists(expectedNewPath))
.withFailMessage("File should not be moved if library path is missing")
.isFalse();
assertThat(Files.exists(fakeOldFile))
.withFailMessage("Original file should remain when library path is missing")
.isTrue();
Files.deleteIfExists(fakeOldFile);
}
@Test
void testMoveFiles_skipsBookWithNullFileName() throws IOException {
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("NullFileName")
.build();
LibraryEntity library = LibraryEntity.builder()
.id(46L)
.name("Test Library")
.fileNamingPattern("Moved/{title}")
.build();
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString())
.library(library)
.build();
BookEntity book = BookEntity.builder()
.id(10L)
.fileName(null)
.fileSubPath("folder")
.metadata(metadata)
.libraryPath(libraryPathEntity)
.build();
when(bookQueryService.findAllWithMetadataByIds(Set.of(10L))).thenReturn(List.of(book));
AppSettings appSettings = new AppSettings();
appSettings.setUploadPattern("Moved/{title}");
when(appSettingService.getAppSettings()).thenReturn(appSettings);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(Set.of(10L));
fileMoveService.moveFiles(request);
Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("NullFileName");
assertThat(Files.exists(expectedNewPath))
.withFailMessage("File should not be moved if filename is null")
.isFalse();
}
@Test
void testMoveFiles_skipsBookWithEmptyFileName() throws IOException {
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("EmptyFileName")
.build();
LibraryEntity library = LibraryEntity.builder()
.id(47L)
.name("Test Library")
.fileNamingPattern("Moved/{title}")
.build();
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString())
.library(library)
.build();
BookEntity book = BookEntity.builder()
.id(11L)
.fileName("")
.fileSubPath("folder")
.metadata(metadata)
.libraryPath(libraryPathEntity)
.build();
when(bookQueryService.findAllWithMetadataByIds(Set.of(11L))).thenReturn(List.of(book));
AppSettings appSettings = new AppSettings();
appSettings.setUploadPattern("Moved/{title}");
when(appSettingService.getAppSettings()).thenReturn(appSettings);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(Set.of(11L));
fileMoveService.moveFiles(request);
Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("EmptyFileName");
assertThat(Files.exists(expectedNewPath))
.withFailMessage("File should not be moved if filename is empty")
.isFalse();
}
@Test
void testMoveFiles_skipsBookWithNullFileSubPath() throws IOException {
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("NullSubPath")
.build();
LibraryEntity library = LibraryEntity.builder()
.id(48L)
.name("Test Library")
.fileNamingPattern("Moved/{title}")
.build();
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString())
.library(library)
.build();
BookEntity book = BookEntity.builder()
.id(12L)
.fileName("file.epub")
.fileSubPath(null)
.metadata(metadata)
.libraryPath(libraryPathEntity)
.build();
Path oldFile = tempLibraryRoot.resolve("file.epub");
Files.createFile(oldFile);
when(bookQueryService.findAllWithMetadataByIds(Set.of(12L))).thenReturn(List.of(book));
AppSettings appSettings = new AppSettings();
appSettings.setUploadPattern("Moved/{title}");
when(appSettingService.getAppSettings()).thenReturn(appSettings);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(Set.of(12L));
fileMoveService.moveFiles(request);
Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("NullSubPath.epub");
assertThat(Files.exists(expectedNewPath))
.withFailMessage("File should not be moved if fileSubPath is null")
.isFalse();
Files.deleteIfExists(oldFile);
}
@Test
void testMoveFiles_skipsBookWithNullMetadata() throws IOException {
LibraryEntity library = LibraryEntity.builder()
.id(49L)
.name("Test Library")
.fileNamingPattern("Moved/{title}")
.build();
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString())
.library(library)
.build();
BookEntity book = BookEntity.builder()
.id(13L)
.fileName("file.epub")
.fileSubPath("folder")
.metadata(null)
.libraryPath(libraryPathEntity)
.build();
Path oldFile = tempLibraryRoot.resolve("folder").resolve("file.epub");
Files.createDirectories(oldFile.getParent());
Files.createFile(oldFile);
when(bookQueryService.findAllWithMetadataByIds(Set.of(13L))).thenReturn(List.of(book));
AppSettings appSettings = new AppSettings();
appSettings.setUploadPattern("Moved/{title}");
when(appSettingService.getAppSettings()).thenReturn(appSettings);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(Set.of(13L));
fileMoveService.moveFiles(request);
Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve(".epub");
assertThat(Files.exists(expectedNewPath))
.withFailMessage("File should not be moved if metadata is null")
.isFalse();
Files.deleteIfExists(oldFile);
}
@Test
void testMoveFiles_successfulMove() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
Path oldFilePath = book.getFullFilePath();
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
Path newPath = tempLibraryRoot.resolve("X").resolve("Test Book.epub");
assertThat(Files.exists(newPath)).isTrue();
assertThat(Files.exists(oldFilePath)).isFalse();
verify(bookRepository).save(book);
verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), anyList());
// Verify monitoring protection was applied correctly
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("file move operations"));
// Note: Library rescan now happens asynchronously with 8-second delay
// We can't verify it immediately in the test, but the operation is scheduled
}
@Test
void testMoveFiles_usesDefaultPatternWhenLibraryPatternEmpty() throws IOException {
LibraryEntity lib = LibraryEntity.builder()
.id(99L).name("Lib").fileNamingPattern(" ").build();
LibraryPathEntity lp = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString()).library(lib).build();
BookMetadataEntity meta = BookMetadataEntity.builder()
.title("DFT").build();
BookEntity book = BookEntity.builder()
.id(55L).fileSubPath("old").fileName("a.epub")
.libraryPath(lp).metadata(meta).build();
Path old = book.getFullFilePath();
Files.createDirectories(old.getParent());
Files.createFile(old);
when(bookQueryService.findAllWithMetadataByIds(Set.of(55L))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("DEF/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(55L));
fileMoveService.moveFiles(req);
Path moved = tempLibraryRoot.resolve("DEF").resolve("DFT.epub");
assertThat(Files.exists(moved)).isTrue();
verify(bookRepository).save(book);
}
@Test
void testMoveFiles_deletesEmptyParentDirectories() throws IOException {
LibraryEntity library = LibraryEntity.builder()
.id(100L).name("Lib").fileNamingPattern(null).build();
LibraryPathEntity lp = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString()).library(library).build();
BookMetadataEntity meta = BookMetadataEntity.builder()
.title("Nested").build();
BookEntity book = BookEntity.builder()
.id(101L).fileSubPath("a/b/c").fileName("nested.epub")
.libraryPath(lp).metadata(meta).build();
Path old = book.getFullFilePath();
Files.createDirectories(old.getParent());
Files.createFile(old);
when(bookQueryService.findAllWithMetadataByIds(Set.of(101L))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("Z/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
when(bookMapper.toBook(book)).thenReturn(Book.builder().id(book.getId()).build());
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(101L));
fileMoveService.moveFiles(req);
Path newPath = tempLibraryRoot.resolve("Z").resolve("Nested.epub");
assertThat(Files.exists(newPath)).isTrue();
assertThat(Files.notExists(tempLibraryRoot.resolve("a"))).isTrue();
}
@Test
void testMoveFiles_overwritesExistingDestination() throws IOException {
LibraryEntity library = LibraryEntity.builder()
.id(102L).name("Lib").fileNamingPattern(null).build();
LibraryPathEntity lp = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString()).library(library).build();
BookMetadataEntity meta = BookMetadataEntity.builder()
.title("Overwrite").build();
BookEntity book = BookEntity.builder()
.id(103L).fileSubPath("sub").fileName("file.epub")
.libraryPath(lp).metadata(meta).build();
Path old = book.getFullFilePath();
Files.createDirectories(old.getParent());
Files.write(old, "SRC".getBytes());
Path destDir = tempLibraryRoot.resolve("DEST");
Files.createDirectories(destDir);
Path dest = destDir.resolve("Overwrite.epub");
Files.write(dest, "OLD".getBytes());
when(bookQueryService.findAllWithMetadataByIds(Set.of(103L))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("DEST/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
when(bookMapper.toBook(book)).thenReturn(Book.builder().id(book.getId()).build());
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(103L));
fileMoveService.moveFiles(req);
assertThat(Files.exists(dest)).isTrue();
String content = Files.readString(dest);
assertThat(content).isEqualTo("SRC");
}
@Test
void testMoveFiles_usesLibraryPatternWhenSet() throws IOException {
LibraryEntity library = LibraryEntity.builder()
.id(104L).name("Lib").fileNamingPattern("LIBY/{title}").build();
LibraryPathEntity lp = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString()).library(library).build();
BookMetadataEntity meta = BookMetadataEntity.builder()
.title("LibTest").build();
BookEntity book = BookEntity.builder()
.id(105L).fileSubPath("x").fileName("file.epub")
.libraryPath(lp).metadata(meta).build();
Path old = book.getFullFilePath();
Files.createDirectories(old.getParent());
Files.createFile(old);
when(bookQueryService.findAllWithMetadataByIds(Set.of(105L))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("DEFAULT/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
when(bookMapper.toBook(book)).thenReturn(Book.builder().id(book.getId()).build());
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(105L));
fileMoveService.moveFiles(req);
Path newPath = tempLibraryRoot.resolve("LIBY").resolve("LibTest.epub");
assertThat(Files.exists(newPath)).isTrue();
}
@Test
void testMoveFiles_skipsWhenDestinationSameAsSource() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
Path oldFilePath = book.getFullFilePath();
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId())))
.thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("sub/mybook.epub");
when(appSettingService.getAppSettings()).thenReturn(settings);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
assertThat(Files.exists(oldFilePath)).isTrue();
verify(bookRepository, never()).save(any());
verify(notificationService, never()).sendMessage(any(), anyList());
verify(libraryService, never()).rescanLibrary(anyLong());
}
@Test
void testMoveFiles_executesWithMonitoringProtection() {
when(bookQueryService.findAllWithMetadataByIds(anySet())).thenReturn(List.of());
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(999L));
fileMoveService.moveFiles(req);
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("file move operations"));
}
@Test
void testMoveFiles_movesAdditionalFiles() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
// Create additional files
BookAdditionalFileEntity additionalFile1 = createAdditionalFile(book, 1L, "mybook.pdf", "sub",
AdditionalFileType.ALTERNATIVE_FORMAT, true);
BookAdditionalFileEntity additionalFile2 = createAdditionalFile(book, 2L, "mybook_notes.txt", "sub",
AdditionalFileType.SUPPLEMENTARY, true);
List<BookAdditionalFileEntity> additionalFiles = List.of(additionalFile1, additionalFile2);
book.setAdditionalFiles(additionalFiles);
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify main book moved
Path newBookPath = tempLibraryRoot.resolve("X").resolve("Test Book.epub");
assertThat(Files.exists(newBookPath)).isTrue();
// Verify additional files moved
Path newAdditionalPath1 = tempLibraryRoot.resolve("X").resolve("Test Book.pdf");
Path newAdditionalPath2 = tempLibraryRoot.resolve("X").resolve("Test Book.txt");
assertThat(Files.exists(newAdditionalPath1)).isTrue();
assertThat(Files.exists(newAdditionalPath2)).isTrue();
// Verify database updated
verify(bookAdditionalFileRepository, times(2)).save(any(BookAdditionalFileEntity.class));
}
@Test
void testMoveFiles_handlesUniqueNamesForAdditionalFiles() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
// Create additional files that will result in same name after pattern resolution
BookAdditionalFileEntity additionalFile1 = createAdditionalFile(book, 1L, "version1.pdf", "sub",
AdditionalFileType.ALTERNATIVE_FORMAT, true);
BookAdditionalFileEntity additionalFile2 = createAdditionalFile(book, 2L, "version2.pdf", "sub",
AdditionalFileType.ALTERNATIVE_FORMAT, true);
List<BookAdditionalFileEntity> additionalFiles = List.of(additionalFile1, additionalFile2);
book.setAdditionalFiles(additionalFiles);
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify files moved with unique names
Path newAdditionalPath1 = tempLibraryRoot.resolve("X").resolve("Test Book.pdf");
Path newAdditionalPath2 = tempLibraryRoot.resolve("X").resolve("Test Book_2.pdf");
assertThat(Files.exists(newAdditionalPath1)).isTrue();
assertThat(Files.exists(newAdditionalPath2)).isTrue();
verify(bookAdditionalFileRepository, times(2)).save(any(BookAdditionalFileEntity.class));
}
@Test
void testMoveFiles_skipsNonexistentAdditionalFiles() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
// Create additional file entity without actual file
BookAdditionalFileEntity additionalFile = createAdditionalFile(book, 1L, "nonexistent.pdf", "sub",
AdditionalFileType.ALTERNATIVE_FORMAT, false);
book.setAdditionalFiles(List.of(additionalFile));
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify main book moved
Path newBookPath = tempLibraryRoot.resolve("X").resolve("Test Book.epub");
assertThat(Files.exists(newBookPath)).isTrue();
// Verify nonexistent additional file not saved
verify(bookAdditionalFileRepository, never()).save(any(BookAdditionalFileEntity.class));
}
@Test
void testMoveFiles_handlesEmptyAdditionalFilesList() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
book.setAdditionalFiles(new ArrayList<>());
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify main book moved
Path newBookPath = tempLibraryRoot.resolve("X").resolve("Test Book.epub");
assertThat(Files.exists(newBookPath)).isTrue();
// Verify no additional file operations
verify(bookAdditionalFileRepository, never()).save(any(BookAdditionalFileEntity.class));
}
@Test
void testMoveFiles_handlesNullAdditionalFilesList() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
book.setAdditionalFiles(null);
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify main book moved
Path newBookPath = tempLibraryRoot.resolve("X").resolve("Test Book.epub");
assertThat(Files.exists(newBookPath)).isTrue();
// Verify no additional file operations
verify(bookAdditionalFileRepository, never()).save(any(BookAdditionalFileEntity.class));
}
@Test
void testMoveFiles_additionalFileWithDifferentExtensions() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
// Create additional files with different extensions
BookAdditionalFileEntity additionalFile1 = createAdditionalFile(book, 1L, "mybook.pdf", "sub",
AdditionalFileType.ALTERNATIVE_FORMAT, true);
BookAdditionalFileEntity additionalFile2 = createAdditionalFile(book, 2L, "mybook.mobi", "sub",
AdditionalFileType.ALTERNATIVE_FORMAT, true);
BookAdditionalFileEntity additionalFile3 = createAdditionalFile(book, 3L, "cover.jpg", "sub",
AdditionalFileType.SUPPLEMENTARY, true);
List<BookAdditionalFileEntity> additionalFiles = List.of(additionalFile1, additionalFile2, additionalFile3);
book.setAdditionalFiles(additionalFiles);
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("Library/{authors}/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify all files moved with correct extensions
Path basePath = tempLibraryRoot.resolve("Library").resolve("Author Name");
assertThat(Files.exists(basePath.resolve("Test Book.epub"))).isTrue();
assertThat(Files.exists(basePath.resolve("Test Book.pdf"))).isTrue();
assertThat(Files.exists(basePath.resolve("Test Book.mobi"))).isTrue();
assertThat(Files.exists(basePath.resolve("Test Book.jpg"))).isTrue();
verify(bookAdditionalFileRepository, times(3)).save(any(BookAdditionalFileEntity.class));
}
@Test
void testMoveFiles_skipsSamePathAdditionalFiles() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "X", "Test Book.epub");
// Create additional file that will resolve to same path
BookAdditionalFileEntity additionalFile = createAdditionalFile(book, 1L, "Test Book.pdf", "X",
AdditionalFileType.ALTERNATIVE_FORMAT, true);
book.setAdditionalFiles(List.of(additionalFile));
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify files still exist at original location
Path additionalFilePath = tempLibraryRoot.resolve("X").resolve("Test Book.pdf");
assertThat(Files.exists(additionalFilePath)).isTrue();
// Verify no save called for additional file (skipped)
verify(bookAdditionalFileRepository, never()).save(any(BookAdditionalFileEntity.class));
}
}
@@ -90,7 +90,7 @@ class FileMoveServiceTest {
.isIn(
"/Good Omens - Neil Gaiman, Terry Pratchett (1990).mobi",
"/Good Omens - Terry Pratchett, Neil Gaiman (1990).mobi"
); // Set order is non-deterministic
);
}
@Test
@@ -162,7 +162,7 @@ class FileMoveServiceTest {
BookEntity book = BookEntity.builder()
.metadata(metadata)
.fileName("") // explicitly empty
.fileName("")
.build();
String result = fileMoveService.generatePathFromPattern(book, "/{title}");
@@ -1,29 +1,36 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.mapper.AdditionalFileMapper;
import com.adityachandel.booklore.model.dto.AdditionalFile;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
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.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@@ -36,7 +43,7 @@ class AdditionalFileServiceTest {
private AdditionalFileMapper additionalFileMapper;
@Mock
private MonitoringProtectionService monitoringProtectionService;
private MonitoringRegistrationService monitoringRegistrationService;
@InjectMocks
private AdditionalFileService additionalFileService;
@@ -44,146 +51,243 @@ class AdditionalFileServiceTest {
@TempDir
Path tempDir;
@BeforeEach
void setUp() {
// Configure mock to execute the Runnable for file operations (lenient for tests that don't use it)
lenient().doAnswer(invocation -> {
Runnable runnable = invocation.getArgument(0);
runnable.run();
return null;
}).when(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
}
private BookAdditionalFileEntity fileEntity;
private AdditionalFile additionalFile;
private BookEntity bookEntity;
private LibraryPathEntity libraryPathEntity;
@Test
void deleteAdditionalFile_success() throws IOException {
// Arrange
@BeforeEach
void setUp() throws IOException {
Path testFile = tempDir.resolve("test-file.pdf");
Files.createFile(testFile);
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath(tempDir.toString());
libraryPathEntity = new LibraryPathEntity();
libraryPathEntity.setId(1L);
libraryPathEntity.setPath(tempDir.toString());
BookEntity book = new BookEntity();
book.setLibraryPath(libraryPath);
bookEntity = new BookEntity();
bookEntity.setId(100L);
bookEntity.setLibraryPath(libraryPathEntity);
BookAdditionalFileEntity fileEntity = BookAdditionalFileEntity.builder()
.id(1L)
.fileName("test-file.pdf")
.fileSubPath("")
.additionalFileType(AdditionalFileType.ALTERNATIVE_FORMAT)
.book(book)
.build();
fileEntity = new BookAdditionalFileEntity();
fileEntity.setId(1L);
fileEntity.setBook(bookEntity);
fileEntity.setFileName("test-file.pdf");
fileEntity.setFileSubPath(".");
fileEntity.setAdditionalFileType(AdditionalFileType.ALTERNATIVE_FORMAT);
when(additionalFileRepository.findById(1L)).thenReturn(Optional.of(fileEntity));
// Act
additionalFileService.deleteAdditionalFile(1L);
// Assert
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
verify(additionalFileRepository).delete(fileEntity);
assertThat(Files.exists(testFile)).isFalse();
additionalFile = mock(AdditionalFile.class);
}
@Test
void deleteAdditionalFile_fileNotFound() {
// Arrange
when(additionalFileRepository.findById(1L)).thenReturn(Optional.empty());
void getAdditionalFilesByBookId_WhenFilesExist_ShouldReturnMappedFiles() {
Long bookId = 100L;
List<BookAdditionalFileEntity> entities = List.of(fileEntity);
List<AdditionalFile> expectedFiles = List.of(additionalFile);
// Act & Assert
assertThatThrownBy(() -> additionalFileService.deleteAdditionalFile(1L))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Additional file not found with id: 1");
when(additionalFileRepository.findByBookId(bookId)).thenReturn(entities);
when(additionalFileMapper.toAdditionalFiles(entities)).thenReturn(expectedFiles);
verify(monitoringProtectionService, never()).executeWithProtection(any(Runnable.class), any());
List<AdditionalFile> result = additionalFileService.getAdditionalFilesByBookId(bookId);
assertEquals(expectedFiles, result);
verify(additionalFileRepository).findByBookId(bookId);
verify(additionalFileMapper).toAdditionalFiles(entities);
}
@Test
void deleteAdditionalFile_physicalFileNotExists() {
// Arrange
Path nonExistentFile = tempDir.resolve("non-existent.pdf");
void getAdditionalFilesByBookId_WhenNoFilesExist_ShouldReturnEmptyList() {
Long bookId = 100L;
List<BookAdditionalFileEntity> entities = Collections.emptyList();
List<AdditionalFile> expectedFiles = Collections.emptyList();
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath(tempDir.toString());
when(additionalFileRepository.findByBookId(bookId)).thenReturn(entities);
when(additionalFileMapper.toAdditionalFiles(entities)).thenReturn(expectedFiles);
BookEntity book = new BookEntity();
book.setLibraryPath(libraryPath);
List<AdditionalFile> result = additionalFileService.getAdditionalFilesByBookId(bookId);
BookAdditionalFileEntity fileEntity = BookAdditionalFileEntity.builder()
.id(1L)
.fileName("non-existent.pdf")
.fileSubPath("")
.additionalFileType(AdditionalFileType.ALTERNATIVE_FORMAT)
.book(book)
.build();
when(additionalFileRepository.findById(1L)).thenReturn(Optional.of(fileEntity));
// Act
additionalFileService.deleteAdditionalFile(1L);
// Assert
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
verify(additionalFileRepository).delete(fileEntity);
assertTrue(result.isEmpty());
verify(additionalFileRepository).findByBookId(bookId);
verify(additionalFileMapper).toAdditionalFiles(entities);
}
@Test
void deleteAdditionalFile_ioExceptionDuringDeletion() throws IOException {
// This test verifies that DB record is still deleted even if file deletion fails
// Arrange
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath("/invalid/path");
void getAdditionalFilesByBookIdAndType_WhenFilesExist_ShouldReturnMappedFiles() {
Long bookId = 100L;
AdditionalFileType type = AdditionalFileType.ALTERNATIVE_FORMAT;
List<BookAdditionalFileEntity> entities = List.of(fileEntity);
List<AdditionalFile> expectedFiles = List.of(additionalFile);
BookEntity book = new BookEntity();
book.setLibraryPath(libraryPath);
when(additionalFileRepository.findByBookIdAndAdditionalFileType(bookId, type)).thenReturn(entities);
when(additionalFileMapper.toAdditionalFiles(entities)).thenReturn(expectedFiles);
BookAdditionalFileEntity fileEntity = BookAdditionalFileEntity.builder()
.id(1L)
.fileName("test-file.pdf")
.fileSubPath("")
.additionalFileType(AdditionalFileType.ALTERNATIVE_FORMAT)
.book(book)
.build();
List<AdditionalFile> result = additionalFileService.getAdditionalFilesByBookIdAndType(bookId, type);
when(additionalFileRepository.findById(1L)).thenReturn(Optional.of(fileEntity));
// Act
additionalFileService.deleteAdditionalFile(1L);
// Assert - DB record should still be deleted even if file deletion fails
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
verify(additionalFileRepository).delete(fileEntity);
assertEquals(expectedFiles, result);
verify(additionalFileRepository).findByBookIdAndAdditionalFileType(bookId, type);
verify(additionalFileMapper).toAdditionalFiles(entities);
}
@Test
void deleteAdditionalFile_withMonitoringProtection() {
// Arrange
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath(tempDir.toString());
void getAdditionalFilesByBookIdAndType_WhenNoFilesExist_ShouldReturnEmptyList() {
Long bookId = 100L;
AdditionalFileType type = AdditionalFileType.SUPPLEMENTARY;
List<BookAdditionalFileEntity> entities = Collections.emptyList();
List<AdditionalFile> expectedFiles = Collections.emptyList();
BookEntity book = new BookEntity();
book.setLibraryPath(libraryPath);
when(additionalFileRepository.findByBookIdAndAdditionalFileType(bookId, type)).thenReturn(entities);
when(additionalFileMapper.toAdditionalFiles(entities)).thenReturn(expectedFiles);
BookAdditionalFileEntity fileEntity = BookAdditionalFileEntity.builder()
.id(1L)
.fileName("test-file.pdf")
.fileSubPath("subfolder")
.additionalFileType(AdditionalFileType.SUPPLEMENTARY)
.book(book)
.build();
List<AdditionalFile> result = additionalFileService.getAdditionalFilesByBookIdAndType(bookId, type);
when(additionalFileRepository.findById(1L)).thenReturn(Optional.of(fileEntity));
assertTrue(result.isEmpty());
verify(additionalFileRepository).findByBookIdAndAdditionalFileType(bookId, type);
verify(additionalFileMapper).toAdditionalFiles(entities);
}
// Act
additionalFileService.deleteAdditionalFile(1L);
@Test
void deleteAdditionalFile_WhenFileNotFound_ShouldThrowException() {
Long fileId = 1L;
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.empty());
// Assert - Verify monitoring protection was used
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
// Verify the operation name is correct for logging/tracking
verify(monitoringProtectionService).executeWithProtection(
any(Runnable.class),
eq("additional file deletion")
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> additionalFileService.deleteAdditionalFile(fileId)
);
assertEquals("Additional file not found with id: 1", exception.getMessage());
verify(additionalFileRepository).findById(fileId);
verify(additionalFileRepository, never()).delete(any());
verify(monitoringRegistrationService, never()).unregisterSpecificPath(any());
}
}
@Test
void deleteAdditionalFile_WhenFileExists_ShouldDeleteSuccessfully() throws IOException {
Long fileId = 1L;
Path parentPath = fileEntity.getFullFilePath().getParent();
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.of(fileEntity));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.deleteIfExists(fileEntity.getFullFilePath())).thenReturn(true);
additionalFileService.deleteAdditionalFile(fileId);
verify(additionalFileRepository).findById(fileId);
verify(monitoringRegistrationService).unregisterSpecificPath(parentPath);
filesMock.verify(() -> Files.deleteIfExists(fileEntity.getFullFilePath()));
verify(additionalFileRepository).delete(fileEntity);
}
}
@Test
void deleteAdditionalFile_WhenIOExceptionOccurs_ShouldStillDeleteFromRepository() throws IOException {
Long fileId = 1L;
Path parentPath = fileEntity.getFullFilePath().getParent();
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.of(fileEntity));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.deleteIfExists(fileEntity.getFullFilePath())).thenThrow(new IOException("File access error"));
additionalFileService.deleteAdditionalFile(fileId);
verify(additionalFileRepository).findById(fileId);
verify(monitoringRegistrationService).unregisterSpecificPath(parentPath);
filesMock.verify(() -> Files.deleteIfExists(fileEntity.getFullFilePath()));
verify(additionalFileRepository).delete(fileEntity);
}
}
@Test
void deleteAdditionalFile_WhenEntityRelationshipsMissing_ShouldThrowIllegalStateException() {
Long fileId = 1L;
BookAdditionalFileEntity invalidEntity = new BookAdditionalFileEntity();
invalidEntity.setId(fileId);
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.of(invalidEntity));
assertThrows(
IllegalStateException.class,
() -> additionalFileService.deleteAdditionalFile(fileId)
);
verify(additionalFileRepository).findById(fileId);
verify(additionalFileRepository, never()).delete(any());
verify(monitoringRegistrationService, never()).unregisterSpecificPath(any());
}
@Test
void downloadAdditionalFile_WhenFileNotFound_ShouldReturnNotFound() throws IOException {
Long fileId = 1L;
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.empty());
ResponseEntity<Resource> result = additionalFileService.downloadAdditionalFile(fileId);
assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode());
assertNull(result.getBody());
verify(additionalFileRepository).findById(fileId);
}
@Test
void downloadAdditionalFile_WhenPhysicalFileNotExists_ShouldReturnNotFound() throws IOException {
Long fileId = 1L;
BookAdditionalFileEntity entityWithNonExistentFile = new BookAdditionalFileEntity();
entityWithNonExistentFile.setId(fileId);
entityWithNonExistentFile.setBook(bookEntity);
entityWithNonExistentFile.setFileName("non-existent.pdf");
entityWithNonExistentFile.setFileSubPath(".");
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.of(entityWithNonExistentFile));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
Path actualPath = entityWithNonExistentFile.getFullFilePath();
filesMock.when(() -> Files.exists(actualPath)).thenReturn(false);
ResponseEntity<Resource> result = additionalFileService.downloadAdditionalFile(fileId);
assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode());
assertNull(result.getBody());
verify(additionalFileRepository).findById(fileId);
filesMock.verify(() -> Files.exists(actualPath));
}
}
@Test
void downloadAdditionalFile_WhenFileExists_ShouldReturnFileResource() throws IOException {
Long fileId = 1L;
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.of(fileEntity));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(fileEntity.getFullFilePath())).thenReturn(true);
ResponseEntity<Resource> result = additionalFileService.downloadAdditionalFile(fileId);
assertEquals(HttpStatus.OK, result.getStatusCode());
assertNotNull(result.getBody());
assertTrue(result.getHeaders().containsKey(HttpHeaders.CONTENT_DISPOSITION));
assertTrue(result.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION).contains("test-file.pdf"));
assertEquals(MediaType.APPLICATION_OCTET_STREAM, result.getHeaders().getContentType());
verify(additionalFileRepository).findById(fileId);
filesMock.verify(() -> Files.exists(fileEntity.getFullFilePath()));
}
}
@Test
void downloadAdditionalFile_WhenEntityRelationshipsMissing_ShouldThrowIllegalStateException() throws IOException {
Long fileId = 1L;
BookAdditionalFileEntity invalidEntity = new BookAdditionalFileEntity();
invalidEntity.setId(fileId);
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.of(invalidEntity));
assertThrows(
IllegalStateException.class,
() -> additionalFileService.downloadAdditionalFile(fileId)
);
verify(additionalFileRepository).findById(fileId);
}
}
@@ -1,275 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.response.BookDeletionResponse;
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.repository.*;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.util.FileService;
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.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class BookServiceDeleteBooksTest {
@Mock private BookRepository bookRepository;
@Mock private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
@Mock private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
@Mock private CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
@Mock private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
@Mock private ShelfRepository shelfRepository;
@Mock private FileService fileService;
@Mock private BookMapper bookMapper;
@Mock private UserRepository userRepository;
@Mock private UserBookProgressRepository userBookProgressRepository;
@Mock private AuthenticationService authenticationService;
@Mock private BookQueryService bookQueryService;
@Mock private UserProgressService userProgressService;
@Mock private BookDownloadService bookDownloadService;
@Mock private MonitoringProtectionService monitoringProtectionService;
private BookService bookService;
@TempDir
Path tempDir;
@BeforeEach
void setUp() {
bookService = new BookService(
bookRepository,
pdfViewerPreferencesRepository,
epubViewerPreferencesRepository,
cbxViewerPreferencesRepository,
newPdfViewerPreferencesRepository,
shelfRepository,
fileService,
bookMapper,
userRepository,
userBookProgressRepository,
authenticationService,
bookQueryService,
userProgressService,
bookDownloadService,
monitoringProtectionService
);
// Configure mock to execute the Supplier for file operations
when(monitoringProtectionService.executeWithProtection(any(Supplier.class), eq("book deletion")))
.thenAnswer(invocation -> {
Supplier<?> supplier = invocation.getArgument(0);
return supplier.get();
});
}
private LibraryEntity createTestLibrary() {
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath(tempDir.toString());
LibraryEntity library = new LibraryEntity();
library.setId(1L);
library.setName("Test Library");
library.setLibraryPaths(List.of(libraryPath));
return library;
}
private LibraryPathEntity createTestLibraryPath() {
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath(tempDir.toString());
return libraryPath;
}
@Test
void deleteBooks_successfulDeletion() throws IOException {
// Arrange
Path testFile1 = tempDir.resolve("book1.epub");
Path testFile2 = tempDir.resolve("book2.pdf");
Files.createFile(testFile1);
Files.createFile(testFile2);
LibraryEntity library = createTestLibrary();
LibraryPathEntity libraryPath = createTestLibraryPath();
BookEntity book1 = BookEntity.builder()
.id(1L)
.fileName("book1.epub")
.fileSubPath("")
.libraryPath(libraryPath)
.library(library)
.build();
BookEntity book2 = BookEntity.builder()
.id(2L)
.fileName("book2.pdf")
.fileSubPath("")
.libraryPath(libraryPath)
.library(library)
.build();
List<BookEntity> books = List.of(book1, book2);
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L))).thenReturn(books);
// Act
ResponseEntity<BookDeletionResponse> response = bookService.deleteBooks(Set.of(1L, 2L));
// Assert
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
BookDeletionResponse deletionResponse = response.getBody();
assertThat(deletionResponse).isNotNull();
assertThat(deletionResponse.getDeleted()).containsExactlyInAnyOrder(1L, 2L);
assertThat(deletionResponse.getFailedFileDeletions()).isEmpty();
// Verify monitoring protection was used
verify(monitoringProtectionService).executeWithProtection(any(Supplier.class), eq("book deletion"));
// Verify books were deleted from database
verify(bookRepository).deleteAll(books);
// Verify files were deleted
assertThat(Files.exists(testFile1)).isFalse();
assertThat(Files.exists(testFile2)).isFalse();
}
@Test
void deleteBooks_fileNotFound() {
// Arrange
Path nonExistentFile = tempDir.resolve("non-existent.epub");
LibraryEntity library = createTestLibrary();
LibraryPathEntity libraryPath = createTestLibraryPath();
BookEntity book = BookEntity.builder()
.id(1L)
.fileName("non-existent.epub")
.fileSubPath("")
.libraryPath(libraryPath)
.library(library)
.build();
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
// Act
ResponseEntity<BookDeletionResponse> response = bookService.deleteBooks(Set.of(1L));
// Assert
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
BookDeletionResponse deletionResponse = response.getBody();
assertThat(deletionResponse).isNotNull();
assertThat(deletionResponse.getDeleted()).containsExactly(1L);
// File doesn't exist, so no deletion failure is recorded
assertThat(deletionResponse.getFailedFileDeletions()).isEmpty();
verify(monitoringProtectionService).executeWithProtection(any(Supplier.class), eq("book deletion"));
verify(bookRepository).deleteAll(List.of(book));
}
@Test
void deleteBooks_partialFailure() throws IOException {
// Arrange
Path existingFile = tempDir.resolve("existing.epub");
Files.createFile(existingFile);
LibraryEntity library = createTestLibrary();
LibraryPathEntity libraryPath = createTestLibraryPath();
BookEntity existingBook = BookEntity.builder()
.id(1L)
.fileName("existing.epub")
.fileSubPath("")
.libraryPath(libraryPath)
.library(library)
.build();
BookEntity missingBook = BookEntity.builder()
.id(2L)
.fileName("missing.epub")
.fileSubPath("")
.libraryPath(libraryPath)
.library(library)
.build();
List<BookEntity> books = List.of(existingBook, missingBook);
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L))).thenReturn(books);
// Act
ResponseEntity<BookDeletionResponse> response = bookService.deleteBooks(Set.of(1L, 2L));
// Assert
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
BookDeletionResponse deletionResponse = response.getBody();
assertThat(deletionResponse).isNotNull();
assertThat(deletionResponse.getDeleted()).containsExactlyInAnyOrder(1L, 2L);
assertThat(deletionResponse.getFailedFileDeletions()).isEmpty(); // Missing file is not considered a failure
verify(monitoringProtectionService).executeWithProtection(any(Supplier.class), eq("book deletion"));
verify(bookRepository).deleteAll(books);
// Existing file should be deleted
assertThat(Files.exists(existingFile)).isFalse();
}
@Test
void deleteBooks_emptySet() {
// Act
ResponseEntity<BookDeletionResponse> response = bookService.deleteBooks(Set.of());
// Assert
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
BookDeletionResponse deletionResponse = response.getBody();
assertThat(deletionResponse).isNotNull();
assertThat(deletionResponse.getDeleted()).isEmpty();
assertThat(deletionResponse.getFailedFileDeletions()).isEmpty();
// Should still use monitoring protection even for empty operations
verify(monitoringProtectionService).executeWithProtection(any(Supplier.class), eq("book deletion"));
verify(bookRepository).deleteAll(List.of());
}
@Test
void deleteBooks_verifyMonitoringProtectionUsage() {
// Arrange
LibraryEntity library = createTestLibrary();
LibraryPathEntity libraryPath = createTestLibraryPath();
BookEntity book = BookEntity.builder()
.id(1L)
.fileName("test.epub")
.fileSubPath("")
.libraryPath(libraryPath)
.library(library)
.build();
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
// Act
bookService.deleteBooks(Set.of(1L));
// Assert - Verify monitoring protection is called with correct parameters
verify(monitoringProtectionService).executeWithProtection(
any(Supplier.class),
eq("book deletion")
);
}
}
@@ -1,276 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class MonitoringProtectionConcurrentTest {
@Mock
private MonitoringService monitoringService;
private MonitoringProtectionService monitoringProtectionService;
@BeforeEach
void setUp() {
monitoringProtectionService = new MonitoringProtectionService(monitoringService);
}
@Test
void concurrentOperations_properSynchronization() throws InterruptedException {
// Arrange
when(monitoringService.isPaused()).thenReturn(false, true, true, true, true);
AtomicInteger operationCount = new AtomicInteger(0);
AtomicInteger pauseCount = new AtomicInteger(0);
AtomicInteger resumeCount = new AtomicInteger(0);
// Track pause/resume calls
doAnswer(invocation -> {
pauseCount.incrementAndGet();
return null;
}).when(monitoringService).pauseMonitoring();
doAnswer(invocation -> {
resumeCount.incrementAndGet();
return null;
}).when(monitoringService).resumeMonitoring();
int numberOfThreads = 10;
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
// Act - Run multiple concurrent operations
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < numberOfThreads; i++) {
final int operationId = i;
Future<?> future = executor.submit(() -> {
try {
monitoringProtectionService.executeWithProtection(() -> {
operationCount.incrementAndGet();
// Simulate some work
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "concurrent test operation " + operationId);
} finally {
latch.countDown();
}
});
futures.add(future);
}
// Wait for all operations to complete
boolean completed = latch.await(30, TimeUnit.SECONDS);
executor.shutdown();
// Assert
assertThat(completed).isTrue();
assertThat(operationCount.get()).isEqualTo(numberOfThreads);
// Verify monitoring was paused at least once (may be fewer due to synchronization)
assertThat(pauseCount.get()).isGreaterThan(0);
// Wait a bit for resume calls (they happen with delay in virtual threads)
Thread.sleep(6000);
assertThat(resumeCount.get()).isGreaterThan(0);
// All futures should complete successfully
for (Future<?> future : futures) {
assertThat(future.isDone()).isTrue();
}
}
@Test
void concurrentOperations_onlyOnePausesMonitoring() throws InterruptedException {
// Arrange - First call returns false (not paused), subsequent return true (already paused)
when(monitoringService.isPaused()).thenReturn(false).thenReturn(true);
AtomicInteger pauseCallCount = new AtomicInteger(0);
doAnswer(invocation -> {
pauseCallCount.incrementAndGet();
return null;
}).when(monitoringService).pauseMonitoring();
int numberOfThreads = 5;
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
CountDownLatch startLatch = new CountDownLatch(1);
CountDownLatch finishLatch = new CountDownLatch(numberOfThreads);
// Act - Start all threads at the same time to maximize contention
for (int i = 0; i < numberOfThreads; i++) {
executor.submit(() -> {
try {
startLatch.await(); // Wait for signal to start
monitoringProtectionService.executeWithProtection(() -> {
// Simulate work
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "sync test");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
finishLatch.countDown();
}
});
}
startLatch.countDown(); // Start all threads
boolean completed = finishLatch.await(10, TimeUnit.SECONDS);
executor.shutdown();
// Assert
assertThat(completed).isTrue();
// Only one thread should have actually called pauseMonitoring due to synchronization
assertThat(pauseCallCount.get()).isEqualTo(1);
}
@Test
void concurrentOperations_withExceptions() throws InterruptedException {
// Arrange
when(monitoringService.isPaused()).thenReturn(false, true, true);
AtomicInteger successCount = new AtomicInteger(0);
AtomicInteger exceptionCount = new AtomicInteger(0);
AtomicInteger resumeCount = new AtomicInteger(0);
doAnswer(invocation -> {
resumeCount.incrementAndGet();
return null;
}).when(monitoringService).resumeMonitoring();
int numberOfThreads = 8;
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
// Act - Half the operations throw exceptions
for (int i = 0; i < numberOfThreads; i++) {
final int operationId = i;
executor.submit(() -> {
try {
monitoringProtectionService.executeWithProtection(() -> {
if (operationId % 2 == 0) {
successCount.incrementAndGet();
} else {
exceptionCount.incrementAndGet();
throw new RuntimeException("Test exception " + operationId);
}
}, "exception test " + operationId);
} catch (RuntimeException e) {
// Expected for half the operations
} finally {
latch.countDown();
}
});
}
boolean completed = latch.await(10, TimeUnit.SECONDS);
executor.shutdown();
// Assert
assertThat(completed).isTrue();
assertThat(successCount.get()).isEqualTo(numberOfThreads / 2);
assertThat(exceptionCount.get()).isEqualTo(numberOfThreads / 2);
// Wait for resume calls (delayed)
Thread.sleep(6000);
// Even with exceptions, monitoring should still be resumed
assertThat(resumeCount.get()).isGreaterThan(0);
}
@Test
void concurrentOperations_supplierReturnValues() throws InterruptedException, ExecutionException, TimeoutException {
// Arrange
when(monitoringService.isPaused()).thenReturn(false, true, true, true);
int numberOfThreads = 6;
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
// Act - Use Supplier version to test return values
List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < numberOfThreads; i++) {
final int operationId = i;
Future<String> future = executor.submit(() ->
monitoringProtectionService.executeWithProtection(() -> {
try {
Thread.sleep(50); // Simulate work
return "Result-" + operationId;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return "Interrupted-" + operationId;
}
}, "supplier test " + operationId)
);
futures.add(future);
}
// Assert
List<String> results = new ArrayList<>();
for (Future<String> future : futures) {
String result = future.get(10, TimeUnit.SECONDS);
results.add(result);
}
executor.shutdown();
assertThat(results).hasSize(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
assertThat(results).contains("Result-" + i);
}
}
@Test
void stressTest_manyQuickOperations() throws InterruptedException {
// Arrange
when(monitoringService.isPaused()).thenReturn(false).thenReturn(true);
AtomicInteger completedOperations = new AtomicInteger(0);
int numberOfOperations = 100;
ExecutorService executor = Executors.newFixedThreadPool(20);
CountDownLatch latch = new CountDownLatch(numberOfOperations);
// Act - Many quick operations to test lock contention
for (int i = 0; i < numberOfOperations; i++) {
executor.submit(() -> {
try {
monitoringProtectionService.executeWithProtection(() -> {
completedOperations.incrementAndGet();
// Very quick operation
}, "stress test");
} finally {
latch.countDown();
}
});
}
boolean completed = latch.await(30, TimeUnit.SECONDS);
executor.shutdown();
// Assert
assertThat(completed).isTrue();
assertThat(completedOperations.get()).isEqualTo(numberOfOperations);
// Should only pause once due to synchronization, even with many operations
verify(monitoringService, times(1)).pauseMonitoring();
}
}
@@ -1,100 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.*;
/**
* Integration test to verify that critical file operations properly use monitoring protection
* to prevent race conditions that can cause data loss.
*
* This addresses the race condition bug where monitoring would detect file operations
* as "missing files" and delete them before the operations completed.
*/
@ExtendWith(MockitoExtension.class)
class MonitoringProtectionIntegrationTest {
@Mock
private MonitoringService monitoringService;
@Test
void testMonitoringProtectionPattern_PauseAndResumeSequence() {
// Given - monitoring service that reports not paused initially
when(monitoringService.isPaused()).thenReturn(false);
// When - simulating the monitoring protection pattern used in file operations
boolean didPause = pauseMonitoringIfNeeded();
try {
// Critical file operation would happen here
// (simulated - actual file operations tested in integration tests)
} finally {
resumeMonitoringImmediately(didPause);
}
// Then - verify the correct sequence occurred
verify(monitoringService).isPaused(); // Check current state
verify(monitoringService).pauseMonitoring(); // Pause before operation
verify(monitoringService).resumeMonitoring(); // Resume after operation
}
@Test
void testMonitoringProtectionPattern_AlreadyPaused() {
// Given - monitoring service that reports already paused
when(monitoringService.isPaused()).thenReturn(true);
// When - simulating the monitoring protection pattern
boolean didPause = pauseMonitoringIfNeeded();
try {
// Critical file operation would happen here
} finally {
resumeMonitoringImmediately(didPause);
}
// Then - verify no additional pause/resume calls were made
verify(monitoringService).isPaused(); // Check current state
verify(monitoringService, never()).pauseMonitoring(); // Should not pause again
verify(monitoringService, never()).resumeMonitoring(); // Should not resume what we didn't pause
}
@Test
void testMonitoringProtectionPattern_ExceptionHandling() {
// Given - monitoring service that reports not paused initially
when(monitoringService.isPaused()).thenReturn(false);
// When - simulating the monitoring protection pattern with exception
boolean didPause = pauseMonitoringIfNeeded();
try {
// Simulate a critical file operation that throws an exception
throw new RuntimeException("File operation failed");
} catch (RuntimeException e) {
// Exception handling would occur here in real code
} finally {
resumeMonitoringImmediately(didPause);
}
// Then - verify monitoring was still resumed despite the exception
verify(monitoringService).isPaused();
verify(monitoringService).pauseMonitoring();
verify(monitoringService).resumeMonitoring(); // Critical: must resume even on failure
}
// Helper methods that mirror the actual implementation pattern
private boolean pauseMonitoringIfNeeded() {
if (!monitoringService.isPaused()) {
monitoringService.pauseMonitoring();
return true;
}
return false;
}
private void resumeMonitoringImmediately(boolean didPause) {
if (didPause) {
monitoringService.resumeMonitoring();
}
}
}
@@ -1,232 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
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.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
/**
* Integration test that simulates the actual race condition scenario:
* File operations happening while monitoring service detects "missing" files.
*
* This test verifies that MonitoringProtectionService prevents the race condition
* that was causing data loss in the original bug.
*/
@ExtendWith(MockitoExtension.class)
class MonitoringProtectionRaceConditionTest {
@TempDir
Path tempDir;
@Mock
private MonitoringService monitoringService;
private MonitoringProtectionService monitoringProtectionService;
@BeforeEach
void setUp() {
monitoringProtectionService = new MonitoringProtectionService(monitoringService);
}
@Test
void raceConditionPrevention_fileMoveDuringMonitoring() throws InterruptedException, IOException, ExecutionException, TimeoutException {
// Arrange
Path sourceFile = tempDir.resolve("source.txt");
Path targetFile = tempDir.resolve("target.txt");
Files.write(sourceFile, "test content".getBytes());
AtomicBoolean fileOperationCompleted = new AtomicBoolean(false);
AtomicBoolean monitoringDetectedMissingFile = new AtomicBoolean(false);
AtomicBoolean raceConditionOccurred = new AtomicBoolean(false);
// Configure mock behavior - monitoring is paused during file operations
when(monitoringService.isPaused()).thenAnswer(invocation -> {
// isPaused() should return true when monitoring is paused (during file operations)
// We start unpaused, then get paused during the operation, then unpaused after
return !fileOperationCompleted.get(); // true when operation is running = paused
});
// Start aggressive monitoring that looks for the file
ExecutorService monitoringExecutor = Executors.newSingleThreadExecutor();
Future<?> monitoringTask = monitoringExecutor.submit(() -> {
while (!fileOperationCompleted.get()) {
if (!monitoringService.isPaused() && !Files.exists(sourceFile)) {
monitoringDetectedMissingFile.set(true);
if (!fileOperationCompleted.get()) {
// This would be where the monitoring service deletes the "missing" file
raceConditionOccurred.set(true);
break;
}
}
try {
Thread.sleep(1); // Very aggressive checking
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
});
// Act - Perform file operation with protection
monitoringProtectionService.executeWithProtection(() -> {
try {
// Simulate the file operation that was causing issues
Thread.sleep(100); // Simulate some processing time
Files.move(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING);
Thread.sleep(100); // Simulate more processing time
fileOperationCompleted.set(true);
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
}, "race condition test");
// Wait for monitoring task to complete
monitoringTask.get(10, TimeUnit.SECONDS);
monitoringExecutor.shutdown();
// Assert
assertThat(Files.exists(targetFile)).isTrue();
assertThat(Files.exists(sourceFile)).isFalse();
assertThat(fileOperationCompleted.get()).isTrue();
// The critical assertion: monitoring should not have detected a missing file during the operation
assertThat(raceConditionOccurred.get())
.withFailMessage("Race condition occurred! Monitoring detected missing file during protected operation")
.isFalse();
}
@Test
void raceConditionPrevention_multipleConcurrentFileOperations() throws InterruptedException, IOException, ExecutionException, TimeoutException {
// Arrange
when(monitoringService.isPaused()).thenReturn(false).thenReturn(true);
// Multiple file operations that could interfere with each other
int numberOfOperations = 10;
List<Path> sourceFiles = new ArrayList<>();
List<Path> targetFiles = new ArrayList<>();
for (int i = 0; i < numberOfOperations; i++) {
Path source = tempDir.resolve("source_" + i + ".txt");
Path target = tempDir.resolve("target_" + i + ".txt");
Files.write(source, ("content " + i).getBytes());
sourceFiles.add(source);
targetFiles.add(target);
}
AtomicInteger completedOperations = new AtomicInteger(0);
AtomicInteger raceConditionCount = new AtomicInteger(0);
// Start monitoring that checks for missing files
ExecutorService monitoringExecutor = Executors.newSingleThreadExecutor();
Future<?> monitoringTask = monitoringExecutor.submit(() -> {
while (completedOperations.get() < numberOfOperations) {
if (!monitoringService.isPaused()) {
// Check for any missing source files
for (int i = 0; i < numberOfOperations; i++) {
Path source = sourceFiles.get(i);
Path target = targetFiles.get(i);
// If source is gone but target doesn't exist, it's a race condition
if (!Files.exists(source) && !Files.exists(target)) {
raceConditionCount.incrementAndGet();
}
}
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
});
// Act - Perform multiple concurrent file operations
ExecutorService operationExecutor = Executors.newFixedThreadPool(5);
CountDownLatch latch = new CountDownLatch(numberOfOperations);
for (int i = 0; i < numberOfOperations; i++) {
final int operationIndex = i;
operationExecutor.submit(() -> {
try {
monitoringProtectionService.executeWithProtection(() -> {
try {
Thread.sleep(50); // Simulate processing
Files.move(sourceFiles.get(operationIndex),
targetFiles.get(operationIndex),
StandardCopyOption.REPLACE_EXISTING);
completedOperations.incrementAndGet();
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
}, "concurrent operation " + operationIndex);
} finally {
latch.countDown();
}
});
}
// Wait for all operations to complete
boolean allCompleted = latch.await(30, TimeUnit.SECONDS);
monitoringTask.get(5, TimeUnit.SECONDS);
operationExecutor.shutdown();
monitoringExecutor.shutdown();
// Assert
assertThat(allCompleted).isTrue();
assertThat(completedOperations.get()).isEqualTo(numberOfOperations);
// All target files should exist
for (Path target : targetFiles) {
assertThat(Files.exists(target)).isTrue();
}
// No source files should exist
for (Path source : sourceFiles) {
assertThat(Files.exists(source)).isFalse();
}
// Critical assertion: no race conditions should have occurred
assertThat(raceConditionCount.get())
.withFailMessage("Race conditions detected during concurrent operations")
.isEqualTo(0);
}
@Test
void monitoringResumesAfterDelay() throws InterruptedException {
// Arrange
when(monitoringService.isPaused()).thenReturn(false, true);
// Act - Perform operation with protection
monitoringProtectionService.executeWithProtection(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "delay test");
// Wait for monitoring to resume (should happen after 5 seconds)
Thread.sleep(6000);
// Assert - Verify monitoring service methods were called
verify(monitoringService).pauseMonitoring();
verify(monitoringService).resumeMonitoring();
}
}
@@ -0,0 +1,421 @@
package com.adityachandel.booklore.service.bookdrop;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.mapper.BookdropFileMapper;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.BookdropFile;
import com.adityachandel.booklore.model.dto.BookdropFileNotification;
import com.adityachandel.booklore.model.dto.request.BookdropFinalizeRequest;
import com.adityachandel.booklore.model.dto.response.BookdropFinalizeResult;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookdropFileEntity;
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.BookRepository;
import com.adityachandel.booklore.repository.BookdropFileRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.file.FileMovingHelper;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Ignore;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
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.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class BookDropServiceTest {
@Mock
private BookdropFileRepository bookdropFileRepository;
@Mock
private LibraryRepository libraryRepository;
@Mock
private BookRepository bookRepository;
@Mock
private BookdropMonitoringService bookdropMonitoringService;
@Mock
private NotificationService notificationService;
@Mock
private MetadataRefreshService metadataRefreshService;
@Mock
private BookdropNotificationService bookdropNotificationService;
@Mock
private BookFileProcessorRegistry processorRegistry;
@Mock
private AppProperties appProperties;
@Mock
private BookdropFileMapper mapper;
@Mock
private ObjectMapper objectMapper;
@Mock
private FileMovingHelper fileMovingHelper;
@InjectMocks
private BookDropService bookDropService;
@TempDir
Path tempDir;
private BookdropFileEntity bookdropFileEntity;
private LibraryEntity libraryEntity;
private LibraryPathEntity libraryPathEntity;
private BookdropFile bookdropFile;
@BeforeEach
void setUp() throws IOException {
libraryPathEntity = new LibraryPathEntity();
libraryPathEntity.setId(1L);
libraryPathEntity.setPath(tempDir.toString());
libraryEntity = new LibraryEntity();
libraryEntity.setId(1L);
libraryEntity.setName("Test Library");
libraryEntity.setLibraryPaths(List.of(libraryPathEntity));
bookdropFileEntity = new BookdropFileEntity();
bookdropFileEntity.setId(1L);
bookdropFileEntity.setFileName("test-book.pdf");
bookdropFileEntity.setFilePath(tempDir.resolve("test-book.pdf").toString());
bookdropFileEntity.setStatus(BookdropFileEntity.Status.PENDING_REVIEW);
bookdropFileEntity.setOriginalMetadata("{\"title\":\"Test Book\"}");
bookdropFileEntity.setFetchedMetadata(null);
bookdropFile = new BookdropFile();
bookdropFile.setId(1L);
bookdropFile.setFileName("test-book.pdf");
Files.createFile(tempDir.resolve("test-book.pdf"));
}
@Test
void getFileNotificationSummary_ShouldReturnCorrectCounts() {
when(bookdropFileRepository.countByStatus(BookdropFileEntity.Status.PENDING_REVIEW)).thenReturn(5L);
when(bookdropFileRepository.count()).thenReturn(10L);
BookdropFileNotification result = bookDropService.getFileNotificationSummary();
assertEquals(5, result.getPendingCount());
assertEquals(10, result.getTotalCount());
assertNotNull(result.getLastUpdatedAt());
verify(bookdropFileRepository).countByStatus(BookdropFileEntity.Status.PENDING_REVIEW);
verify(bookdropFileRepository).count();
}
@Test
void getFilesByStatus_WhenStatusIsPending_ShouldReturnPendingFiles() {
Pageable pageable = PageRequest.of(0, 10);
Page<BookdropFileEntity> entityPage = new PageImpl<>(List.of(bookdropFileEntity));
Page<BookdropFile> expectedPage = new PageImpl<>(List.of(bookdropFile));
when(bookdropFileRepository.findAllByStatus(BookdropFileEntity.Status.PENDING_REVIEW, pageable))
.thenReturn(entityPage);
when(mapper.toDto(bookdropFileEntity)).thenReturn(bookdropFile);
Page<BookdropFile> result = bookDropService.getFilesByStatus("pending", pageable);
assertEquals(1, result.getContent().size());
assertEquals(bookdropFile, result.getContent().get(0));
verify(bookdropFileRepository).findAllByStatus(BookdropFileEntity.Status.PENDING_REVIEW, pageable);
verify(mapper).toDto(bookdropFileEntity);
}
@Test
void getFilesByStatus_WhenStatusIsNotPending_ShouldReturnAllFiles() {
Pageable pageable = PageRequest.of(0, 10);
Page<BookdropFileEntity> entityPage = new PageImpl<>(List.of(bookdropFileEntity));
when(bookdropFileRepository.findAll(pageable)).thenReturn(entityPage);
when(mapper.toDto(bookdropFileEntity)).thenReturn(bookdropFile);
Page<BookdropFile> result = bookDropService.getFilesByStatus("all", pageable);
assertEquals(1, result.getContent().size());
verify(bookdropFileRepository).findAll(pageable);
verify(mapper).toDto(bookdropFileEntity);
}
@Test
void getBookdropCover_WhenCoverExists_ShouldReturnResource() throws IOException {
long bookdropId = 1L;
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
Path coverPath = tempDir.resolve("bookdrop_temp").resolve("1.jpg");
Files.createDirectories(coverPath.getParent());
Files.createFile(coverPath);
Resource result = bookDropService.getBookdropCover(bookdropId);
assertNotNull(result);
assertTrue(result.exists());
}
@Test
void getBookdropCover_WhenCoverDoesNotExist_ShouldReturnNull() {
long bookdropId = 999L;
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
Resource result = bookDropService.getBookdropCover(bookdropId);
assertNull(result);
}
@Test
void finalizeImport_ShouldPauseAndResumeMonitoring() {
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(false);
request.setFiles(List.of());
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
assertNotNull(result);
assertNotNull(result.getProcessedAt());
verify(bookdropMonitoringService).pauseMonitoring();
verify(bookdropMonitoringService).resumeMonitoring();
}
@Test
@Disabled
void finalizeImport_WhenSelectAllTrue_ShouldProcessAllFiles() throws Exception {
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(true);
request.setDefaultLibraryId(1L);
request.setDefaultPathId(1L);
request.setExcludedIds(List.of());
BookMetadata metadata = new BookMetadata();
metadata.setTitle("Test Book");
when(bookdropFileRepository.findAllExcludingIdsFlat(any())).thenReturn(List.of(1L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity));
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
.thenReturn(tempDir.resolve("moved-book.pdf"));
BookFileProcessor processor = mock(BookFileProcessor.class);
when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor);
Book book = Book.builder()
.id(1L)
.title("Test Book")
.build();
FileProcessResult processResult = FileProcessResult.builder()
.book(book)
.build();
when(processor.processFile(any())).thenReturn(processResult);
BookEntity bookEntity = new BookEntity();
bookEntity.setId(1L);
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.createTempFile(anyString(), anyString())).thenReturn(tempDir.resolve("temp-file"));
filesMock.when(() -> Files.copy(any(Path.class), any(Path.class), any())).thenReturn(1024L);
filesMock.when(() -> Files.createDirectories(any(Path.class))).thenReturn(tempDir);
filesMock.when(() -> Files.move(any(Path.class), any(Path.class), any())).thenReturn(tempDir);
filesMock.when(() -> Files.deleteIfExists(any(Path.class))).thenReturn(true);
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
assertNotNull(result);
assertEquals(1, result.getTotalFiles());
assertEquals(1, result.getSuccessfullyImported());
assertEquals(0, result.getFailed());
}
}
@Test
void finalizeImport_WhenLibraryNotFound_ShouldFail() throws Exception {
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(true);
request.setDefaultLibraryId(999L);
request.setDefaultPathId(1L);
when(bookdropFileRepository.findAllExcludingIdsFlat(any())).thenReturn(List.of(1L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(999L)).thenReturn(Optional.empty());
BookMetadata metadata = new BookMetadata();
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
assertNotNull(result);
assertEquals(1, result.getTotalFiles());
assertEquals(0, result.getSuccessfullyImported());
assertEquals(1, result.getFailed());
}
}
@Test
void discardSelectedFiles_WhenSelectAllTrue_ShouldDeleteAllExceptExcluded() throws IOException {
List<Long> excludedIds = List.of(2L);
BookdropFileEntity fileToDelete = new BookdropFileEntity();
fileToDelete.setId(1L);
fileToDelete.setFilePath(tempDir.resolve("file-to-delete.pdf").toString());
Files.createFile(tempDir.resolve("file-to-delete.pdf"));
when(bookdropFileRepository.findAll()).thenReturn(List.of(fileToDelete));
when(appProperties.getBookdropFolder()).thenReturn(tempDir.toString());
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.walk(any(Path.class))).thenReturn(java.util.stream.Stream.of(tempDir));
filesMock.when(() -> Files.isDirectory(any(Path.class))).thenReturn(false);
filesMock.when(() -> Files.isRegularFile(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.deleteIfExists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.list(any(Path.class))).thenReturn(java.util.stream.Stream.empty());
bookDropService.discardSelectedFiles(true, excludedIds, null);
verify(bookdropFileRepository).findAll();
verify(bookdropFileRepository).deleteAllById(List.of(1L));
verify(bookdropNotificationService).sendBookdropFileSummaryNotification();
verify(bookdropMonitoringService).pauseMonitoring();
verify(bookdropMonitoringService).resumeMonitoring();
}
}
@Test
void discardSelectedFiles_WhenSelectAllFalse_ShouldDeleteOnlySelected() throws IOException {
List<Long> selectedIds = List.of(1L);
when(bookdropFileRepository.findAllById(selectedIds)).thenReturn(List.of(bookdropFileEntity));
when(appProperties.getBookdropFolder()).thenReturn(tempDir.toString());
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.walk(any(Path.class))).thenReturn(java.util.stream.Stream.of(tempDir));
filesMock.when(() -> Files.isDirectory(any(Path.class))).thenReturn(false);
filesMock.when(() -> Files.isRegularFile(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.deleteIfExists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.list(any(Path.class))).thenReturn(java.util.stream.Stream.empty());
bookDropService.discardSelectedFiles(false, null, selectedIds);
verify(bookdropFileRepository).findAllById(selectedIds);
verify(bookdropFileRepository).deleteAllById(List.of(1L));
verify(bookdropNotificationService).sendBookdropFileSummaryNotification();
}
}
@Test
void discardSelectedFiles_WhenBookdropFolderDoesNotExist_ShouldHandleGracefully() {
when(appProperties.getBookdropFolder()).thenReturn("/non-existent-path");
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(false);
bookDropService.discardSelectedFiles(true, null, null);
verify(bookdropMonitoringService).pauseMonitoring();
verify(bookdropMonitoringService).resumeMonitoring();
}
}
@Test
void finalizeImport_WhenSourceFileDoesNotExist_ShouldDeleteFromDB() throws Exception {
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(true);
request.setDefaultLibraryId(1L);
request.setDefaultPathId(1L);
BookdropFileEntity missingFileEntity = new BookdropFileEntity();
missingFileEntity.setId(2L);
missingFileEntity.setFileName("missing-file.pdf");
missingFileEntity.setFilePath("/non-existent/missing-file.pdf");
missingFileEntity.setOriginalMetadata("{\"title\":\"Missing Book\"}");
missingFileEntity.setFetchedMetadata(null);
when(bookdropFileRepository.findAllExcludingIdsFlat(any())).thenReturn(List.of(2L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(missingFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity));
BookMetadata metadata = new BookMetadata();
metadata.setTitle("Missing Book");
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
.thenReturn(tempDir.resolve("target-file.pdf"));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(Path.of("/non-existent/missing-file.pdf"))).thenReturn(false);
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
verify(bookdropFileRepository).deleteById(2L);
verify(bookdropNotificationService).sendBookdropFileSummaryNotification();
assertNotNull(result);
assertEquals(1, result.getTotalFiles());
assertEquals(0, result.getSuccessfullyImported());
assertEquals(1, result.getFailed());
}
}
@Test
void finalizeImport_WhenIOExceptionDuringMove_ShouldHandleGracefully() throws Exception {
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(true);
request.setDefaultLibraryId(1L);
request.setDefaultPathId(1L);
when(bookdropFileRepository.findAllExcludingIdsFlat(any())).thenReturn(List.of(1L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity));
BookMetadata metadata = new BookMetadata();
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
.thenReturn(tempDir.resolve("target-file.pdf"));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.createTempFile(anyString(), anyString()))
.thenThrow(new IOException("Disk full"));
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
assertNotNull(result);
assertEquals(1, result.getTotalFiles());
assertEquals(0, result.getSuccessfullyImported());
assertEquals(1, result.getFailed());
}
}
}
@@ -0,0 +1,362 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.request.FileMoveRequest;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.util.PathPatternResolver;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.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.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class FileMoveServiceTest {
@Mock
private BookQueryService bookQueryService;
@Mock
private BookRepository bookRepository;
@Mock
private BookMapper bookMapper;
@Mock
private NotificationService notificationService;
@Mock
private UnifiedFileMoveService unifiedFileMoveService;
@InjectMocks
private FileMoveService fileMoveService;
private BookEntity bookEntity1;
private BookEntity bookEntity2;
private Book book1;
private Book book2;
@BeforeEach
void setUp() {
// Setup BookMetadataEntity for book1
BookMetadataEntity metadata1 = new BookMetadataEntity();
metadata1.setTitle("Test Book 1");
bookEntity1 = new BookEntity();
bookEntity1.setId(1L);
bookEntity1.setMetadata(metadata1);
metadata1.setBook(bookEntity1);
// Setup BookMetadataEntity for book2
BookMetadataEntity metadata2 = new BookMetadataEntity();
metadata2.setTitle("Test Book 2");
bookEntity2 = new BookEntity();
bookEntity2.setId(2L);
bookEntity2.setMetadata(metadata2);
metadata2.setBook(bookEntity2);
book1 = mock(Book.class);
book2 = mock(Book.class);
}
@Test
void moveFiles_WhenSingleBatch_ShouldProcessAllBooks() {
// Given
Set<Long> bookIds = Set.of(1L, 2L);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
List<BookEntity> batchBooks = List.of(bookEntity1, bookEntity2);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(batchBooks);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 100, 100))
.thenReturn(List.of());
when(bookMapper.toBook(bookEntity1)).thenReturn(book1);
when(bookMapper.toBook(bookEntity2)).thenReturn(book2);
doAnswer(invocation -> {
UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(1);
callback.onBookMoved(bookEntity1);
callback.onBookMoved(bookEntity2);
return null;
}).when(unifiedFileMoveService).moveBatchBookFiles(eq(batchBooks), any());
// When
fileMoveService.moveFiles(request);
// Then
verify(bookQueryService).findWithMetadataByIdsWithPagination(bookIds, 0, 100);
verify(unifiedFileMoveService).moveBatchBookFiles(eq(batchBooks), any());
verify(bookRepository).save(bookEntity1);
verify(bookRepository).save(bookEntity2);
verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), eq(List.of(book1, book2)));
}
@Test
void moveFiles_WhenMultipleBatches_ShouldProcessAllBatches() {
// Given - create >100 ids so service iterates multiple batches
Set<Long> bookIds = IntStream.rangeClosed(1, 150)
.mapToObj(i -> (long) i)
.collect(Collectors.toSet());
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
// First batch
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(List.of(bookEntity1));
// Second batch
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 100, 100))
.thenReturn(List.of(bookEntity2));
// Third batch - empty
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 200, 100))
.thenReturn(List.of());
when(book1.getId()).thenReturn(1L);
when(book2.getId()).thenReturn(2L);
when(bookMapper.toBook(bookEntity1)).thenReturn(book1);
when(bookMapper.toBook(bookEntity2)).thenReturn(book2);
doAnswer(invocation -> {
UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(1);
List<BookEntity> books = invocation.getArgument(0);
for (BookEntity book : books) {
callback.onBookMoved(book);
}
return null;
}).when(unifiedFileMoveService).moveBatchBookFiles(any(), any());
// When
fileMoveService.moveFiles(request);
// Then
verify(bookQueryService).findWithMetadataByIdsWithPagination(bookIds, 0, 100);
verify(bookQueryService).findWithMetadataByIdsWithPagination(bookIds, 100, 100);
verify(unifiedFileMoveService, times(2)).moveBatchBookFiles(any(), any());
verify(bookRepository).save(bookEntity1);
verify(bookRepository).save(bookEntity2);
verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), eq(List.of(book1, book2)));
}
@Test
void moveFiles_WhenNoBooksFound_ShouldNotProcessAnything() {
// Given
Set<Long> bookIds = Set.of(1L, 2L);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(List.of());
// When
fileMoveService.moveFiles(request);
// Then
verify(bookQueryService).findWithMetadataByIdsWithPagination(bookIds, 0, 100);
verify(unifiedFileMoveService, never()).moveBatchBookFiles(any(), any());
verify(bookRepository, never()).save(any());
verify(notificationService, never()).sendMessage(any(), any());
}
@Test
void moveFiles_WhenMoveFailsForSomeBooks_ShouldThrowException() {
// Given
Set<Long> bookIds = Set.of(1L, 2L);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
List<BookEntity> batchBooks = List.of(bookEntity1, bookEntity2);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(batchBooks);
RuntimeException moveException = new RuntimeException("File move failed");
doAnswer(invocation -> {
UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(1);
callback.onBookMoved(bookEntity1);
callback.onBookMoveFailed(bookEntity2, moveException);
return null;
}).when(unifiedFileMoveService).moveBatchBookFiles(eq(batchBooks), any());
when(bookMapper.toBook(bookEntity1)).thenReturn(book1);
// When & Then
RuntimeException exception = assertThrows(RuntimeException.class, () -> {
fileMoveService.moveFiles(request);
});
assertEquals("File move failed for book id 2", exception.getMessage());
assertEquals(moveException, exception.getCause());
verify(bookRepository).save(bookEntity1);
verify(bookRepository, never()).save(bookEntity2);
}
@Test
void moveFiles_WhenEmptyBookIds_ShouldCompleteWithoutProcessing() {
// Given
Set<Long> bookIds = Set.of();
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
// When
fileMoveService.moveFiles(request);
// Then: service should not call pagination when bookIds is empty
verify(bookQueryService, never()).findWithMetadataByIdsWithPagination(anySet(), anyInt(), anyInt());
verify(unifiedFileMoveService, never()).moveBatchBookFiles(any(), any());
verify(notificationService, never()).sendMessage(any(), any());
}
@Test
void moveFiles_WhenPartialBatch_ShouldProcessCorrectly() {
// Given
Set<Long> bookIds = Set.of(1L);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(List.of(bookEntity1));
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 100, 100))
.thenReturn(List.of());
when(book1.getId()).thenReturn(1L);
when(bookMapper.toBook(bookEntity1)).thenReturn(book1);
doAnswer(invocation -> {
UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(1);
callback.onBookMoved(bookEntity1);
return null;
}).when(unifiedFileMoveService).moveBatchBookFiles(any(), any());
// When
fileMoveService.moveFiles(request);
// Then
verify(bookQueryService).findWithMetadataByIdsWithPagination(bookIds, 0, 100);
verify(unifiedFileMoveService).moveBatchBookFiles(eq(List.of(bookEntity1)), any());
verify(bookRepository).save(bookEntity1);
verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), eq(List.of(book1)));
}
@Test
void generatePathFromPattern_ShouldDelegateToPathPatternResolver() {
// Given
String pattern = "{author}/{title}";
String expectedPath = "John Doe/Test Book";
try (MockedStatic<PathPatternResolver> mockedResolver = mockStatic(PathPatternResolver.class)) {
mockedResolver.when(() -> PathPatternResolver.resolvePattern(bookEntity1, pattern))
.thenReturn(expectedPath);
// When
String result = fileMoveService.generatePathFromPattern(bookEntity1, pattern);
// Then
assertEquals(expectedPath, result);
mockedResolver.verify(() -> PathPatternResolver.resolvePattern(bookEntity1, pattern));
}
}
@Test
void generatePathFromPattern_WithDifferentPatterns_ShouldReturnCorrectPaths() {
// Given
String pattern1 = "{title}";
String pattern2 = "{author}/{series}/{title}";
String expectedPath1 = "Test Book 1";
String expectedPath2 = "Author/Series/Test Book 1";
try (MockedStatic<PathPatternResolver> mockedResolver = mockStatic(PathPatternResolver.class)) {
mockedResolver.when(() -> PathPatternResolver.resolvePattern(bookEntity1, pattern1))
.thenReturn(expectedPath1);
mockedResolver.when(() -> PathPatternResolver.resolvePattern(bookEntity1, pattern2))
.thenReturn(expectedPath2);
// When
String result1 = fileMoveService.generatePathFromPattern(bookEntity1, pattern1);
String result2 = fileMoveService.generatePathFromPattern(bookEntity1, pattern2);
// Then
assertEquals(expectedPath1, result1);
assertEquals(expectedPath2, result2);
mockedResolver.verify(() -> PathPatternResolver.resolvePattern(bookEntity1, pattern1));
mockedResolver.verify(() -> PathPatternResolver.resolvePattern(bookEntity1, pattern2));
}
}
@Test
void moveFiles_ShouldSendNotificationWithAllUpdatedBooks() {
// Given
Set<Long> bookIds = Set.of(1L, 2L);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(List.of(bookEntity1, bookEntity2));
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 100, 100))
.thenReturn(List.of());
when(bookMapper.toBook(bookEntity1)).thenReturn(book1);
when(bookMapper.toBook(bookEntity2)).thenReturn(book2);
doAnswer(invocation -> {
UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(1);
callback.onBookMoved(bookEntity1);
callback.onBookMoved(bookEntity2);
return null;
}).when(unifiedFileMoveService).moveBatchBookFiles(any(), any());
// When
fileMoveService.moveFiles(request);
// Then
ArgumentCaptor<List<Book>> booksCaptor = ArgumentCaptor.forClass(List.class);
verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), booksCaptor.capture());
List<Book> sentBooks = booksCaptor.getValue();
assertEquals(2, sentBooks.size());
assertTrue(sentBooks.contains(book1));
assertTrue(sentBooks.contains(book2));
}
@Test
void moveFiles_WhenNoBooksMoved_ShouldNotSendNotification() {
// Given
Set<Long> bookIds = Set.of(1L, 2L);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(List.of(bookEntity1, bookEntity2));
RuntimeException moveException = new RuntimeException("All moves failed");
doAnswer(invocation -> {
UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(1);
callback.onBookMoveFailed(bookEntity1, moveException);
return null;
}).when(unifiedFileMoveService).moveBatchBookFiles(any(), any());
// When & Then
assertThrows(RuntimeException.class, () -> {
fileMoveService.moveFiles(request);
});
verify(notificationService, never()).sendMessage(any(), any());
}
}
@@ -0,0 +1,306 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.util.PathPatternResolver;
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 java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class FileMovingHelperTest {
@Mock
BookAdditionalFileRepository additionalFileRepository;
@Mock
AppSettingService appSettingService;
@InjectMocks
FileMovingHelper helper;
@TempDir
Path tmp;
LibraryEntity library;
LibraryPathEntity libraryPath;
BookEntity book;
@BeforeEach
void init() {
library = new LibraryEntity();
library.setId(11L);
library.setName("lib");
libraryPath = new LibraryPathEntity();
libraryPath.setId(22L);
libraryPath.setPath(tmp.toString());
library.setLibraryPaths(List.of(libraryPath));
book = new BookEntity();
book.setId(101L);
BookMetadataEntity metaEntity = new BookMetadataEntity();
metaEntity.setTitle("Title");
book.setMetadata(metaEntity);
metaEntity.setBook(book);
book.setLibraryPath(libraryPath);
}
@Test
void generateNewFilePath_fromBook_usesResolvedPattern() {
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(book), eq("{pattern}")))
.thenReturn("some/sub/path/book.pdf");
Path result = helper.generateNewFilePath(book, "{pattern}");
assertTrue(result.toAbsolutePath().toString().contains("some/sub/path/book.pdf"));
}
}
@Test
void generateNewFilePath_fromMetadata_usesResolvedPattern() {
BookMetadata metadata = new BookMetadata();
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(metadata), eq("{p}"), eq("orig.pdf")))
.thenReturn("meta/path/orig.pdf");
Path result = helper.generateNewFilePath(tmp.toString(), metadata, "{p}", "orig.pdf");
assertTrue(result.toString().endsWith("meta/path/orig.pdf"));
}
}
@Test
void getFileNamingPattern_prefersLibrary_thenApp_thenFallback() {
library.setFileNamingPattern("LIB_PATTERN/{currentFilename}");
String p1 = helper.getFileNamingPattern(library);
assertEquals("LIB_PATTERN/{currentFilename}", p1);
library.setFileNamingPattern(null);
AppSettings settings = new AppSettings();
settings.setUploadPattern("APP_PATTERN/{currentFilename}");
when(appSettingService.getAppSettings()).thenReturn(settings);
String p2 = helper.getFileNamingPattern(library);
assertEquals("APP_PATTERN/{currentFilename}", p2);
settings.setUploadPattern(null);
when(appSettingService.getAppSettings()).thenReturn(settings);
String p3 = helper.getFileNamingPattern(library);
assertEquals("{currentFilename}", p3);
}
@Test
void hasRequiredPathComponents_returnsFalseWhenMissing() {
BookEntity b = new BookEntity();
b.setId(1L);
b.setFileName("f");
b.setFileSubPath("s");
assertFalse(helper.hasRequiredPathComponents(b));
book.setFileSubPath("s");
book.setFileName(null);
assertFalse(helper.hasRequiredPathComponents(book));
book.setFileName("file.pdf");
assertTrue(helper.hasRequiredPathComponents(book));
}
@Test
void moveBookFileIfNeeded_noOpWhenPathsEqual() throws IOException {
book.setFileSubPath("same");
book.setFileName("file.pdf");
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(book), anyString()))
.thenReturn("same/file.pdf");
boolean changed = helper.moveBookFileIfNeeded(book, "{p}");
assertFalse(changed);
}
}
@Test
void moveBookFileIfNeeded_movesAndUpdatesPaths() throws Exception {
book.setFileSubPath("olddir");
book.setFileName("file.pdf");
Path oldDir = tmp.resolve("olddir");
Files.createDirectories(oldDir);
Path oldFile = oldDir.resolve("file.pdf");
Files.createFile(oldFile);
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(book), anyString()))
.thenReturn("newdir/file.pdf");
boolean moved = helper.moveBookFileIfNeeded(book, "{p}");
assertTrue(moved);
Path newFile = tmp.resolve("newdir").resolve("file.pdf");
assertTrue(Files.exists(newFile));
assertEquals("newdir", book.getFileSubPath());
assertEquals("file.pdf", book.getFileName());
assertFalse(Files.exists(oldFile));
}
}
@Test
void moveAdditionalFiles_movesFilesAndSaves() throws Exception {
book.setFileSubPath(".");
book.setFileName("book.pdf");
BookAdditionalFileEntity add = new BookAdditionalFileEntity();
add.setId(555L);
add.setFileSubPath("oldsub");
add.setFileName("add.pdf");
add.setBook(book);
book.setAdditionalFiles(List.of(add));
Path oldDir = tmp.resolve("oldsub");
Files.createDirectories(oldDir);
Path oldFile = oldDir.resolve("add.pdf");
Files.createFile(oldFile);
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(book.getMetadata()), anyString(), eq("add.pdf")))
.thenReturn("additional/newadd.pdf");
helper.moveAdditionalFiles(book, "{pattern}");
Path newFile = tmp.resolve("additional").resolve("newadd.pdf");
assertTrue(Files.exists(newFile));
verify(additionalFileRepository).save(add);
assertEquals("newadd.pdf", add.getFileName());
}
}
@Test
void generateNewFilePath_trimsLeadingSeparator() {
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(book), eq("{pattern}")))
.thenReturn("/leading/path/book.pdf");
Path result = helper.generateNewFilePath(book, "{pattern}");
assertTrue(result.toString().endsWith("leading/path/book.pdf"));
assertFalse(result.toString().contains("//"));
}
}
@Test
void getFileNamingPattern_appendsFilename_whenEndsWithSeparator() {
library.setFileNamingPattern("SOME/PATTERN/");
String pattern = helper.getFileNamingPattern(library);
assertTrue(pattern.endsWith("{currentFilename}"));
assertEquals("SOME/PATTERN/{currentFilename}", pattern);
}
@Test
void moveFile_createsParentDirectories_and_movesFile() throws Exception {
Path srcDir = tmp.resolve("srcdir");
Files.createDirectories(srcDir);
Path src = srcDir.resolve("file.txt");
Files.writeString(src, "hello");
Path target = tmp.resolve("nested").resolve("deep").resolve("file.txt");
assertFalse(Files.exists(target.getParent()));
helper.moveFile(src, target);
assertTrue(Files.exists(target));
assertFalse(Files.exists(src));
assertTrue(Files.exists(target.getParent()));
}
@Test
void deleteEmptyParentDirsUpToLibraryFolders_deletesIgnoredFilesAndDirs() throws Exception {
Path libRoot = tmp.resolve("libroot");
Path dir1 = libRoot.resolve("dir1");
Path dir2 = dir1.resolve("dir2");
Files.createDirectories(dir2);
Files.writeString(dir2.resolve(".DS_Store"), "");
Files.writeString(dir1.resolve(".DS_Store"), "");
assertTrue(Files.exists(dir2));
assertTrue(Files.exists(dir1));
assertTrue(Files.exists(libRoot) || Files.createDirectories(libRoot) != null);
helper.deleteEmptyParentDirsUpToLibraryFolders(dir2, Set.of(libRoot));
assertFalse(Files.exists(dir2));
assertFalse(Files.exists(dir1));
assertTrue(Files.exists(libRoot));
}
@Test
void deleteEmptyParentDirsUpToLibraryFolders_stopsWhenNonIgnoredPresent() throws Exception {
Path libRoot = tmp.resolve("libroot2");
Path dir = libRoot.resolve("keepdir");
Files.createDirectories(dir);
Files.writeString(dir.resolve("keep.txt"), "keep");
helper.deleteEmptyParentDirsUpToLibraryFolders(dir, Set.of(libRoot));
assertTrue(Files.exists(dir));
}
@Test
void moveAdditionalFiles_handles_duplicate_target_names_and_saves() throws Exception {
book.setFileSubPath(".");
book.setFileName("book.pdf");
BookAdditionalFileEntity a1 = new BookAdditionalFileEntity();
a1.setId(1L);
a1.setFileSubPath("oldsub");
a1.setFileName("add.pdf");
a1.setBook(book);
BookAdditionalFileEntity a2 = new BookAdditionalFileEntity();
a2.setId(2L);
a2.setFileSubPath("oldsub");
a2.setFileName("add_2.pdf");
a2.setBook(book);
book.setAdditionalFiles(List.of(a1, a2));
Path oldDir = tmp.resolve("oldsub");
Files.createDirectories(oldDir);
Files.writeString(oldDir.resolve("add.pdf"), "one");
Files.writeString(oldDir.resolve("add_2.pdf"), "two");
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(book.getMetadata()), anyString(), eq("add.pdf")))
.thenReturn("additional/add.pdf");
ms.when(() -> PathPatternResolver.resolvePattern(eq(book.getMetadata()), anyString(), eq("add_2.pdf")))
.thenReturn("additional/add.pdf");
helper.moveAdditionalFiles(book, "{pattern}");
Path first = tmp.resolve("additional").resolve("add.pdf");
Path second = tmp.resolve("additional").resolve("add_2.pdf");
assertTrue(Files.exists(first));
assertTrue(Files.exists(second));
verify(additionalFileRepository, atLeastOnce()).save(any(BookAdditionalFileEntity.class));
assertTrue(a1.getFileName().equals("add.pdf") || a1.getFileName().equals("add_2.pdf"));
assertTrue(a2.getFileName().equals("add.pdf") || a2.getFileName().equals("add_2.pdf"));
assertNotEquals(a1.getFileName(), a2.getFileName());
}
}
}
@@ -0,0 +1,208 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
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 java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class MonitoredFileOperationServiceTest {
@Mock
MonitoringRegistrationService monitoringRegistrationService;
@InjectMocks
MonitoredFileOperationService service;
@TempDir
Path tmp;
Path sourceDir;
Path targetDir;
Path sourceFile;
Path targetFile;
final Long libraryId = 42L;
@BeforeEach
void init() throws IOException {
sourceDir = tmp.resolve("source");
Files.createDirectories(sourceDir);
sourceFile = sourceDir.resolve("file.txt");
Files.writeString(sourceFile, "data");
targetDir = tmp.resolve("target");
targetFile = targetDir.resolve("file.txt");
}
@Test
void executeWithMonitoringSuspended_unregistersAndReregisters_whenDifferentPaths() {
Supplier<String> operation = () -> {
try {
Files.createDirectories(targetDir);
Files.createDirectories(targetDir.resolve("sub"));
Files.writeString(targetFile, "moved");
} catch (IOException e) {
throw new RuntimeException(e);
}
return "ok";
};
when(monitoringRegistrationService.isPathMonitored(any()))
.thenAnswer(invocation -> {
Path p = invocation.getArgument(0);
return p.equals(sourceDir);
});
service.executeWithMonitoringSuspended(sourceFile, targetFile, libraryId, operation);
verify(monitoringRegistrationService).isPathMonitored(eq(sourceDir));
verify(monitoringRegistrationService).unregisterSpecificPath(eq(sourceDir));
verify(monitoringRegistrationService).registerSpecificPath(eq(sourceDir), eq(libraryId));
verify(monitoringRegistrationService).registerSpecificPath(eq(targetDir), eq(libraryId));
verify(monitoringRegistrationService).registerSpecificPath(eq(targetDir.resolve("sub")), eq(libraryId));
}
@Test
void executeWithMonitoringSuspended_skipsDoubleUnregister_whenSamePaths() {
Path src = sourceDir.resolve("a.txt");
Path tgt = sourceDir.resolve("b.txt");
when(monitoringRegistrationService.isPathMonitored(eq(sourceDir))).thenReturn(true);
Supplier<Boolean> operation = () -> {
try {
Files.writeString(tgt, "x");
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
};
service.executeWithMonitoringSuspended(src, tgt, libraryId, operation);
verify(monitoringRegistrationService).unregisterSpecificPath(eq(sourceDir));
verify(monitoringRegistrationService, never()).unregisterSpecificPath(eq(targetDir));
verify(monitoringRegistrationService).registerSpecificPath(eq(sourceDir), eq(libraryId));
}
@Test
void executeWithMonitoringSuspended_reRegistersEvenIfOperationThrows() {
when(monitoringRegistrationService.isPathMonitored(eq(sourceDir))).thenReturn(true);
Supplier<Void> operation = () -> {
throw new IllegalStateException("boom");
};
IllegalStateException ex = assertThrows(IllegalStateException.class, () ->
service.executeWithMonitoringSuspended(sourceFile, targetFile, libraryId, operation)
);
assertEquals("boom", ex.getMessage());
verify(monitoringRegistrationService).unregisterSpecificPath(eq(sourceDir));
verify(monitoringRegistrationService).registerSpecificPath(eq(sourceDir), eq(libraryId));
}
@Test
void reregister_handlesFilesWalkIOException_gracefully() throws Exception {
Supplier<String> operation = () -> {
try {
Files.createDirectories(targetDir);
Files.writeString(targetFile, "moved");
} catch (IOException e) {
throw new RuntimeException(e);
}
return "ok";
};
when(monitoringRegistrationService.isPathMonitored(any()))
.thenAnswer(invocation -> false);
try (MockedStatic<Files> filesMock = mockStatic(Files.class, invocation -> invocation.callRealMethod())) {
filesMock.when(() -> Files.exists(any(Path.class))).thenCallRealMethod();
filesMock.when(() -> Files.isDirectory(any(Path.class))).thenCallRealMethod();
filesMock.when(() -> Files.walk(eq(targetDir))).thenThrow(new IOException("walk fail"));
assertDoesNotThrow(() ->
service.executeWithMonitoringSuspended(sourceFile, targetFile, libraryId, operation)
);
verify(monitoringRegistrationService).registerSpecificPath(eq(targetDir), eq(libraryId));
}
}
@Test
void executeWithMonitoringSuspended_skipsReregister_whenSourceRemovedByOperation() {
when(monitoringRegistrationService.isPathMonitored(eq(sourceDir))).thenReturn(true);
Supplier<String> operation = () -> {
try {
Files.deleteIfExists(sourceFile);
Files.deleteIfExists(sourceDir);
} catch (IOException e) {
throw new RuntimeException(e);
}
return "done";
};
service.executeWithMonitoringSuspended(sourceFile, targetFile, libraryId, operation);
verify(monitoringRegistrationService).unregisterSpecificPath(eq(sourceDir));
verify(monitoringRegistrationService, never()).registerSpecificPath(eq(sourceDir), eq(libraryId));
}
@Test
void noUnregisters_whenNothingMonitored() {
Supplier<String> operation = () -> {
try {
Files.createDirectories(targetDir);
Files.writeString(targetFile, "ok");
} catch (IOException e) {
throw new RuntimeException(e);
}
return "ok";
};
when(monitoringRegistrationService.isPathMonitored(any())).thenReturn(false);
service.executeWithMonitoringSuspended(sourceFile, targetFile, libraryId, operation);
verify(monitoringRegistrationService, never()).unregisterSpecificPath(any());
verify(monitoringRegistrationService).registerSpecificPath(eq(targetDir), eq(libraryId));
}
@Test
void targetAlreadyMonitored_doesNotReRegister() throws Exception {
Files.createDirectories(targetDir);
when(monitoringRegistrationService.isPathMonitored(eq(sourceDir))).thenReturn(true);
when(monitoringRegistrationService.isPathMonitored(eq(targetDir))).thenReturn(true);
Supplier<String> operation = () -> {
try {
Files.writeString(targetFile, "x");
} catch (IOException e) {
throw new RuntimeException(e);
}
return "done";
};
service.executeWithMonitoringSuspended(sourceFile, targetFile, libraryId, operation);
verify(monitoringRegistrationService).unregisterSpecificPath(eq(sourceDir));
verify(monitoringRegistrationService).unregisterSpecificPath(eq(targetDir));
verify(monitoringRegistrationService).registerSpecificPath(eq(targetDir), eq(libraryId));
}
}
@@ -0,0 +1,210 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
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.service.monitoring.MonitoringRegistrationService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static java.util.Collections.singletonList;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class UnifiedFileMoveServiceTest {
@Mock
FileMovingHelper fileMovingHelper;
@Mock
MonitoredFileOperationService monitoredFileOperationService;
@Mock
MonitoringRegistrationService monitoringRegistrationService;
@InjectMocks
UnifiedFileMoveService service;
@TempDir
Path tmp;
LibraryEntity library;
LibraryPathEntity libraryPath;
@BeforeEach
void setup() {
library = new LibraryEntity();
library.setId(10L);
library.setName("lib");
libraryPath = new LibraryPathEntity();
libraryPath.setId(20L);
libraryPath.setPath(tmp.toString());
libraryPath.setLibrary(library);
library.setLibraryPaths(singletonList(libraryPath));
}
@Test
void moveSingleBookFile_skipsWhenNoLibrary() {
BookEntity book = new BookEntity();
// no libraryPath set
service.moveSingleBookFile(book);
verifyNoInteractions(monitoredFileOperationService);
verifyNoInteractions(fileMovingHelper);
}
@Test
void moveSingleBookFile_skipsWhenFileMissing() throws Exception {
BookEntity book = new BookEntity();
book.setId(1L);
book.setLibraryPath(libraryPath);
book.setFileSubPath(".");
book.setFileName("missing.pdf");
when(fileMovingHelper.getFileNamingPattern(any())).thenReturn("{currentFilename}");
service.moveSingleBookFile(book);
verifyNoInteractions(monitoredFileOperationService);
}
@Test
void moveSingleBookFile_executesMoveWhenNeeded() throws Exception {
BookEntity book = new BookEntity();
book.setId(2L);
book.setLibraryPath(libraryPath);
book.setFileSubPath(".");
book.setFileName("book.pdf");
Path src = tmp.resolve("book.pdf");
Files.writeString(src, "data");
Path expected = tmp.resolve("moved").resolve("book.pdf");
when(fileMovingHelper.getFileNamingPattern(library)).thenReturn("{currentFilename}");
when(fileMovingHelper.generateNewFilePath(eq(book), anyString())).thenReturn(expected);
when(fileMovingHelper.hasRequiredPathComponents(eq(book))).thenReturn(true);
doAnswer(invocation -> {
java.util.function.Supplier<?> supplier = invocation.getArgument(3);
supplier.get();
return null;
}).when(monitoredFileOperationService).executeWithMonitoringSuspended(any(), any(), anyLong(), any());
when(fileMovingHelper.moveBookFileIfNeeded(eq(book), anyString())).thenAnswer(inv -> {
book.setFileSubPath("moved");
book.setFileName("book.pdf");
return true;
});
Path actualSrc = book.getFullFilePath();
service.moveSingleBookFile(book);
verify(monitoredFileOperationService).executeWithMonitoringSuspended(eq(actualSrc), eq(expected), eq(10L), any());
verify(fileMovingHelper).moveBookFileIfNeeded(eq(book), anyString());
assertEquals("moved", book.getFileSubPath());
}
@Test
void moveBatchBookFiles_movesBooks_and_callsCallback_and_reRegistersLibraries() throws Exception {
BookEntity b1 = new BookEntity();
b1.setId(11L);
b1.setLibraryPath(libraryPath);
b1.setFileSubPath(".");
b1.setFileName("a.pdf");
BookMetadataEntity m1 = new BookMetadataEntity();
m1.setTitle("A");
b1.setMetadata(m1);
m1.setBook(b1);
BookEntity b2 = new BookEntity();
b2.setId(12L);
b2.setLibraryPath(libraryPath);
b2.setFileSubPath(".");
b2.setFileName("b.pdf");
BookMetadataEntity m2 = new BookMetadataEntity();
m2.setTitle("B");
b2.setMetadata(m2);
m2.setBook(b2);
Path p1 = tmp.resolve("a.pdf");
Path p2 = tmp.resolve("b.pdf");
Files.writeString(p1, "1");
Files.writeString(p2, "2");
when(fileMovingHelper.getFileNamingPattern(library)).thenReturn("{currentFilename}");
when(fileMovingHelper.hasRequiredPathComponents(eq(b1))).thenReturn(true);
when(fileMovingHelper.hasRequiredPathComponents(eq(b2))).thenReturn(true);
when(fileMovingHelper.moveBookFileIfNeeded(eq(b1), anyString())).thenAnswer(inv -> {
b1.setFileSubPath("moved");
return true;
});
when(fileMovingHelper.moveBookFileIfNeeded(eq(b2), anyString())).thenReturn(false);
BookAdditionalFileEntity add = new BookAdditionalFileEntity();
add.setId(100L);
add.setBook(b1);
add.setFileSubPath(".");
add.setFileName("extra.pdf");
b1.setAdditionalFiles(List.of(add));
doNothing().when(fileMovingHelper).moveAdditionalFiles(eq(b1), anyString());
UnifiedFileMoveService.BatchMoveCallback cb = mock(UnifiedFileMoveService.BatchMoveCallback.class);
service.moveBatchBookFiles(List.of(b1, b2), cb);
verify(monitoringRegistrationService).unregisterLibrary(eq(10L));
verify(fileMovingHelper).moveBookFileIfNeeded(eq(b1), anyString());
verify(fileMovingHelper).moveBookFileIfNeeded(eq(b2), anyString());
verify(cb).onBookMoved(eq(b1));
verify(cb, never()).onBookMoved(eq(b2));
verify(fileMovingHelper).moveAdditionalFiles(eq(b1), anyString());
verify(monitoringRegistrationService).registerLibraryPaths(eq(10L), any());
}
@Test
void moveBatchBookFiles_callsOnBookMoveFailed_onIOException() throws Exception {
BookEntity b = new BookEntity();
b.setId(21L);
b.setLibraryPath(libraryPath);
b.setFileSubPath(".");
b.setFileName("c.pdf");
BookMetadataEntity m = new BookMetadataEntity();
m.setTitle("C");
b.setMetadata(m);
m.setBook(b);
Path p = tmp.resolve("c.pdf");
Files.writeString(p, "c");
when(fileMovingHelper.getFileNamingPattern(library)).thenReturn("{currentFilename}");
when(fileMovingHelper.hasRequiredPathComponents(eq(b))).thenReturn(true);
when(fileMovingHelper.moveBookFileIfNeeded(eq(b), anyString())).thenThrow(new IOException("disk"));
UnifiedFileMoveService.BatchMoveCallback cb = mock(UnifiedFileMoveService.BatchMoveCallback.class);
service.moveBatchBookFiles(List.of(b), cb);
verify(cb).onBookMoveFailed(eq(b), any(IOException.class));
verify(monitoringRegistrationService).unregisterLibrary(eq(10L));
verify(monitoringRegistrationService).registerLibraryPaths(eq(10L), any());
}
}
@@ -0,0 +1,140 @@
package com.adityachandel.booklore.service.monitoring;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
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.*;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class MonitoringRegistrationServiceTest {
@Mock
MonitoringService monitoringService;
@InjectMocks
MonitoringRegistrationService registrationService;
@TempDir
Path tmp;
Path root;
Path sub1;
Path sub2;
@BeforeEach
void setupFs() throws IOException {
root = tmp.resolve("libroot");
sub1 = root.resolve("a");
sub2 = root.resolve("a").resolve("b");
Files.createDirectories(sub2);
}
@Test
void isPathMonitored_delegatesToMonitoringService() {
when(monitoringService.isPathMonitored(root)).thenReturn(true);
assertTrue(registrationService.isPathMonitored(root));
verify(monitoringService).isPathMonitored(root);
}
@Test
void unregisterSpecificPath_delegates() {
registrationService.unregisterSpecificPath(root);
verify(monitoringService).unregisterPath(root);
}
@Test
void registerSpecificPath_delegates() {
registrationService.registerSpecificPath(root, 123L);
verify(monitoringService).registerPath(root, 123L);
}
@Test
void unregisterLibrary_delegates() {
registrationService.unregisterLibrary(99L);
verify(monitoringService).unregisterLibrary(99L);
}
@Test
void registerLibraryPaths_noopWhenMissingOrNotDirectory() throws IOException {
Path missing = tmp.resolve("does-not-exist");
registrationService.registerLibraryPaths(7L, missing);
verifyNoInteractions(monitoringService);
Path file = tmp.resolve("afile.txt");
Files.writeString(file, "x");
registrationService.registerLibraryPaths(7L, file);
verifyNoInteractions(monitoringService);
}
@Test
void registerLibraryPaths_registersRootAndAllSubdirs() {
registrationService.registerLibraryPaths(42L, root);
verify(monitoringService).registerPath(root, 42L);
// subdirs a and a/b should be registered as well
verify(monitoringService).registerPath(sub1, 42L);
verify(monitoringService).registerPath(sub2, 42L);
ArgumentCaptor<Path> capt = ArgumentCaptor.forClass(Path.class);
verify(monitoringService, atLeast(3)).registerPath(capt.capture(), eq(42L));
List<Path> registered = capt.getAllValues();
assertTrue(registered.contains(root));
assertTrue(registered.contains(sub1));
assertTrue(registered.contains(sub2));
}
@Test
void registerLibraryPaths_handlesMonitoringServiceExceptionGracefully() {
doThrow(new RuntimeException("boom")).when(monitoringService).registerPath(eq(root), eq(55L));
assertDoesNotThrow(() -> registrationService.registerLibraryPaths(55L, root));
verify(monitoringService).registerPath(root, 55L);
}
@Test
void registerLibraryPaths_partialFailureStops() {
doAnswer(invocation -> {
Path p = invocation.getArgument(0);
Long id = invocation.getArgument(1);
if (id != null && id.equals(42L) && p.getFileName() != null && "a".equals(p.getFileName().toString())) {
throw new RuntimeException("fail-sub1");
}
return null;
}).when(monitoringService).registerPath(any(Path.class), anyLong());
registrationService.registerLibraryPaths(42L, root);
verify(monitoringService).registerPath(root, 42L);
verify(monitoringService).registerPath(argThat(p -> p.getFileName() != null && "a".equals(p.getFileName().toString())), eq(42L));
verify(monitoringService, never()).registerPath(argThat(p -> p.getFileName() != null && "b".equals(p.getFileName().toString())), eq(42L));
}
@Test
void registerLibraryPaths_onlyRegistersDirectories() throws IOException {
Path fileInRoot = root.resolve("file.txt");
Files.createDirectories(root);
Files.writeString(fileInRoot, "content");
registrationService.registerLibraryPaths(100L, root);
verify(monitoringService).registerPath(root, 100L);
verify(monitoringService).registerPath(sub1, 100L);
verify(monitoringService).registerPath(sub2, 100L);
verify(monitoringService, never()).registerPath(eq(fileInRoot), anyLong());
}
}
@@ -0,0 +1,288 @@
package com.adityachandel.booklore.service.monitoring;
import com.adityachandel.booklore.model.dto.Library;
import com.adityachandel.booklore.model.dto.LibraryPath;
import com.adityachandel.booklore.service.watcher.LibraryFileEventProcessor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mockito;
import java.lang.reflect.Field;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class MonitoringServiceTest {
@TempDir
Path tmp;
MonitoringService service;
LibraryFileEventProcessor processor;
MonitoringTask monitoringTask;
WatchService watchService;
@BeforeEach
void setup() throws Exception {
processor = mock(LibraryFileEventProcessor.class);
monitoringTask = mock(MonitoringTask.class);
watchService = FileSystems.getDefault().newWatchService();
service = Mockito.spy(new MonitoringService(processor, watchService, monitoringTask));
}
@AfterEach
void teardown() throws Exception {
try {
service.stopMonitoring();
} catch (Exception ignored) {}
try { watchService.close(); } catch (Exception ignored) {}
}
@Test
void registerLibrary_registersAllDirectoriesUnderLibraryPath() throws Exception {
Path root = tmp.resolve("libroot");
Path a = root.resolve("a");
Path b = a.resolve("b");
Files.createDirectories(b);
Library lib = mock(Library.class);
LibraryPath lp = mock(LibraryPath.class);
when(lp.getPath()).thenReturn(root.toString());
when(lib.getPaths()).thenReturn(List.of(lp));
when(lib.getId()).thenReturn(7L);
when(lib.getName()).thenReturn("my-lib");
when(lib.isWatch()).thenReturn(true);
doReturn(true).when(service).registerPath(any(Path.class), eq(7L));
service.registerLibrary(lib);
Files.walk(root).filter(Files::isDirectory).forEach(path ->
verify(service).registerPath(eq(path), eq(7L))
);
}
@Test
void unregisterLibrary_removesRegisteredPathsAndUpdatesMaps() throws Exception {
Path root = tmp.resolve("libroot2");
Files.createDirectories(root);
Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap");
pathToLibraryField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,Long> map = (Map<Path,Long>) pathToLibraryField.get(service);
map.put(root, 99L);
Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths");
monitoredPathsField.setAccessible(true);
@SuppressWarnings("unchecked")
Set<Path> monitored = (Set<Path>) monitoredPathsField.get(service);
monitored.add(root);
Field registeredKeysField = MonitoringService.class.getDeclaredField("registeredWatchKeys");
registeredKeysField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,WatchKey> keys = (Map<Path,WatchKey>) registeredKeysField.get(service);
WatchKey mockKey = mock(WatchKey.class);
keys.put(root, mockKey);
service.unregisterLibrary(99L);
assertFalse(monitored.contains(root), "monitoredPaths should no longer contain root");
assertFalse(map.containsKey(root), "pathToLibraryIdMap should no longer contain root");
assertFalse(keys.containsKey(root), "registeredWatchKeys should no longer contain root");
verify(mockKey).cancel();
}
@Test
void handleFileChangeEvent_createDirectory_registersNestedPaths() throws Exception {
Path watched = tmp.resolve("watched");
Files.createDirectories(watched);
Path newDir = watched.resolve("newdir");
Files.createDirectories(newDir);
Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap");
pathToLibraryField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,Long> map = (Map<Path,Long>) pathToLibraryField.get(service);
map.put(watched, 5L);
doReturn(true).when(service).registerPath(any(Path.class), eq(5L));
FileChangeEvent ev = mock(FileChangeEvent.class);
when(ev.getFilePath()).thenReturn(newDir);
doReturn(StandardWatchEventKinds.ENTRY_CREATE).when(ev).getEventKind();
when(ev.getWatchedFolder()).thenReturn(watched);
service.handleFileChangeEvent(ev);
Files.walk(newDir).filter(Files::isDirectory).forEach(p -> verify(service).registerPath(eq(p), eq(5L)));
}
@Test
void backgroundProcessor_processesQueuedEvents_and_callsProcessor() throws Exception {
Path watched = tmp.resolve("wf");
Files.createDirectories(watched);
Path file = watched.resolve("book.pdf");
Files.writeString(file, "x");
Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap");
pathToLibraryField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,Long> map = (Map<Path,Long>) pathToLibraryField.get(service);
map.put(watched, 123L);
java.lang.reflect.Method startMethod = MonitoringService.class.getDeclaredMethod("startProcessingThread");
startMethod.setAccessible(true);
startMethod.invoke(service);
FileChangeEvent ev = mock(FileChangeEvent.class);
when(ev.getFilePath()).thenReturn(file);
doReturn(StandardWatchEventKinds.ENTRY_CREATE).when(ev).getEventKind();
when(ev.getWatchedFolder()).thenReturn(watched);
service.handleFileChangeEvent(ev);
verify(processor, timeout(2_000)).processFile(eq(StandardWatchEventKinds.ENTRY_CREATE), eq(123L), eq(watched.toString()), eq(file.toString()));
}
@Test
void handleWatchKeyInvalidation_removesInvalidPath_and_cancelsKey() throws Exception {
Path invalid = tmp.resolve("inv");
Files.createDirectories(invalid);
Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths");
monitoredPathsField.setAccessible(true);
@SuppressWarnings("unchecked")
Set<Path> monitored = (Set<Path>) monitoredPathsField.get(service);
monitored.add(invalid);
Field registeredKeysField = MonitoringService.class.getDeclaredField("registeredWatchKeys");
registeredKeysField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,WatchKey> keys = (Map<Path,WatchKey>) registeredKeysField.get(service);
WatchKey wk = mock(WatchKey.class);
keys.put(invalid, wk);
WatchKeyInvalidatedEvent ev = mock(WatchKeyInvalidatedEvent.class);
when(ev.getInvalidPath()).thenReturn(invalid);
service.handleWatchKeyInvalidation(ev);
assertFalse(monitored.contains(invalid));
assertFalse(keys.containsKey(invalid));
verify(wk).cancel();
}
@Test
void isRelevantBookFile_detectsBookExtensions() {
Path pdf = Paths.get("somebook.pdf");
Path txt = Paths.get("notes.txt");
assertTrue(service.isRelevantBookFile(pdf));
assertFalse(service.isRelevantBookFile(txt));
}
@Test
void handleFileChangeEvent_ignoresIrrelevantNonBookFile() throws Exception {
Path watched = tmp.resolve("watched-ignore");
Files.createDirectories(watched);
Path file = watched.resolve("notes.txt");
Files.writeString(file, "notes");
Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap");
pathToLibraryField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,Long> map = (Map<Path,Long>) pathToLibraryField.get(service);
map.put(watched, 11L);
java.lang.reflect.Method startMethod = MonitoringService.class.getDeclaredMethod("startProcessingThread");
startMethod.setAccessible(true);
startMethod.invoke(service);
FileChangeEvent ev = mock(FileChangeEvent.class);
when(ev.getFilePath()).thenReturn(file);
doReturn(StandardWatchEventKinds.ENTRY_CREATE).when(ev).getEventKind();
when(ev.getWatchedFolder()).thenReturn(watched);
service.handleFileChangeEvent(ev);
verify(processor, timeout(500).times(0)).processFile(any(), anyLong(), anyString(), anyString());
}
@Test
void handleFileChangeEvent_deleteDirectory_unregistersSubPaths() throws Exception {
Path watched = tmp.resolve("watched-del");
Path a = watched.resolve("a");
Path b = a.resolve("b");
Files.createDirectories(b);
Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths");
monitoredPathsField.setAccessible(true);
@SuppressWarnings("unchecked")
Set<Path> monitored = (Set<Path>) monitoredPathsField.get(service);
monitored.add(watched);
monitored.add(a);
monitored.add(b);
FileChangeEvent ev = mock(FileChangeEvent.class);
when(ev.getFilePath()).thenReturn(a);
doReturn(StandardWatchEventKinds.ENTRY_DELETE).when(ev).getEventKind();
when(ev.getWatchedFolder()).thenReturn(watched);
service.handleFileChangeEvent(ev);
assertFalse(monitored.contains(a));
assertFalse(monitored.contains(b));
assertTrue(monitored.contains(watched));
}
@Test
void isPathMonitored_handlesNonNormalizedPaths() throws Exception {
Path root = tmp.resolve("libroot-norm");
Path sub = root.resolve("subdir");
Files.createDirectories(sub);
Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths");
monitoredPathsField.setAccessible(true);
@SuppressWarnings("unchecked")
Set<Path> monitored = (Set<Path>) monitoredPathsField.get(service);
monitored.add(sub.toAbsolutePath().normalize());
Path nonNormalized = root.resolve("subdir/../subdir/.");
assertTrue(service.isPathMonitored(nonNormalized));
}
@Test
void registerPath_successful_updatesInternalMapsAndSets() throws Exception {
Path dir = tmp.resolve("regdir");
Files.createDirectories(dir);
boolean registered = service.registerPath(dir, 55L);
assertTrue(registered);
Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap");
pathToLibraryField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,Long> map = (Map<Path,Long>) pathToLibraryField.get(service);
assertEquals(55L, map.get(dir));
Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths");
monitoredPathsField.setAccessible(true);
@SuppressWarnings("unchecked")
Set<Path> monitored = (Set<Path>) monitoredPathsField.get(service);
assertTrue(monitored.contains(dir));
Field keysField = MonitoringService.class.getDeclaredField("registeredWatchKeys");
keysField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path, WatchKey> keys = (Map<Path, WatchKey>) keysField.get(service);
assertTrue(keys.containsKey(dir));
}
}
@@ -3,32 +3,29 @@ package com.adityachandel.booklore.service.upload;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.AdditionalFileMapperImpl;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.mapper.AdditionalFileMapper;
import com.adityachandel.booklore.model.dto.AdditionalFile;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
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.BookFileType;
import com.adityachandel.booklore.model.enums.FileProcessStatus;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.FileFingerprint;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.file.FileMovingHelper;
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@@ -39,7 +36,7 @@ import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
class FileUploadServiceTest {
@@ -54,17 +51,15 @@ class FileUploadServiceTest {
@Mock
BookAdditionalFileRepository bookAdditionalFileRepository;
@Mock
BookFileProcessorRegistry processorRegistry;
@Mock
NotificationService notificationService;
@Mock
AppSettingService appSettingService;
@Mock
PdfMetadataExtractor pdfMetadataExtractor;
@Mock
EpubMetadataExtractor epubMetadataExtractor;
@Mock
MonitoringService monitoringService;
FileMovingHelper fileMovingHelper;
@Mock
AdditionalFileMapper additionalFileMapper;
AppProperties appProperties;
FileUploadService service;
@@ -80,17 +75,11 @@ class FileUploadServiceTest {
settings.setUploadPattern("{currentFilename}");
when(appSettingService.getAppSettings()).thenReturn(settings);
var additionalFilesMapper = new AdditionalFileMapperImpl();
service = new FileUploadService(
libraryRepository, bookRepository, bookAdditionalFileRepository,
processorRegistry, notificationService,
appSettingService, appProperties, pdfMetadataExtractor,
epubMetadataExtractor, additionalFilesMapper, monitoringService
epubMetadataExtractor, additionalFileMapper, fileMovingHelper
);
ReflectionTestUtils.setField(service, "userId", "0");
ReflectionTestUtils.setField(service, "groupId", "0");
}
@Test
@@ -185,6 +174,7 @@ class FileUploadServiceTest {
path.setPath(tempDir.toString());
lib.setLibraryPaths(List.of(path));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(lib));
when(fileMovingHelper.getFileNamingPattern(lib)).thenReturn("{currentFilename}");
assertThatExceptionOfType(APIException.class)
.isThrownBy(() -> service.uploadFile(file, 1L, 1L))
@@ -206,22 +196,76 @@ class FileUploadServiceTest {
path.setPath(tempDir.toString());
lib.setLibraryPaths(List.of(path));
when(libraryRepository.findById(7L)).thenReturn(Optional.of(lib));
when(fileMovingHelper.getFileNamingPattern(lib)).thenReturn("{currentFilename}");
BookFileProcessor proc = mock(BookFileProcessor.class);
FileProcessResult fileProcessResult = FileProcessResult.builder()
.book(Book.builder().build())
.status(FileProcessStatus.NEW)
.build();
service.uploadFile(file, 7L, 2L);
when(processorRegistry.getProcessorOrThrow(BookFileType.CBX)).thenReturn(proc);
when(proc.processFile(any())).thenReturn(fileProcessResult);
Book result = service.uploadFile(file, 7L, 2L);
assertThat(result).isSameAs(fileProcessResult.getBook());
Path moved = tempDir.resolve("book.cbz");
assertThat(Files.exists(moved)).isTrue();
verify(notificationService).sendMessage(eq(Topic.BOOK_ADD), same(fileProcessResult.getBook()));
verifyNoInteractions(pdfMetadataExtractor, epubMetadataExtractor);
}
@Test
void uploadAdditionalFile_successful_and_saves_entity() throws Exception {
long bookId = 5L;
MockMultipartFile file = new MockMultipartFile("file", "add.pdf", "application/pdf", "payload".getBytes());
LibraryPathEntity libPath = new LibraryPathEntity();
libPath.setId(1L);
libPath.setPath(tempDir.toString());
BookEntity book = new BookEntity();
book.setId(bookId);
book.setLibraryPath(libPath);
book.setFileSubPath(".");
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
try (MockedStatic<FileFingerprint> fp = mockStatic(FileFingerprint.class)) {
fp.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash-123");
when(bookAdditionalFileRepository.findByAltFormatCurrentHash("hash-123")).thenReturn(Optional.empty());
when(bookAdditionalFileRepository.save(any(BookAdditionalFileEntity.class))).thenAnswer(inv -> {
BookAdditionalFileEntity e = inv.getArgument(0);
e.setId(99L);
return e;
});
AdditionalFile dto = mock(AdditionalFile.class);
when(additionalFileMapper.toAdditionalFile(any(BookAdditionalFileEntity.class))).thenReturn(dto);
AdditionalFile result = service.uploadAdditionalFile(bookId, file, AdditionalFileType.ALTERNATIVE_FORMAT, "desc");
assertThat(result).isEqualTo(dto);
verify(bookAdditionalFileRepository).save(any(BookAdditionalFileEntity.class));
verify(additionalFileMapper).toAdditionalFile(any(BookAdditionalFileEntity.class));
}
}
@Test
void uploadAdditionalFile_duplicate_alternative_format_throws() {
long bookId = 6L;
MockMultipartFile file = new MockMultipartFile("file", "alt.pdf", "application/pdf", "payload".getBytes());
LibraryPathEntity libPath = new LibraryPathEntity();
libPath.setId(2L);
libPath.setPath(tempDir.toString());
BookEntity book = new BookEntity();
book.setId(bookId);
book.setLibraryPath(libPath);
book.setFileSubPath(".");
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
try (MockedStatic<FileFingerprint> fp = mockStatic(FileFingerprint.class)) {
fp.when(() -> FileFingerprint.generateHash(any())).thenReturn("dup-hash");
BookAdditionalFileEntity existing = new BookAdditionalFileEntity();
existing.setId(1L);
when(bookAdditionalFileRepository.findByAltFormatCurrentHash("dup-hash")).thenReturn(Optional.of(existing));
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> service.uploadAdditionalFile(bookId, file, AdditionalFileType.ALTERNATIVE_FORMAT, null));
}
}
}