From 8f811bb82de6d10b17f46b2f8204c40bb0ffd421 Mon Sep 17 00:00:00 2001 From: "aditya.chandel" <8075870+adityachandelgit@users.noreply.github.com> Date: Fri, 21 Nov 2025 00:42:02 -0700 Subject: [PATCH] Fixes are PR merges --- .../service/kobo/KoboReadingStateService.java | 2 +- .../booklore/util/FileUtils.java | 20 +-- .../booklore/util/MetadataChangeDetector.java | 9 -- .../service/KoboReadingStateServiceTest.java | 71 ++++------ .../booklore/util/FileUtilsTest.java | 134 +++++++++++++----- 5 files changed, 130 insertions(+), 106 deletions(-) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboReadingStateService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboReadingStateService.java index 36447732c..43cc43187 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboReadingStateService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboReadingStateService.java @@ -192,4 +192,4 @@ public class KoboReadingStateService { userProgress.setReadStatus(ReadStatus.UNREAD); } } -} \ No newline at end of file +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java index eeea91dd7..b5db45f90 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java @@ -27,21 +27,11 @@ public class FileUtils { } public static String getRelativeSubPath(String basePath, Path fullFilePath) { - try { - // Add .normalize() to both paths for robust comparison - Path normalizedBasePath = Path.of(basePath).normalize(); - Path normalizedFullPath = fullFilePath.normalize(); - - return Optional.ofNullable(normalizedBasePath - .relativize(normalizedFullPath) - .getParent()) - .map(path -> path.toString().replace("\\", "/")) - .orElse(""); - } catch (Exception e) { - log.error("Failed to get relative sub-path for basePath '{}' and fullFilePath '{}': {}", - basePath, fullFilePath, e.getMessage(), e); - return ""; // Fallback to empty string on any error - } + return Optional.ofNullable(Path.of(basePath) + .relativize(fullFilePath) + .getParent()) + .map(path -> path.toString().replace("\\", "/")) + .orElse(""); } public static Long getFileSizeInKb(BookEntity bookEntity) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/MetadataChangeDetector.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/MetadataChangeDetector.java index bdfdbddda..b07ce9cad 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/MetadataChangeDetector.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/MetadataChangeDetector.java @@ -112,19 +112,10 @@ public class MetadataChangeDetector { compareValue(diffs, "comicvineId", clear.isComicvineId(), newMeta.getComicvineId(), existingMeta.getComicvineId(), () -> !isTrue(existingMeta.getComicvineIdLocked())); compareValue(diffs, "hardcoverId", clear.isHardcoverId(), newMeta.getHardcoverId(), existingMeta.getHardcoverId(), () -> !isTrue(existingMeta.getHardcoverIdLocked())); compareValue(diffs, "googleId", clear.isGoogleId(), newMeta.getGoogleId(), existingMeta.getGoogleId(), () -> !isTrue(existingMeta.getGoogleIdLocked())); - compareValue(diffs, "pageCount", clear.isPageCount(), newMeta.getPageCount(), existingMeta.getPageCount(), () -> !isTrue(existingMeta.getPageCountLocked())); compareValue(diffs, "language", clear.isLanguage(), newMeta.getLanguage(), existingMeta.getLanguage(), () -> !isTrue(existingMeta.getLanguageLocked())); compareValue(diffs, "personalRating", clear.isPersonalRating(), newMeta.getPersonalRating(), existingMeta.getPersonalRating(), () -> !isTrue(existingMeta.getPersonalRatingLocked())); - compareValue(diffs, "amazonRating", clear.isAmazonRating(), newMeta.getAmazonRating(), existingMeta.getAmazonRating(), () -> !isTrue(existingMeta.getAmazonRatingLocked())); - compareValue(diffs, "amazonReviewCount", clear.isAmazonReviewCount(), newMeta.getAmazonReviewCount(), existingMeta.getAmazonReviewCount(), () -> !isTrue(existingMeta.getAmazonReviewCountLocked())); - compareValue(diffs, "goodreadsRating", clear.isGoodreadsRating(), newMeta.getGoodreadsRating(), existingMeta.getGoodreadsRating(), () -> !isTrue(existingMeta.getGoodreadsRatingLocked())); - compareValue(diffs, "goodreadsReviewCount", clear.isGoodreadsReviewCount(), newMeta.getGoodreadsReviewCount(), existingMeta.getGoodreadsReviewCount(), () -> !isTrue(existingMeta.getGoodreadsReviewCountLocked())); - compareValue(diffs, "hardcoverRating", clear.isHardcoverRating(), newMeta.getHardcoverRating(), existingMeta.getHardcoverRating(), () -> !isTrue(existingMeta.getHardcoverRatingLocked())); - compareValue(diffs, "hardcoverReviewCount", clear.isHardcoverReviewCount(), newMeta.getHardcoverReviewCount(), existingMeta.getHardcoverReviewCount(), () -> !isTrue(existingMeta.getHardcoverReviewCountLocked())); compareValue(diffs, "authors", clear.isAuthors(), newMeta.getAuthors(), toNameSet(existingMeta.getAuthors()), () -> !isTrue(existingMeta.getAuthorsLocked())); compareValue(diffs, "categories", clear.isCategories(), newMeta.getCategories(), toNameSet(existingMeta.getCategories()), () -> !isTrue(existingMeta.getCategoriesLocked())); - compareValue(diffs, "moods", clear.isMoods(), newMeta.getMoods(), toNameSet(existingMeta.getMoods()), () -> !isTrue(existingMeta.getMoodsLocked())); - compareValue(diffs, "tags", clear.isTags(), newMeta.getTags(), toNameSet(existingMeta.getTags()), () -> !isTrue(existingMeta.getTagsLocked())); return !diffs.isEmpty(); } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/KoboReadingStateServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/KoboReadingStateServiceTest.java index 4869df760..206efdab0 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/KoboReadingStateServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/KoboReadingStateServiceTest.java @@ -1,9 +1,5 @@ package com.adityachandel.booklore.service; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; -import static org.mockito.ArgumentMatchers.*; - import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.mapper.KoboReadingStateMapper; import com.adityachandel.booklore.model.dto.BookLoreUser; @@ -20,11 +16,16 @@ import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.KoboReadingStateRepository; import com.adityachandel.booklore.repository.UserBookProgressRepository; import com.adityachandel.booklore.repository.UserRepository; +import com.adityachandel.booklore.service.kobo.KoboReadingStateBuilder; import com.adityachandel.booklore.service.kobo.KoboReadingStateService; import com.adityachandel.booklore.service.kobo.KoboSettingsService; -import org.junit.jupiter.api.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.*; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; @@ -33,6 +34,9 @@ import java.time.Instant; import java.util.List; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) class KoboReadingStateServiceTest { @@ -58,6 +62,9 @@ class KoboReadingStateServiceTest { @Mock private KoboSettingsService koboSettingsService; + @Mock + private KoboReadingStateBuilder readingStateBuilder; + @InjectMocks private KoboReadingStateService service; @@ -91,7 +98,6 @@ class KoboReadingStateServiceTest { @Test @DisplayName("Should sync Kobo progress to UserBookProgress with valid data") void testSyncKoboProgressToUserBookProgress_Success() { - // Arrange String entitlementId = "100"; KoboReadingState.CurrentBookmark.Location location = KoboReadingState.CurrentBookmark.Location.builder() .value("epubcfi(/6/4[chap01ref]!/4/2/1:3)") @@ -121,10 +127,8 @@ class KoboReadingStateServiceTest { ArgumentCaptor progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class); when(progressRepository.save(progressCaptor.capture())).thenReturn(new UserBookProgressEntity()); - // Act KoboReadingStateResponse response = service.saveReadingState(List.of(readingState)); - // Assert assertNotNull(response); assertEquals("Success", response.getRequestResult()); assertEquals(1, response.getUpdateResults().size()); @@ -143,7 +147,6 @@ class KoboReadingStateServiceTest { @Test @DisplayName("Should update existing progress when syncing Kobo data") void testSyncKoboProgressToUserBookProgress_UpdateExisting() { - // Arrange String entitlementId = "100"; UserBookProgressEntity existingProgress = new UserBookProgressEntity(); existingProgress.setUser(testUserEntity); @@ -171,10 +174,8 @@ class KoboReadingStateServiceTest { ArgumentCaptor progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class); when(progressRepository.save(progressCaptor.capture())).thenReturn(existingProgress); - // Act service.saveReadingState(List.of(readingState)); - // Assert UserBookProgressEntity savedProgress = progressCaptor.getValue(); assertEquals(50.0f, savedProgress.getKoboProgressPercent()); assertEquals(ReadStatus.READING, savedProgress.getReadStatus()); @@ -183,7 +184,6 @@ class KoboReadingStateServiceTest { @Test @DisplayName("Should mark book as READ when progress reaches finished threshold") void testSyncKoboProgressToUserBookProgress_MarkAsRead() { - // Arrange String entitlementId = "100"; testSettings.setProgressMarkAsFinishedThreshold(99f); @@ -208,10 +208,8 @@ class KoboReadingStateServiceTest { ArgumentCaptor progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class); when(progressRepository.save(progressCaptor.capture())).thenReturn(new UserBookProgressEntity()); - // Act service.saveReadingState(List.of(readingState)); - // Assert UserBookProgressEntity savedProgress = progressCaptor.getValue(); assertEquals(100.0f, savedProgress.getKoboProgressPercent()); assertEquals(ReadStatus.READ, savedProgress.getReadStatus()); @@ -221,7 +219,6 @@ class KoboReadingStateServiceTest { @Test @DisplayName("Should mark book as READING when progress exceeds reading threshold") void testSyncKoboProgressToUserBookProgress_MarkAsReading() { - // Arrange String entitlementId = "100"; testSettings.setProgressMarkAsReadingThreshold(1f); @@ -246,10 +243,8 @@ class KoboReadingStateServiceTest { ArgumentCaptor progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class); when(progressRepository.save(progressCaptor.capture())).thenReturn(new UserBookProgressEntity()); - // Act service.saveReadingState(List.of(readingState)); - // Assert UserBookProgressEntity savedProgress = progressCaptor.getValue(); assertEquals(1.0f, savedProgress.getKoboProgressPercent()); assertEquals(ReadStatus.READING, savedProgress.getReadStatus()); @@ -259,7 +254,6 @@ class KoboReadingStateServiceTest { @Test @DisplayName("Should use custom thresholds from settings") void testSyncKoboProgressToUserBookProgress_CustomThresholds() { - // Arrange String entitlementId = "100"; testSettings.setProgressMarkAsReadingThreshold(5.0f); testSettings.setProgressMarkAsFinishedThreshold(95.0f); @@ -285,10 +279,8 @@ class KoboReadingStateServiceTest { ArgumentCaptor progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class); when(progressRepository.save(progressCaptor.capture())).thenReturn(new UserBookProgressEntity()); - // Act service.saveReadingState(List.of(readingState)); - // Assert UserBookProgressEntity savedProgress = progressCaptor.getValue(); assertEquals(ReadStatus.READ, savedProgress.getReadStatus()); } @@ -296,7 +288,6 @@ class KoboReadingStateServiceTest { @Test @DisplayName("Should handle invalid entitlement ID gracefully") void testSyncKoboProgressToUserBookProgress_InvalidEntitlementId() { - // Arrange String entitlementId = "not-a-number"; KoboReadingState readingState = KoboReadingState.builder() .entitlementId(entitlementId) @@ -309,7 +300,6 @@ class KoboReadingStateServiceTest { when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty()); when(repository.save(any())).thenReturn(entity); - // Act & Assert - should not throw exception assertDoesNotThrow(() -> service.saveReadingState(List.of(readingState))); verify(progressRepository, never()).save(any()); } @@ -317,7 +307,6 @@ class KoboReadingStateServiceTest { @Test @DisplayName("Should handle missing book gracefully") void testSyncKoboProgressToUserBookProgress_BookNotFound() { - // Arrange String entitlementId = "999"; KoboReadingState readingState = KoboReadingState.builder() .entitlementId(entitlementId) @@ -333,7 +322,6 @@ class KoboReadingStateServiceTest { when(repository.save(any())).thenReturn(entity); when(bookRepository.findById(999L)).thenReturn(Optional.empty()); - // Act & Assert - should not throw exception assertDoesNotThrow(() -> service.saveReadingState(List.of(readingState))); verify(progressRepository, never()).save(any()); } @@ -341,7 +329,6 @@ class KoboReadingStateServiceTest { @Test @DisplayName("Should construct reading state from UserBookProgress when no Kobo state exists") void testGetReadingState_ConstructFromProgress() { - // Arrange String entitlementId = "100"; UserBookProgressEntity progress = new UserBookProgressEntity(); progress.setKoboProgressPercent(75.5f); @@ -350,14 +337,25 @@ class KoboReadingStateServiceTest { progress.setKoboLocationSource("Kobo"); progress.setKoboLastSyncTime(Instant.now()); + KoboReadingState expectedState = KoboReadingState.builder() + .entitlementId(entitlementId) + .currentBookmark(KoboReadingState.CurrentBookmark.builder() + .progressPercent(75) + .location(KoboReadingState.CurrentBookmark.Location.builder() + .value("epubcfi(/6/4[chap01ref]!/4/2/1:3)") + .type("EpubCfi") + .source("Kobo") + .build()) + .build()) + .build(); + when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty()); when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress)); + when(readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress)).thenReturn(expectedState); - // Act KoboReadingStateWrapper result = service.getReadingState(entitlementId); - // Assert assertNotNull(result); assertNotNull(result.getReadingStates()); assertEquals(1, result.getReadingStates().size()); @@ -373,15 +371,14 @@ class KoboReadingStateServiceTest { verify(repository).findByEntitlementId(entitlementId); verify(progressRepository).findByUserIdAndBookId(1L, 100L); + verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress); } @Test @DisplayName("Should return null when no Kobo reading state exists and UserBookProgress has no Kobo data") void testGetReadingState_NoKoboDataInProgress() { - // Arrange String entitlementId = "100"; UserBookProgressEntity progress = new UserBookProgressEntity(); - // Progress exists but has no Kobo-specific data progress.setKoboProgressPercent(null); progress.setKoboLocation(null); @@ -389,10 +386,8 @@ class KoboReadingStateServiceTest { when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress)); - // Act KoboReadingStateWrapper result = service.getReadingState(entitlementId); - // Assert assertNull(result); verify(repository).findByEntitlementId(entitlementId); verify(progressRepository).findByUserIdAndBookId(1L, 100L); @@ -401,16 +396,13 @@ class KoboReadingStateServiceTest { @Test @DisplayName("Should return null when no Kobo state and no UserBookProgress exists") void testGetReadingState_NoDataExists() { - // Arrange String entitlementId = "100"; when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty()); when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.empty()); - // Act KoboReadingStateWrapper result = service.getReadingState(entitlementId); - // Assert assertNull(result); verify(progressRepository).findByUserIdAndBookId(1L, 100L); } @@ -418,7 +410,6 @@ class KoboReadingStateServiceTest { @Test @DisplayName("Should return existing Kobo reading state when it exists") void testGetReadingState_ExistingState() { - // Arrange String entitlementId = "100"; KoboReadingState existingState = KoboReadingState.builder() .entitlementId(entitlementId) @@ -428,10 +419,8 @@ class KoboReadingStateServiceTest { when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.of(entity)); when(mapper.toDto(entity)).thenReturn(existingState); - // Act KoboReadingStateWrapper result = service.getReadingState(entitlementId); - // Assert assertNotNull(result); assertEquals(1, result.getReadingStates().size()); assertEquals(entitlementId, result.getReadingStates().get(0).getEntitlementId()); @@ -441,7 +430,6 @@ class KoboReadingStateServiceTest { @Test @DisplayName("Should handle null bookmark gracefully") void testSyncKoboProgressToUserBookProgress_NullBookmark() { - // Arrange String entitlementId = "100"; KoboReadingState readingState = KoboReadingState.builder() .entitlementId(entitlementId) @@ -460,10 +448,8 @@ class KoboReadingStateServiceTest { ArgumentCaptor progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class); when(progressRepository.save(progressCaptor.capture())).thenReturn(new UserBookProgressEntity()); - // Act assertDoesNotThrow(() -> service.saveReadingState(List.of(readingState))); - // Assert UserBookProgressEntity savedProgress = progressCaptor.getValue(); assertNull(savedProgress.getKoboProgressPercent()); assertNotNull(savedProgress.getKoboLastSyncTime()); @@ -472,7 +458,6 @@ class KoboReadingStateServiceTest { @Test @DisplayName("Should handle null progress percent in bookmark") void testSyncKoboProgressToUserBookProgress_NullProgressPercent() { - // Arrange String entitlementId = "100"; KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder() .progressPercent(null) @@ -495,10 +480,8 @@ class KoboReadingStateServiceTest { ArgumentCaptor progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class); when(progressRepository.save(progressCaptor.capture())).thenReturn(new UserBookProgressEntity()); - // Act assertDoesNotThrow(() -> service.saveReadingState(List.of(readingState))); - // Assert UserBookProgressEntity savedProgress = progressCaptor.getValue(); assertNull(savedProgress.getKoboProgressPercent()); } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileUtilsTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileUtilsTest.java index 7b3d9771a..b4ca57e8a 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileUtilsTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileUtilsTest.java @@ -1,61 +1,121 @@ -// package test.java.com.adityachandel.booklore.util; -// import com.adityachandel.booklore.util.FileUtils; - package com.adityachandel.booklore.util; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; -import static org.assertj.core.api.Assertions.assertThat; + +import static org.junit.jupiter.api.Assertions.*; class FileUtilsTest { - @Test - void getRelativeSubPath_shouldHandleStandardCase() { - String basePath = "C:\\Library\\Books"; - Path fullFilePath = Path.of("C:\\Library\\Books\\Series A\\book.epub"); - String result = FileUtils.getRelativeSubPath(basePath, fullFilePath); - assertThat(result).isEqualTo("Series A"); + @TempDir + Path tempDir; + + private BookEntity createBookEntity(Path libraryPath, String subPath, String fileName) { + LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); + libraryPathEntity.setPath(libraryPath.toString()); + + BookEntity bookEntity = new BookEntity(); + bookEntity.setLibraryPath(libraryPathEntity); + bookEntity.setFileSubPath(subPath); + bookEntity.setFileName(fileName); + + return bookEntity; } @Test - void getRelativeSubPath_shouldHandleNestedFolders() { - String basePath = "C:\\Library\\Books"; - Path fullFilePath = Path.of("C:\\Library\\Books\\Series A\\Subfolder 1\\book.epub"); - String result = FileUtils.getRelativeSubPath(basePath, fullFilePath); - assertThat(result).isEqualTo("Series A/Subfolder 1"); + void testGetBookFullPath() { + Path libraryPath = tempDir; + String subPath = "sub/folder"; + String fileName = "test.pdf"; + + BookEntity book = createBookEntity(libraryPath, subPath, fileName); + + String fullPath = FileUtils.getBookFullPath(book); + + String expected = libraryPath.resolve(subPath).resolve(fileName) + .toString().replace("\\", "/"); + + assertEquals(expected, fullPath); } @Test - void getRelativeSubPath_shouldHandleFileInRoot() { - String basePath = "C:\\Library\\Books"; - Path fullFilePath = Path.of("C:\\Library\\Books\\book.epub"); - String result = FileUtils.getRelativeSubPath(basePath, fullFilePath); - assertThat(result).isEqualTo(""); + void testGetRelativeSubPath() { + Path base = tempDir; + Path nested = base.resolve("a/b/c/file.txt"); + + String relative = FileUtils.getRelativeSubPath(base.toString(), nested); + + assertEquals("a/b/c", relative); } @Test - void getRelativeSubPath_shouldHandleTrailingSlashOnBase() { - // This was a likely cause of the bug - String basePath = "C:\\Library\\Books\\"; - Path fullFilePath = Path.of("C:\\Library\\Books\\Series A\\book.epub"); - String result = FileUtils.getRelativeSubPath(basePath, fullFilePath); - assertThat(result).isEqualTo("Series A"); + void testGetRelativeSubPath_noParent() { + Path base = tempDir; + Path file = base.resolve("file.txt"); + + String result = FileUtils.getRelativeSubPath(base.toString(), file); + + assertEquals("", result); } @Test - void getRelativeSubPath_shouldHandleLinuxPaths() { - String basePath = "/home/user/books"; - Path fullFilePath = Path.of("/home/user/books/Series A/book.epub"); - String result = FileUtils.getRelativeSubPath(basePath, fullFilePath); - assertThat(result).isEqualTo("Series A"); + void testGetFileSizeInKb_path() throws IOException { + Path file = tempDir.resolve("sample.txt"); + byte[] content = new byte[2048]; // 2 KB + Files.write(file, content); + + Long size = FileUtils.getFileSizeInKb(file); + + assertEquals(2, size); } @Test - void getRelativeSubPath_shouldHandleNonNormalizedPaths() { - String basePath = "C:\\Library\\.\\Books"; - Path fullFilePath = Path.of("C:\\Library\\Books\\Series A\\..\\Series A\\book.epub"); - String result = FileUtils.getRelativeSubPath(basePath, fullFilePath); - // The normalization should fix both paths and find the correct relative path - assertThat(result).isEqualTo("Series A"); + void testGetFileSizeInKb_pathFileNotFound() { + Path file = tempDir.resolve("missing.txt"); + + Long size = FileUtils.getFileSizeInKb(file); + + assertNull(size); + } + + @Test + void testGetFileSizeInKb_bookEntity() throws IOException { + Path library = tempDir.resolve("lib"); + Files.createDirectories(library); + + String sub = "files"; + Path subFolder = library.resolve(sub); + Files.createDirectories(subFolder); + + Path file = subFolder.resolve("book.epub"); + Files.write(file, new byte[4096]); // 4 KB + + BookEntity book = createBookEntity(library, sub, "book.epub"); + + Long size = FileUtils.getFileSizeInKb(book); + + assertEquals(4, size); + } + + @Test + void testDeleteDirectoryRecursively() throws IOException { + Path dir = tempDir.resolve("deleteMe"); + Files.createDirectories(dir); + + Files.write(dir.resolve("file1.txt"), "data".getBytes()); + Files.createDirectories(dir.resolve("nested")); + Files.write(dir.resolve("nested/file2.txt"), "more".getBytes()); + + assertTrue(Files.exists(dir)); + + FileUtils.deleteDirectoryRecursively(dir); + + assertFalse(Files.exists(dir)); } } \ No newline at end of file