fix(bookdrop): Ensure source file is only deleted after successful import and cleanup target on failure (#1638)
* fix(bookdrop): improve error handling and cleanup for file move failures - Ensure target file is deleted if processing or metadata refresh fails after move - Only delete source file on successful processing - Add tests to verify file cleanup and source preservation on failure scenarios - Use lenient mocking for Files in tests to support error simulation * fix(bookdrop): enhance file and cover cleanup logic, improve test coverage for import finalization * test(bookdrop): improve finalize import test with LibraryPathRepository mock and enhanced stubbing
This commit is contained in:
+203
-7
@@ -15,6 +15,7 @@ import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.BookdropFileRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryPathRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.file.FileMovingHelper;
|
||||
@@ -23,6 +24,7 @@ import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistr
|
||||
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -32,6 +34,8 @@ 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 org.springframework.core.io.Resource;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
@@ -41,6 +45,7 @@ import org.springframework.data.domain.Pageable;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -49,6 +54,7 @@ import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class BookDropServiceTest {
|
||||
|
||||
@Mock
|
||||
@@ -58,6 +64,8 @@ class BookDropServiceTest {
|
||||
@Mock
|
||||
private LibraryRepository libraryRepository;
|
||||
@Mock
|
||||
private LibraryPathRepository libraryPathRepository;
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
@Mock
|
||||
private BookdropMonitoringService bookdropMonitoringService;
|
||||
@@ -114,6 +122,24 @@ class BookDropServiceTest {
|
||||
Files.createFile(tempDir.resolve("test-book.pdf"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws IOException {
|
||||
if (Files.exists(tempDir)) {
|
||||
try (var stream = Files.walk(tempDir)) {
|
||||
stream.sorted(Comparator.reverseOrder()) // reverse order for directories
|
||||
.forEach(path -> {
|
||||
try {
|
||||
if (!path.equals(tempDir)) { // Don't delete the tempDir itself
|
||||
Files.deleteIfExists(path);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Ignore cleanup failures in tearDown
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getFileNotificationSummary_ShouldReturnCorrectCounts() {
|
||||
when(bookdropFileRepository.countByStatus(BookdropFileEntity.Status.PENDING_REVIEW)).thenReturn(5L);
|
||||
@@ -236,7 +262,7 @@ class BookDropServiceTest {
|
||||
bookEntity.setId(1L);
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
|
||||
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
|
||||
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);
|
||||
@@ -267,7 +293,7 @@ class BookDropServiceTest {
|
||||
BookMetadata metadata = new BookMetadata();
|
||||
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
|
||||
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
|
||||
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
|
||||
|
||||
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
|
||||
@@ -292,7 +318,7 @@ class BookDropServiceTest {
|
||||
when(appProperties.getBookdropFolder()).thenReturn(tempDir.toString());
|
||||
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
|
||||
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
|
||||
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);
|
||||
@@ -317,7 +343,7 @@ class BookDropServiceTest {
|
||||
when(appProperties.getBookdropFolder()).thenReturn(tempDir.toString());
|
||||
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
|
||||
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
|
||||
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);
|
||||
@@ -337,7 +363,7 @@ class BookDropServiceTest {
|
||||
void discardSelectedFiles_WhenBookdropFolderDoesNotExist_ShouldHandleGracefully() {
|
||||
when(appProperties.getBookdropFolder()).thenReturn("/non-existent-path");
|
||||
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
|
||||
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(false);
|
||||
|
||||
bookDropService.discardSelectedFiles(true, null, null);
|
||||
@@ -372,7 +398,7 @@ class BookDropServiceTest {
|
||||
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
|
||||
.thenReturn(tempDir.resolve("target-file.pdf"));
|
||||
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
|
||||
filesMock.when(() -> Files.exists(Path.of("/non-existent/missing-file.pdf"))).thenReturn(false);
|
||||
|
||||
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
|
||||
@@ -403,7 +429,7 @@ class BookDropServiceTest {
|
||||
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
|
||||
.thenReturn(tempDir.resolve("target-file.pdf"));
|
||||
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
|
||||
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
|
||||
filesMock.when(() -> Files.createTempFile(anyString(), anyString()))
|
||||
.thenThrow(new IOException("Disk full"));
|
||||
@@ -416,4 +442,174 @@ class BookDropServiceTest {
|
||||
assertEquals(1, result.getFailed());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void finalizeImport_WhenProcessingSucceeds_ShouldDeleteSourceFileFromBookdrop() throws Exception {
|
||||
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
|
||||
request.setSelectAll(true);
|
||||
request.setDefaultLibraryId(1L);
|
||||
request.setDefaultPathId(1L);
|
||||
request.setExcludedIds(List.of());
|
||||
|
||||
when(bookdropFileRepository.findAllExcludingIdsFlat(any())).thenReturn(List.of(1L));
|
||||
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
|
||||
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity));
|
||||
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/books");
|
||||
when(libraryPathRepository.findById(1L)).thenReturn(Optional.of(pathEntity));
|
||||
|
||||
lenient().when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(new BookMetadata());
|
||||
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));
|
||||
|
||||
when(bookRepository.save(any())).thenAnswer(i -> i.getArguments()[0]);
|
||||
|
||||
doNothing().when(bookdropFileRepository).deleteById(any());
|
||||
doNothing().when(bookdropNotificationService).sendBookdropFileSummaryNotification();
|
||||
doNothing().when(notificationService).sendMessage(any(), any());
|
||||
lenient().doNothing().when(metadataRefreshService).updateBookMetadata(any());
|
||||
|
||||
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
|
||||
|
||||
Path sourcePath = Path.of(bookdropFileEntity.getFilePath());
|
||||
Path tempPath = tempDir.resolve("temp-file");
|
||||
Path targetPath = tempDir.resolve("moved-book.pdf");
|
||||
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
|
||||
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
|
||||
filesMock.when(() -> Files.createTempFile(anyString(), anyString())).thenReturn(tempPath);
|
||||
filesMock.when(() -> Files.copy(any(Path.class), any(Path.class), any())).thenReturn(tempPath);
|
||||
filesMock.when(() -> Files.createDirectories(any(Path.class))).thenReturn(tempDir);
|
||||
filesMock.when(() -> Files.move(any(Path.class), any(Path.class), any())).thenReturn(targetPath);
|
||||
|
||||
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getTotalFiles());
|
||||
assertEquals(1, result.getSuccessfullyImported());
|
||||
assertEquals(0, result.getFailed());
|
||||
|
||||
filesMock.verify(() -> Files.delete(sourcePath), times(1));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void finalizeImport_WhenProcessingFails_ShouldPreserveSourceFileInBookdrop() throws Exception {
|
||||
BookdropFinalizeRequest.BookdropFinalizeFile finalizeFile = new BookdropFinalizeRequest.BookdropFinalizeFile();
|
||||
finalizeFile.setFileId(1L);
|
||||
finalizeFile.setLibraryId(1L);
|
||||
finalizeFile.setPathId(1L);
|
||||
finalizeFile.setMetadata(new BookMetadata());
|
||||
|
||||
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
|
||||
request.setSelectAll(false);
|
||||
request.setFiles(List.of(finalizeFile));
|
||||
|
||||
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
|
||||
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity));
|
||||
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(new BookMetadata());
|
||||
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);
|
||||
|
||||
when(processor.processFile(any())).thenThrow(new RuntimeException("Processing failed"));
|
||||
|
||||
Path sourcePath = Path.of(bookdropFileEntity.getFilePath());
|
||||
Path tempPath = tempDir.resolve("temp-file");
|
||||
Path targetPath = tempDir.resolve("moved-book.pdf");
|
||||
|
||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
|
||||
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
|
||||
filesMock.when(() -> Files.createTempFile(anyString(), anyString())).thenReturn(tempPath);
|
||||
filesMock.when(() -> Files.copy(any(Path.class), any(Path.class), any())).thenReturn(tempPath);
|
||||
filesMock.when(() -> Files.createDirectories(any(Path.class))).thenReturn(tempDir);
|
||||
filesMock.when(() -> Files.move(any(Path.class), any(Path.class), any())).thenReturn(targetPath);
|
||||
|
||||
filesMock.when(() -> Files.deleteIfExists(targetPath)).thenReturn(true);
|
||||
|
||||
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getTotalFiles());
|
||||
assertEquals(0, result.getSuccessfullyImported());
|
||||
assertEquals(1, result.getFailed());
|
||||
|
||||
filesMock.verify(() -> Files.delete(sourcePath), never());
|
||||
filesMock.verify(() -> Files.deleteIfExists(targetPath), times(1));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void finalizeImport_WhenMetadataRefreshFails_ShouldPreserveSourceFileInBookdrop() throws Exception {
|
||||
Path sourceFile = tempDir.resolve("metadata-failure-test-book.pdf");
|
||||
Files.createFile(sourceFile);
|
||||
assertTrue(Files.exists(sourceFile), "Source file should exist");
|
||||
bookdropFileEntity.setFilePath(sourceFile.toString());
|
||||
|
||||
Path targetDir = tempDir.resolve("library");
|
||||
Files.createDirectories(targetDir);
|
||||
|
||||
BookdropFinalizeRequest.BookdropFinalizeFile finalizeFile = new BookdropFinalizeRequest.BookdropFinalizeFile();
|
||||
finalizeFile.setFileId(1L);
|
||||
finalizeFile.setLibraryId(1L);
|
||||
finalizeFile.setPathId(1L);
|
||||
finalizeFile.setMetadata(new BookMetadata());
|
||||
|
||||
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
|
||||
request.setSelectAll(false);
|
||||
request.setFiles(List.of(finalizeFile));
|
||||
|
||||
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
|
||||
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity));
|
||||
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(new BookMetadata());
|
||||
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
|
||||
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
|
||||
.thenReturn(targetDir.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));
|
||||
|
||||
doNothing().when(bookdropFileRepository).deleteById(any());
|
||||
doNothing().when(bookdropNotificationService).sendBookdropFileSummaryNotification();
|
||||
doNothing().when(notificationService).sendMessage(any(), any());
|
||||
|
||||
doThrow(new RuntimeException("Metadata refresh failed")).when(metadataRefreshService).updateBookMetadata(any());
|
||||
|
||||
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
|
||||
|
||||
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getTotalFiles());
|
||||
assertEquals(0, result.getSuccessfullyImported());
|
||||
assertEquals(1, result.getFailed());
|
||||
|
||||
assertTrue(Files.exists(sourceFile), "Source file should be preserved on failure");
|
||||
assertFalse(Files.exists(targetDir.resolve("moved-book.pdf")), "Target file should be cleaned up on failure");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user