diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java b/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java index 2a7d67c78..1fee478bd 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java @@ -17,7 +17,7 @@ public enum ApiError { DEFAULT_EMAIL_RECIPIENT_NOT_FOUND(HttpStatus.NOT_FOUND, " Default Email recipient not found"), UNSUPPORTED_BOOK_TYPE(HttpStatus.BAD_REQUEST, "Unsupported book type for viewer settings"), INVALID_VIEWER_SETTING(HttpStatus.BAD_REQUEST, "Invalid viewer setting for the book"), - FILE_READ_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Error reading files from path"), + FILE_READ_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Error reading files from path: %s"), IMAGE_NOT_FOUND(HttpStatus.NOT_FOUND, "Image not found or not readable"), INVALID_FILE_FORMAT(HttpStatus.BAD_REQUEST, "Invalid file format, only pdf and epub are supported"), LIBRARY_NOT_FOUND(HttpStatus.NOT_FOUND, "Library not found with ID: %d"), diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java index 15809ef39..3e45d4de3 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java @@ -60,7 +60,7 @@ public class BackgroundUploadService { String extension = getFileExtension(originalFilename); String filename = "1." + extension; - BufferedImage originalImage = FileService.downloadImageFromUrl(imageUrl); + BufferedImage originalImage = fileService.downloadImageFromUrl(imageUrl); deleteExistingBackgroundFiles(userId); fileService.saveBackgroundImage(originalImage, filename, userId); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java index 7630016b6..72d6b6e88 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java @@ -37,6 +37,7 @@ import java.util.stream.Stream; public class FileService { private final AppProperties appProperties; + private final RestTemplate restTemplate; // @formatter:off private static final String IMAGES_DIR = "images"; @@ -114,7 +115,11 @@ public class FileService { throw new IllegalArgumentException("Uploaded file is empty"); } String contentType = file.getContentType(); - if (!(JPEG_MIME_TYPE.equalsIgnoreCase(contentType) || PNG_MIME_TYPE.equalsIgnoreCase(contentType))) { + if (contentType == null) { + throw new IllegalArgumentException("Content type is required"); + } + String lowerType = contentType.toLowerCase(); + if (!lowerType.startsWith(JPEG_MIME_TYPE) && !lowerType.startsWith(PNG_MIME_TYPE)) { throw new IllegalArgumentException("Only JPEG and PNG files are allowed"); } if (file.getSize() > MAX_FILE_SIZE_BYTES) { @@ -146,7 +151,7 @@ public class FileService { log.info("Image saved successfully to: {}", filePath); } - public static BufferedImage downloadImageFromUrl(String imageUrl) throws IOException { + public BufferedImage downloadImageFromUrl(String imageUrl) throws IOException { try { HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.USER_AGENT, "BookLore/1.0 (Metadata Fetcher)"); @@ -154,7 +159,7 @@ public class FileService { HttpEntity entity = new HttpEntity<>(headers); - ResponseEntity response = new RestTemplate().exchange( + ResponseEntity response = restTemplate.exchange( imageUrl, HttpMethod.GET, entity, @@ -175,7 +180,7 @@ public class FileService { } } catch (Exception e) { log.error("Failed to download image from URL: {} - {}", imageUrl, e.getMessage()); - throw new IOException("Failed to download image from URL: " + imageUrl, e); + throw new IOException("Failed to download image from URL: " + imageUrl + " - " + e.getMessage(), e); } } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java index 7b5953ff8..c47bf5f9c 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java @@ -1,72 +1,1151 @@ package com.adityachandel.booklore.util; -import org.junit.jupiter.api.Test; +import com.adityachandel.booklore.config.AppProperties; +import com.adityachandel.booklore.model.entity.BookMetadataEntity; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.web.client.RestTemplate; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.Set; +import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +@ExtendWith(MockitoExtension.class) class FileServiceTest { - @Test - void testTruncate_nullInput() { - String result = FileService.truncate(null, 10); - assertNull(result); + @Mock + private AppProperties appProperties; + + private FileService fileService; + + @TempDir + Path tempDir; + + @BeforeEach + void setup() { + fileService = new FileService(appProperties, mock(RestTemplate.class)); // mock RestTemplate for most tests } - @Test - void testTruncate_emptyString() { - String result = FileService.truncate("", 10); - assertEquals("", result); + @Nested + @DisplayName("Truncate Method") + class TruncateTests { + + @Test + @DisplayName("Returns null for null input") + void truncate_nullInput_returnsNull() { + assertNull(FileService.truncate(null, 10)); + } + + @Test + @DisplayName("Returns empty string for empty input") + void truncate_emptyString_returnsEmpty() { + assertEquals("", FileService.truncate("", 10)); + } + + @ParameterizedTest(name = "maxLength={0} returns empty string") + @ValueSource(ints = {0, -1, -100, Integer.MIN_VALUE}) + @DisplayName("Returns empty for zero or negative maxLength") + void truncate_zeroOrNegativeMaxLength_returnsEmpty(int maxLength) { + assertEquals("", FileService.truncate("test string", maxLength)); + } + + @Test + @DisplayName("Returns original when shorter than maxLength") + void truncate_shortString_returnsOriginal() { + String input = "short"; + assertSame(input, FileService.truncate(input, 100)); + } + + @Test + @DisplayName("Returns original when exactly maxLength") + void truncate_exactLength_returnsOriginal() { + String input = "exactly10!"; + assertEquals(10, input.length()); + assertSame(input, FileService.truncate(input, 10)); + } + + @Test + @DisplayName("Truncates when longer than maxLength") + void truncate_longString_truncates() { + String result = FileService.truncate("this is a long string", 7); + assertEquals("this is", result); + assertEquals(7, result.length()); + } + + @Test + @DisplayName("Handles maxLength of 1") + void truncate_maxLengthOne_returnsSingleChar() { + assertEquals("a", FileService.truncate("abc", 1)); + } + + @Test + @DisplayName("Preserves unicode characters") + void truncate_unicodeCharacters_handlesCorrectly() { + assertEquals("héllo", FileService.truncate("héllo wörld", 5)); + assertEquals("日本語", FileService.truncate("日本語テスト", 3)); + } + + @Test + @DisplayName("Handles surrogate pairs (emojis)") + void truncate_surrogratePairs_mayBreakEmoji() { + String input = "🚀🌟✨"; + // Note: Each emoji is 2 chars, truncating at 3 may break emoji + String result = FileService.truncate(input, 3); + assertEquals(3, result.length()); + } + + @Test + @DisplayName("Handles whitespace-only strings") + void truncate_whitespaceOnly_handlesCorrectly() { + assertEquals(" ", FileService.truncate(" ", 3)); + assertEquals("\t\n", FileService.truncate("\t\n\r", 2)); + } + + @Test + @DisplayName("Handles special characters") + void truncate_specialCharacters_handlesCorrectly() { + assertEquals("!@#", FileService.truncate("!@#$%^&*()", 3)); + } + + @Test + @DisplayName("Handles max integer length") + void truncate_maxIntegerLength_returnsOriginal() { + String input = "test"; + assertSame(input, FileService.truncate(input, Integer.MAX_VALUE)); + } + + @ParameterizedTest + @MethodSource("truncateTestCases") + @DisplayName("Parameterized truncate tests") + void truncate_parameterized(String input, int maxLength, String expected) { + assertEquals(expected, FileService.truncate(input, maxLength)); + } + + static Stream truncateTestCases() { + return Stream.of( + Arguments.of("hello world", 5, "hello"), + Arguments.of("test", 10, "test"), + Arguments.of("abc", 3, "abc"), + Arguments.of("ab", 3, "ab"), + Arguments.of("a", 1, "a"), + Arguments.of("newline\ntest", 7, "newline") + ); + } } - @Test - void testTruncate_shortString() { - String input = "short"; - String result = FileService.truncate(input, 10); - assertEquals("short", result); + @Nested + @DisplayName("Path Utilities") + class PathUtilitiesTests { + + private static final String CONFIG_PATH = "/config"; + + @BeforeEach + void setup() { + lenient().when(appProperties.getPathConfig()).thenReturn(tempDir.toString()); + } + + @Nested + @DisplayName("getImagesFolder") + class GetImagesFolderTests { + + @Test + void returnsCorrectPath() { + String result = fileService.getImagesFolder(123L); + + assertAll( + () -> assertTrue(result.contains("images")), + () -> assertTrue(result.contains("123")), + () -> assertTrue(result.startsWith(tempDir.toString())) + ); + } + + @ParameterizedTest + @ValueSource(longs = {0L, 1L, Long.MAX_VALUE}) + void handlesEdgeCaseBookIds(long bookId) { + String result = fileService.getImagesFolder(bookId); + assertTrue(result.contains(String.valueOf(bookId))); + } + } + + @Nested + @DisplayName("getThumbnailFile") + class GetThumbnailFileTests { + + @Test + void returnsCorrectPath() { + String result = fileService.getThumbnailFile(456L); + + assertAll( + () -> assertTrue(result.contains("456")), + () -> assertTrue(result.endsWith("thumbnail.jpg")) + ); + } + } + + @Nested + @DisplayName("getCoverFile") + class GetCoverFileTests { + + @Test + void returnsCorrectPath() { + String result = fileService.getCoverFile(789L); + + assertAll( + () -> assertTrue(result.contains("789")), + () -> assertTrue(result.endsWith("cover.jpg")) + ); + } + } + + @Nested + @DisplayName("getBackgroundsFolder") + class GetBackgroundsFolderTests { + + @Test + void withUserId_returnsUserSpecificPath() { + String result = fileService.getBackgroundsFolder(42L); + + assertAll( + () -> assertTrue(result.contains("backgrounds")), + () -> assertTrue(result.contains("user-42")) + ); + } + + @Test + void withNullUserId_returnsGlobalPath() { + String result = fileService.getBackgroundsFolder(null); + + assertAll( + () -> assertTrue(result.contains("backgrounds")), + () -> assertFalse(result.contains("user-")) + ); + } + + @Test + void noArgs_delegatesToNullUserId() { + String withNull = fileService.getBackgroundsFolder(null); + String noArgs = fileService.getBackgroundsFolder(); + + assertEquals(withNull, noArgs); + } + } + + @Nested + @DisplayName("getBackgroundUrl (static)") + class GetBackgroundUrlTests { + + @Test + void withUserId_returnsCorrectUrl() { + String result = FileService.getBackgroundUrl("bg.jpg", 10L); + + assertAll( + () -> assertTrue(result.startsWith("/")), + () -> assertTrue(result.contains("backgrounds")), + () -> assertTrue(result.contains("user-10")), + () -> assertTrue(result.endsWith("bg.jpg")), + () -> assertFalse(result.contains("\\"), "Should use forward slashes") + ); + } + + @Test + void withoutUserId_returnsGlobalUrl() { + String result = FileService.getBackgroundUrl("bg.jpg", null); + + assertAll( + () -> assertFalse(result.contains("user-")), + () -> assertTrue(result.contains("backgrounds")), + () -> assertFalse(result.contains("\\")) + ); + } + + @Test + void handlesFilenameWithSpaces() { + String result = FileService.getBackgroundUrl("my background.jpg", null); + assertTrue(result.contains("my background.jpg")); + } + } + + @Nested + @DisplayName("Other path methods") + class OtherPathTests { + + @Test + void getBookMetadataBackupPath_returnsCorrectPath() { + String result = fileService.getBookMetadataBackupPath(100L); + + assertAll( + () -> assertTrue(result.contains("metadata_backup")), + () -> assertTrue(result.contains("100")) + ); + } + + @Test + void getCbxCachePath_returnsCorrectPath() { + assertTrue(fileService.getCbxCachePath().contains("cbx_cache")); + } + + @Test + void getPdfCachePath_returnsCorrectPath() { + assertTrue(fileService.getPdfCachePath().contains("pdf_cache")); + } + + @Test + void getTempBookdropCoverImagePath_returnsCorrectPath() { + String result = fileService.getTempBookdropCoverImagePath(555L); + + assertAll( + () -> assertTrue(result.contains("bookdrop_temp")), + () -> assertTrue(result.endsWith("555.jpg")) + ); + } + + @Test + void getToolsKepubifyPath_returnsCorrectPath() { + String result = fileService.getToolsKepubifyPath(); + + assertAll( + () -> assertTrue(result.contains("tools")), + () -> assertTrue(result.contains("kepubify")) + ); + } + } } - @Test - void testTruncate_exactLength() { - String input = "exactly10"; - String result = FileService.truncate(input, 9); - assertEquals("exactly10", result); + @Nested + @DisplayName("Image Operations") + class ImageOperationsTests { + + @Nested + @DisplayName("resizeImage") + class ResizeImageTests { + + @Test + void shrinks_imageProperly() { + BufferedImage original = createTestImage(100, 100); + + BufferedImage resized = fileService.resizeImage(original, 50, 50); + + assertAll( + () -> assertEquals(50, resized.getWidth()), + () -> assertEquals(50, resized.getHeight()) + ); + } + + @Test + void enlarges_imageProperly() { + BufferedImage original = createTestImage(50, 50); + + BufferedImage resized = fileService.resizeImage(original, 200, 200); + + assertAll( + () -> assertEquals(200, resized.getWidth()), + () -> assertEquals(200, resized.getHeight()) + ); + } + + @Test + void changesAspectRatio() { + BufferedImage original = createTestImage(100, 100); + + BufferedImage resized = fileService.resizeImage(original, 200, 50); + + assertAll( + () -> assertEquals(200, resized.getWidth()), + () -> assertEquals(50, resized.getHeight()) + ); + } + + @Test + void sameSize_worksCorrectly() { + BufferedImage original = createTestImage(100, 100); + + BufferedImage resized = fileService.resizeImage(original, 100, 100); + + assertAll( + () -> assertEquals(100, resized.getWidth()), + () -> assertEquals(100, resized.getHeight()), + () -> assertNotSame(original, resized) + ); + } + + @Test + void returnsRGBType() { + BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); + + BufferedImage resized = fileService.resizeImage(original, 50, 50); + + assertEquals(BufferedImage.TYPE_INT_RGB, resized.getType()); + } + + @Test + void handlesVerySmallDimensions() { + BufferedImage original = createTestImage(100, 100); + + BufferedImage resized = fileService.resizeImage(original, 1, 1); + + assertAll( + () -> assertEquals(1, resized.getWidth()), + () -> assertEquals(1, resized.getHeight()) + ); + } + } + + @Nested + @DisplayName("saveImage") + class SaveImageTests { + + @Test + void validData_createsFile() throws IOException { + BufferedImage image = createTestImage(100, 100); + byte[] imageData = imageToBytes(image); + Path outputPath = tempDir.resolve("test-output.jpg"); + + fileService.saveImage(imageData, outputPath.toString()); + + assertAll( + () -> assertTrue(Files.exists(outputPath)), + () -> assertTrue(Files.size(outputPath) > 0) + ); + } + + @Test + void createsParentDirectories() throws IOException { + BufferedImage image = createTestImage(100, 100); + byte[] imageData = imageToBytes(image); + Path outputPath = tempDir.resolve("nested/deep/folder/test.jpg"); + + fileService.saveImage(imageData, outputPath.toString()); + + assertTrue(Files.exists(outputPath)); + } + + @Test + void invalidImageData_throwsException() { + byte[] invalidData = "not an image".getBytes(); + Path outputPath = tempDir.resolve("invalid.jpg"); + + assertThrows(IllegalArgumentException.class, () -> + fileService.saveImage(invalidData, outputPath.toString())); + } + + @Test + void emptyImageData_throwsException() { + byte[] emptyData = new byte[0]; + Path outputPath = tempDir.resolve("empty.jpg"); + + assertThrows(IllegalArgumentException.class, () -> + fileService.saveImage(emptyData, outputPath.toString())); + } + + @Test + void savedImage_isReadable() throws IOException { + BufferedImage original = createTestImage(100, 100); + byte[] imageData = imageToBytes(original); + Path outputPath = tempDir.resolve("readable.jpg"); + + fileService.saveImage(imageData, outputPath.toString()); + BufferedImage loaded = ImageIO.read(outputPath.toFile()); + + assertAll( + () -> assertNotNull(loaded), + () -> assertEquals(100, loaded.getWidth()), + () -> assertEquals(100, loaded.getHeight()) + ); + } + } } - @Test - void testTruncate_longString() { - String input = "this is a very long string that should be truncated"; - String result = FileService.truncate(input, 20); - assertEquals("this is a very long ", result); - assertEquals(20, result.length()); + @Nested + @DisplayName("Cover Operations") + class CoverOperationsTests { + + @BeforeEach + void setup() { + lenient().when(appProperties.getPathConfig()).thenReturn(tempDir.toString()); + } + + @Nested + @DisplayName("saveCoverImages") + class SaveCoverImagesTests { + + @Test + void createsBothCoverAndThumbnail() throws IOException { + BufferedImage image = createTestImage(500, 700); + + boolean result = fileService.saveCoverImages(image, 1L); + + assertAll( + () -> assertTrue(result), + () -> assertTrue(Files.exists(Path.of(fileService.getCoverFile(1L)))), + () -> assertTrue(Files.exists(Path.of(fileService.getThumbnailFile(1L)))) + ); + } + + @Test + void thumbnailHasCorrectDimensions() throws IOException { + BufferedImage image = createTestImage(1000, 1400); + + fileService.saveCoverImages(image, 2L); + + BufferedImage thumbnail = ImageIO.read( + new File(fileService.getThumbnailFile(2L))); + + assertAll( + () -> assertEquals(250, thumbnail.getWidth()), + () -> assertEquals(350, thumbnail.getHeight()) + ); + } + + @Test + void convertsTransparentToOpaqueWithWhiteBackground() throws IOException { + BufferedImage imageWithAlpha = new BufferedImage( + 100, 100, BufferedImage.TYPE_INT_ARGB); + Graphics2D g = imageWithAlpha.createGraphics(); + g.setColor(new Color(255, 0, 0, 128)); // Semi-transparent red + g.fillRect(0, 0, 100, 100); + g.dispose(); + + boolean result = fileService.saveCoverImages(imageWithAlpha, 3L); + + assertTrue(result); + + // Verify the saved image has no transparency + BufferedImage saved = ImageIO.read( + new File(fileService.getCoverFile(3L))); + assertFalse(saved.getColorModel().hasAlpha(), "Saved image should not have transparency"); + } + + @Test + void createsDirectoryIfNotExists() throws IOException { + BufferedImage image = createTestImage(100, 100); + long bookId = 999L; + + fileService.saveCoverImages(image, bookId); + + assertTrue(Files.isDirectory( + Path.of(fileService.getImagesFolder(bookId)))); + } + + @Test + void originalMaintainsDimensions() throws IOException { + BufferedImage image = createTestImage(800, 1200); + + fileService.saveCoverImages(image, 4L); + + BufferedImage saved = ImageIO.read( + new File(fileService.getCoverFile(4L))); + + assertAll( + () -> assertEquals(800, saved.getWidth()), + () -> assertEquals(1200, saved.getHeight()) + ); + } + } + + @Nested + @DisplayName("createThumbnailFromFile") + class CreateThumbnailFromFileTests { + + @Test + void validJpegFile_succeeds() throws IOException { + BufferedImage image = createTestImage(300, 400); + byte[] imageBytes = imageToBytes(image); + MockMultipartFile file = new MockMultipartFile( + "file", "test.jpg", "image/jpeg", imageBytes); + + assertDoesNotThrow(() -> + fileService.createThumbnailFromFile(5L, file)); + assertTrue(Files.exists(Path.of(fileService.getCoverFile(5L)))); + } + + @Test + void validPngFile_succeeds() throws IOException { + BufferedImage image = createTestImage(300, 400); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ImageIO.write(image, "PNG", baos); + MockMultipartFile file = new MockMultipartFile( + "file", "test.png", "image/png", baos.toByteArray()); + + assertDoesNotThrow(() -> + fileService.createThumbnailFromFile(6L, file)); + } + + @Test + void emptyFile_throwsException() { + MockMultipartFile emptyFile = new MockMultipartFile( + "file", "empty.jpg", "image/jpeg", new byte[0]); + + Exception exception = assertThrows(Exception.class, () -> + fileService.createThumbnailFromFile(7L, emptyFile)); + assertTrue(exception.getMessage().contains("empty")); + } + + @Test + void invalidMimeType_throwsException() { + MockMultipartFile gifFile = new MockMultipartFile( + "file", "test.gif", "image/gif", "fake data".getBytes()); + + Exception exception = assertThrows(Exception.class, () -> + fileService.createThumbnailFromFile(8L, gifFile)); + assertTrue(exception.getMessage().contains("Only JPEG and PNG files are allowed")); + } + + @Test + void fileTooLarge_throwsException() { + byte[] largeData = new byte[6 * 1024 * 1024]; // 6MB + MockMultipartFile largeFile = new MockMultipartFile( + "file", "large.jpg", "image/jpeg", largeData); + + Exception exception = assertThrows(Exception.class, () -> + fileService.createThumbnailFromFile(9L, largeFile)); + assertTrue(exception.getMessage().contains("5 MB")); + } + + @Test + void fileExactlyAtSizeLimit_succeeds() throws IOException { + BufferedImage image = createTestImage(100, 100); + byte[] imageBytes = imageToBytes(image); + // Ensure it's under 5MB + assertTrue(imageBytes.length < 5 * 1024 * 1024); + + MockMultipartFile file = new MockMultipartFile( + "file", "valid.jpg", "image/jpeg", imageBytes); + + assertDoesNotThrow(() -> + fileService.createThumbnailFromFile(10L, file)); + } + + @Test + void caseInsensitiveMimeType_succeeds() throws IOException { + BufferedImage image = createTestImage(100, 100); + byte[] imageBytes = imageToBytes(image); + MockMultipartFile file = new MockMultipartFile( + "file", "test.jpg", "IMAGE/JPEG", imageBytes); + + assertDoesNotThrow(() -> + fileService.createThumbnailFromFile(11L, file)); + } + + @Test + void corruptImageData_throwsException() { + // Valid MIME type but corrupt image data + byte[] corruptData = ("not an image but has jpeg mime type").getBytes(); + MockMultipartFile corruptFile = new MockMultipartFile( + "file", "corrupt.jpg", "image/jpeg", corruptData); + + Exception exception = assertThrows(Exception.class, () -> + fileService.createThumbnailFromFile(12L, corruptFile)); + assertTrue(exception.getMessage().contains("Image not found or not readable")); + } + + @Test + void unsupportedMimeType_gif_throwsException() { + byte[] gifData = "GIF89a...".getBytes(); // Fake GIF header + MockMultipartFile gifFile = new MockMultipartFile( + "file", "test.gif", "image/gif", gifData); + + assertThrows(Exception.class, () -> + fileService.createThumbnailFromFile(13L, gifFile)); + } + + @Test + void mimeTypeWithExtraParameters_succeeds() throws IOException { + BufferedImage image = createTestImage(100, 100); + byte[] imageBytes = imageToBytes(image); + MockMultipartFile file = new MockMultipartFile( + "file", "test.jpg", "image/jpeg;charset=UTF-8", imageBytes); + + assertDoesNotThrow(() -> + fileService.createThumbnailFromFile(14L, file)); + } + } + + @Nested + @DisplayName("setBookCoverPath") + class SetBookCoverPathTests { + + @Test + void setsTimestampToCurrentTime() { + BookMetadataEntity entity = new BookMetadataEntity(); + Instant before = Instant.now(); + + FileService.setBookCoverPath(entity); + + Instant after = Instant.now(); + + assertNotNull(entity.getCoverUpdatedOn()); + assertFalse(entity.getCoverUpdatedOn().isBefore(before)); + assertFalse(entity.getCoverUpdatedOn().isAfter(after)); + } + + @Test + void overwritesExistingTimestamp() { + BookMetadataEntity entity = new BookMetadataEntity(); + Instant oldTime = Instant.parse("2020-01-01T00:00:00Z"); + entity.setCoverUpdatedOn(oldTime); + + FileService.setBookCoverPath(entity); + + assertNotEquals(oldTime, entity.getCoverUpdatedOn()); + } + } + + @Nested + @DisplayName("deleteBookCovers") + class DeleteBookCoversTests { + + @Test + void existingCovers_deletesAll() throws IOException { + BufferedImage image = createTestImage(100, 100); + fileService.saveCoverImages(image, 10L); + fileService.saveCoverImages(image, 11L); + + fileService.deleteBookCovers(Set.of(10L, 11L)); + + assertAll( + () -> assertFalse(Files.exists( + Path.of(fileService.getImagesFolder(10L)))), + () -> assertFalse(Files.exists( + Path.of(fileService.getImagesFolder(11L)))) + ); + } + + @Test + void nonExistentCovers_doesNotThrow() { + assertDoesNotThrow(() -> + fileService.deleteBookCovers(Set.of(999L, 1000L))); + } + + @Test + void emptySet_doesNothing() { + assertDoesNotThrow(() -> + fileService.deleteBookCovers(Set.of())); + } + + @Test + void mixedExistingAndNonExisting_deletesExisting() throws IOException { + BufferedImage image = createTestImage(100, 100); + fileService.saveCoverImages(image, 20L); + + fileService.deleteBookCovers(Set.of(20L, 21L)); + + assertFalse(Files.exists(Path.of(fileService.getImagesFolder(20L)))); + } + + @Test + void singleBookId_works() throws IOException { + BufferedImage image = createTestImage(100, 100); + fileService.saveCoverImages(image, 30L); + + fileService.deleteBookCovers(Set.of(30L)); + + assertFalse(Files.exists(Path.of(fileService.getImagesFolder(30L)))); + } + } } - @Test - void testTruncate_zeroMaxLength() { - String input = "test string"; - String result = FileService.truncate(input, 0); - assertEquals("", result); + @Nested + @DisplayName("Network Operations") + class NetworkOperationsTests { + + @Mock + private RestTemplate restTemplate; + + private FileService fileService; + + @BeforeEach + void setup() { + lenient().when(appProperties.getPathConfig()).thenReturn(tempDir.toString()); + fileService = new FileService(appProperties, restTemplate); + } + + @Nested + @DisplayName("downloadImageFromUrl") + class DownloadImageFromUrlTests { + + @Test + @DisplayName("downloads and returns valid image") + @Timeout(5) + void downloadImageFromUrl_validImage_returnsBufferedImage() throws IOException { + String imageUrl = "http://example.com/image.jpg"; + BufferedImage testImage = createTestImage(100, 100); + byte[] imageBytes = imageToBytes(testImage); + + RestTemplate mockRestTemplate = mock(RestTemplate.class); + FileService testFileService = new FileService(appProperties, mockRestTemplate); + + ResponseEntity responseEntity = ResponseEntity.ok(imageBytes); + when(mockRestTemplate.exchange( + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) + )).thenReturn(responseEntity); + + BufferedImage result = testFileService.downloadImageFromUrl(imageUrl); + + assertNotNull(result); + assertEquals(100, result.getWidth()); + assertEquals(100, result.getHeight()); + } + + @Test + @DisplayName("throws exception when response body is null") + @Timeout(5) + void downloadImageFromUrl_nullBody_throwsException() { + String imageUrl = "http://example.com/image.jpg"; + ResponseEntity responseEntity = ResponseEntity.ok(null); + when(restTemplate.exchange( + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) + )).thenReturn(responseEntity); + + assertThrows(IOException.class, () -> + fileService.downloadImageFromUrl(imageUrl)); + } + + @Test + @DisplayName("throws exception when ImageIO cannot read bytes") + @Timeout(5) + void downloadImageFromUrl_invalidImageData_throwsException() { + String imageUrl = "http://example.com/image.jpg"; + byte[] invalidBytes = "not an image".getBytes(); + ResponseEntity responseEntity = ResponseEntity.ok(invalidBytes); + when(restTemplate.exchange( + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) + )).thenReturn(responseEntity); + + assertThrows(IOException.class, () -> + fileService.downloadImageFromUrl(imageUrl)); + } + + @Test + @DisplayName("throws exception on HTTP error status") + @Timeout(5) + void downloadImageFromUrl_httpError_throwsException() { + String imageUrl = "http://example.com/image.jpg"; + ResponseEntity responseEntity = ResponseEntity.notFound().build(); + when(restTemplate.exchange( + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) + )).thenReturn(responseEntity); + + assertThrows(IOException.class, () -> + fileService.downloadImageFromUrl(imageUrl)); + } + } + + @Nested + @DisplayName("createThumbnailFromUrl") + class CreateThumbnailFromUrlTests { + + @Test + @DisplayName("downloads and saves cover images successfully") + @Timeout(5) + void createThumbnailFromUrl_validImage_createsCoverAndThumbnail() throws IOException { + String imageUrl = "http://example.com/cover.jpg"; + long bookId = 42L; + BufferedImage testImage = createTestImage(800, 1200); // Portrait image + byte[] imageBytes = imageToBytes(testImage); + + ResponseEntity responseEntity = ResponseEntity.ok(imageBytes); + when(restTemplate.exchange( + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) + )).thenReturn(responseEntity); + + assertDoesNotThrow(() -> + fileService.createThumbnailFromUrl(bookId, imageUrl)); + + Path imagesFolder = tempDir.resolve("images").resolve(String.valueOf(bookId)); + assertTrue(Files.exists(imagesFolder.resolve("cover.jpg"))); + assertTrue(Files.exists(imagesFolder.resolve("thumbnail.jpg"))); + + BufferedImage thumbnail = ImageIO.read(imagesFolder.resolve("thumbnail.jpg").toFile()); + assertEquals(250, thumbnail.getWidth()); // THUMBNAIL_WIDTH + assertEquals(350, thumbnail.getHeight()); // THUMBNAIL_HEIGHT + } + + @Test + @DisplayName("throws ApiError.FILE_READ_ERROR on download failure") + @Timeout(5) + void createThumbnailFromUrl_downloadFails_throwsApiError() { + String imageUrl = "http://example.com/invalid.jpg"; + long bookId = 42L; + + when(restTemplate.exchange( + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) + )).thenThrow(new RuntimeException("Network error")); + + Exception exception = assertThrows(Exception.class, () -> + fileService.createThumbnailFromUrl(bookId, imageUrl)); + assertTrue(exception.getMessage().contains("Network error")); + } + + } } - @Test - void testTruncate_negativeMaxLength() { - String input = "test string"; - String result = FileService.truncate(input, -5); - assertEquals("", result); + @Nested + @DisplayName("Background Operations") + class BackgroundOperationsTests { + + @BeforeEach + void setup() { + when(appProperties.getPathConfig()).thenReturn(tempDir.toString()); + } + + @Nested + @DisplayName("saveBackgroundImage") + class SaveBackgroundImageTests { + + @Test + void userBackground_savesInUserFolder() throws IOException { + BufferedImage image = createTestImage(1920, 1080); + + fileService.saveBackgroundImage(image, "bg.jpg", 1L); + + Path expected = tempDir.resolve("backgrounds/user-1/bg.jpg"); + assertTrue(Files.exists(expected)); + } + + @Test + void globalBackground_savesInGlobalFolder() throws IOException { + BufferedImage image = createTestImage(1920, 1080); + + fileService.saveBackgroundImage(image, "global.jpg", null); + + Path expected = tempDir.resolve("backgrounds/global.jpg"); + assertTrue(Files.exists(expected)); + } + + @Test + void createsDirectoryIfNotExists() throws IOException { + BufferedImage image = createTestImage(100, 100); + + fileService.saveBackgroundImage(image, "new.jpg", 2L); + + assertTrue(Files.isDirectory( + tempDir.resolve("backgrounds/user-2"))); + } + + @Test + void overwritesExistingFile() throws IOException { + BufferedImage image1 = createTestImage(100, 100, Color.RED); + BufferedImage image2 = createTestImage(100, 100, Color.BLUE); + + fileService.saveBackgroundImage(image1, "bg.jpg", 3L); + long size1 = Files.size( + tempDir.resolve("backgrounds/user-3/bg.jpg")); + + fileService.saveBackgroundImage(image2, "bg.jpg", 3L); + long size2 = Files.size( + tempDir.resolve("backgrounds/user-3/bg.jpg")); + + // File exists and was overwritten (sizes might be same/different) + assertTrue(Files.exists( + tempDir.resolve("backgrounds/user-3/bg.jpg"))); + } + } + + @Nested + @DisplayName("deleteBackgroundFile") + class DeleteBackgroundFileTests { + + @Test + void existingFile_deletesIt() throws IOException { + BufferedImage image = createTestImage(100, 100); + fileService.saveBackgroundImage(image, "to-delete.jpg", 4L); + + fileService.deleteBackgroundFile("to-delete.jpg", 4L); + + assertFalse(Files.exists( + tempDir.resolve("backgrounds/user-4/to-delete.jpg"))); + } + + @Test + void nonExistentFile_doesNotThrow() { + assertDoesNotThrow(() -> + fileService.deleteBackgroundFile("nonexistent.jpg", 5L)); + } + + @Test + void lastFileInUserFolder_deletesEmptyFolder() throws IOException { + BufferedImage image = createTestImage(100, 100); + fileService.saveBackgroundImage(image, "only.jpg", 6L); + + fileService.deleteBackgroundFile("only.jpg", 6L); + + assertFalse(Files.exists(tempDir.resolve("backgrounds/user-6"))); + } + + @Test + void notLastFile_keepsFolder() throws IOException { + BufferedImage image = createTestImage(100, 100); + fileService.saveBackgroundImage(image, "file1.jpg", 7L); + fileService.saveBackgroundImage(image, "file2.jpg", 7L); + + fileService.deleteBackgroundFile("file1.jpg", 7L); + + assertTrue(Files.isDirectory( + tempDir.resolve("backgrounds/user-7"))); + } + + @Test + void globalBackground_deletesFile() throws IOException { + BufferedImage image = createTestImage(100, 100); + Path bgFolder = tempDir.resolve("backgrounds"); + Files.createDirectories(bgFolder); + ImageIO.write(image, "JPEG", bgFolder.resolve("global.jpg").toFile()); + + fileService.deleteBackgroundFile("global.jpg", null); + + assertFalse(Files.exists(bgFolder.resolve("global.jpg"))); + } + } + + @Nested + @DisplayName("getBackgroundResource") + class GetBackgroundResourceTests { + + @Test + void userHasBackground_returnsUserBackground() throws IOException { + createUserBackground(8L, "1.jpg"); + + Resource resource = fileService.getBackgroundResource(8L); + + assertAll( + () -> assertInstanceOf(FileSystemResource.class, resource), + () -> assertTrue(resource.exists()) + ); + } + + @Test + void userHasNoBackground_globalExists_returnsGlobal() throws IOException { + createGlobalBackground("1.jpg"); + + Resource resource = fileService.getBackgroundResource(9L); + + assertInstanceOf(FileSystemResource.class, resource); + } + + @Test + void noCustomBackgrounds_returnsDefault() { + Resource resource = fileService.getBackgroundResource(10L); + + assertInstanceOf(ClassPathResource.class, resource); + } + + @ParameterizedTest + @ValueSource(strings = {"1.jpg", "1.jpeg", "1.png"}) + void supportsMultipleFormats(String filename) throws IOException { + Path bgFolder = tempDir.resolve("backgrounds"); + Files.createDirectories(bgFolder); + Files.createFile(bgFolder.resolve(filename)); + + Resource resource = fileService.getBackgroundResource(null); + + assertTrue(resource.exists()); + } + + @Test + void userBackgroundTakesPriority_overGlobal() throws IOException { + createGlobalBackground("1.jpg"); + createUserBackground(11L, "1.jpg"); + + Resource resource = fileService.getBackgroundResource(11L); + + String path = ((FileSystemResource) resource).getPath(); + assertTrue(path.contains("user-11")); + } + + @Test + @DisplayName("Priority: user > global > default") + void checksPriorityOrder() throws IOException { + // Only global exists + createGlobalBackground("1.jpg"); + Resource globalResource = fileService.getBackgroundResource(12L); + assertTrue(globalResource.exists()); + + // Add user background + createUserBackground(12L, "1.jpg"); + Resource userResource = fileService.getBackgroundResource(12L); + String path = ((FileSystemResource) userResource).getPath(); + assertTrue(path.contains("user-12")); + } + + private void createUserBackground(Long userId, String filename) + throws IOException { + Path folder = tempDir.resolve("backgrounds/user-" + userId); + Files.createDirectories(folder); + BufferedImage img = createTestImage(100, 100); + ImageIO.write(img, "JPEG", folder.resolve(filename).toFile()); + } + + private void createGlobalBackground(String filename) throws IOException { + Path folder = tempDir.resolve("backgrounds"); + Files.createDirectories(folder); + BufferedImage img = createTestImage(100, 100); + ImageIO.write(img, "JPEG", folder.resolve(filename).toFile()); + } + } } - @Test - void testTruncate_unicodeCharacters() { - String input = "héllo wörld with unicode"; - String result = FileService.truncate(input, 15); - assertEquals("héllo wörld wit", result); - assertEquals(15, result.length()); + private BufferedImage createTestImage(int width, int height) { + return createTestImage(width, height, Color.BLUE); } - @Test - void testTruncate_multibyteCharacters() { - String input = "🚀 rocket emoji test 🌟"; - String result = FileService.truncate(input, 10); - // Note: This might not be exactly 10 characters due to how Java handles string length with emojis - assertTrue(result.length() <= input.length()); + private BufferedImage createTestImage(int width, int height, Color color) { + BufferedImage image = new BufferedImage( + width, height, BufferedImage.TYPE_INT_RGB); + Graphics2D g = image.createGraphics(); + g.setColor(color); + g.fillRect(0, 0, width, height); + g.setColor(Color.WHITE); + g.drawString("Test", 10, height / 2); + g.dispose(); + return image; } -} + + private byte[] imageToBytes(BufferedImage image) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ImageIO.write(image, "JPEG", baos); + return baos.toByteArray(); + } +} \ No newline at end of file diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/MetadataChangeDetectorTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/MetadataChangeDetectorTest.java new file mode 100644 index 000000000..8c337c3b2 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/MetadataChangeDetectorTest.java @@ -0,0 +1,550 @@ +package com.adityachandel.booklore.util; + +import com.adityachandel.booklore.model.MetadataClearFlags; +import com.adityachandel.booklore.model.dto.BookMetadata; +import com.adityachandel.booklore.model.entity.AuthorEntity; +import com.adityachandel.booklore.model.entity.BookMetadataEntity; +import com.adityachandel.booklore.model.entity.CategoryEntity; +import com.adityachandel.booklore.model.entity.MoodEntity; +import com.adityachandel.booklore.model.entity.TagEntity; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.LocalDate; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.*; + +public class MetadataChangeDetectorTest { + + private BookMetadataEntity existingMeta; + private BookMetadata newMeta; + private MetadataClearFlags clearFlags; + + @BeforeEach + void setup() { + existingMeta = BookMetadataEntity.builder() + .bookId(1L) + .title("Original Title") + .subtitle("Original Subtitle") + .publisher("Original Publisher") + .publishedDate(LocalDate.of(2020, 1, 1)) + .description("Original Description") + .seriesName("Original Series") + .seriesNumber(1.0f) + .seriesTotal(5) + .isbn13("9781234567890") + .isbn10("1234567890") + .asin("B012345678") + .goodreadsId("12345678") + .comicvineId("987654") + .hardcoverId("hc123456") + .googleId("google123") + .pageCount(300) + .language("en") + .personalRating(4.5) + .amazonRating(4.2) + .amazonReviewCount(1500) + .goodreadsRating(4.1) + .goodreadsReviewCount(25000) + .hardcoverRating(4.0) + .hardcoverReviewCount(500) + .titleLocked(false) + .subtitleLocked(false) + .publisherLocked(false) + .publishedDateLocked(false) + .descriptionLocked(false) + .seriesNameLocked(false) + .seriesNumberLocked(false) + .seriesTotalLocked(false) + .isbn13Locked(false) + .isbn10Locked(false) + .asinLocked(false) + .goodreadsIdLocked(false) + .comicvineIdLocked(false) + .hardcoverIdLocked(false) + .googleIdLocked(false) + .pageCountLocked(false) + .languageLocked(false) + .personalRatingLocked(false) + .amazonRatingLocked(false) + .amazonReviewCountLocked(false) + .goodreadsRatingLocked(false) + .goodreadsReviewCountLocked(false) + .hardcoverRatingLocked(false) + .hardcoverReviewCountLocked(false) + .coverLocked(false) + .authorsLocked(false) + .categoriesLocked(false) + .moodsLocked(false) + .tagsLocked(false) + .authors(Set.of( + AuthorEntity.builder().id(1L).name("Author One").build(), + AuthorEntity.builder().id(2L).name("Author Two").build() + )) + .categories(Set.of( + CategoryEntity.builder().id(1L).name("Fiction").build(), + CategoryEntity.builder().id(2L).name("Mystery").build() + )) + .moods(Set.of( + MoodEntity.builder().id(1L).name("Dark").build(), + MoodEntity.builder().id(2L).name("Suspenseful").build() + )) + .tags(Set.of( + TagEntity.builder().id(1L).name("Thriller").build(), + TagEntity.builder().id(2L).name("Bestseller").build() + )) + .build(); + + newMeta = BookMetadata.builder() + .bookId(1L) + .title("Original Title") + .subtitle("Original Subtitle") + .publisher("Original Publisher") + .publishedDate(LocalDate.of(2020, 1, 1)) + .description("Original Description") + .seriesName("Original Series") + .seriesNumber(1.0f) + .seriesTotal(5) + .isbn13("9781234567890") + .isbn10("1234567890") + .asin("B012345678") + .goodreadsId("12345678") + .comicvineId("987654") + .hardcoverId("hc123456") + .googleId("google123") + .pageCount(300) + .language("en") + .personalRating(4.5) + .amazonRating(4.2) + .amazonReviewCount(1500) + .goodreadsRating(4.1) + .goodreadsReviewCount(25000) + .hardcoverRating(4.0) + .hardcoverReviewCount(500) + .titleLocked(false) + .subtitleLocked(false) + .publisherLocked(false) + .publishedDateLocked(false) + .descriptionLocked(false) + .seriesNameLocked(false) + .seriesNumberLocked(false) + .seriesTotalLocked(false) + .isbn13Locked(false) + .isbn10Locked(false) + .asinLocked(false) + .goodreadsIdLocked(false) + .comicvineIdLocked(false) + .hardcoverIdLocked(false) + .googleIdLocked(false) + .pageCountLocked(false) + .languageLocked(false) + .personalRatingLocked(false) + .amazonRatingLocked(false) + .amazonReviewCountLocked(false) + .goodreadsRatingLocked(false) + .goodreadsReviewCountLocked(false) + .hardcoverRatingLocked(false) + .hardcoverReviewCountLocked(false) + .coverLocked(false) + .authorsLocked(false) + .categoriesLocked(false) + .moodsLocked(false) + .tagsLocked(false) + .authors(Set.of("Author One", "Author Two")) + .categories(Set.of("Fiction", "Mystery")) + .moods(Set.of("Dark", "Suspenseful")) + .tags(Set.of("Thriller", "Bestseller")) + .build(); + + clearFlags = new MetadataClearFlags(); + } + + @Test + void testIsDifferent_whenNoChanges_returnsFalse() { + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertFalse(result, "Should return false when no changes exist"); + } + + @ParameterizedTest(name = "{0} field change") + @MethodSource("fieldChangeProvider") + @DisplayName("isDifferent() detects changes in all metadata fields") + void testIsDifferent_whenFieldChanges_returnsTrue(String fieldName, Consumer modifier) { + modifier.accept(newMeta); + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertTrue(result, "Should detect change in " + fieldName); + } + + static Stream fieldChangeProvider() { + return Stream.of( + Arguments.of("title", (Consumer) m -> m.setTitle("New Title")), + Arguments.of("subtitle", (Consumer) m -> m.setSubtitle("New Subtitle")), + Arguments.of("publisher", (Consumer) m -> m.setPublisher("New Publisher")), + Arguments.of("publishedDate", (Consumer) m -> m.setPublishedDate(LocalDate.of(2021, 6, 15))), + Arguments.of("description", (Consumer) m -> m.setDescription("New Description")), + Arguments.of("seriesName", (Consumer) m -> m.setSeriesName("New Series")), + Arguments.of("seriesNumber", (Consumer) m -> m.setSeriesNumber(2.0f)), + Arguments.of("seriesTotal", (Consumer) m -> m.setSeriesTotal(10)), + Arguments.of("isbn13", (Consumer) m -> m.setIsbn13("9780987654321")), + Arguments.of("isbn10", (Consumer) m -> m.setIsbn10("0987654321")), + Arguments.of("asin", (Consumer) m -> m.setAsin("B098765432")), + Arguments.of("goodreadsId", (Consumer) m -> m.setGoodreadsId("87654321")), + Arguments.of("comicvineId", (Consumer) m -> m.setComicvineId("123456")), + Arguments.of("hardcoverId", (Consumer) m -> m.setHardcoverId("hc654321")), + Arguments.of("googleId", (Consumer) m -> m.setGoogleId("google456")), + Arguments.of("pageCount", (Consumer) m -> m.setPageCount(350)), + Arguments.of("language", (Consumer) m -> m.setLanguage("fr")), + Arguments.of("personalRating", (Consumer) m -> m.setPersonalRating(4.8)), + Arguments.of("amazonRating", (Consumer) m -> m.setAmazonRating(4.5)), + Arguments.of("amazonReviewCount", (Consumer) m -> m.setAmazonReviewCount(2000)), + Arguments.of("goodreadsRating", (Consumer) m -> m.setGoodreadsRating(4.3)), + Arguments.of("goodreadsReviewCount", (Consumer) m -> m.setGoodreadsReviewCount(30000)), + Arguments.of("hardcoverRating", (Consumer) m -> m.setHardcoverRating(4.2)), + Arguments.of("hardcoverReviewCount", (Consumer) m -> m.setHardcoverReviewCount(750)) + ); + } + + @Test + void testIsDifferent_whenNullClearFlags_returnsTrue() { + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, null); + assertTrue(result, "Should return true when clear flags is null"); + } + + @Test + void testIsDifferent_whenTitleLocked_changes_returnsTrue() { + newMeta.setTitleLocked(true); + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertTrue(result, "Should return true when title lock changes"); + } + + @Test + void testIsDifferent_whenCoverLocked_changes_returnsTrue() { + newMeta.setCoverLocked(true); + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertTrue(result, "Should return true when cover lock changes"); + } + + @Test + void testIsDifferent_whenFieldLocked_changes_returnsTrue() { + existingMeta.setTitleLocked(true); + newMeta.setTitleLocked(false); + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertTrue(result, "Should return true when field lock changes"); + } + + @Test + void testIsDifferent_whenFieldLocked_noChange_returnsFalse() { + existingMeta.setTitleLocked(true); + newMeta.setTitleLocked(true); + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertFalse(result, "Should return false when field locks match"); + } + + @Test + void testHasValueChanges_whenNoChanges_returnsFalse() { + boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags); + assertFalse(result, "Should return false when no value changes exist"); + } + + @Test + void testHasValueChanges_whenTitleChanged_returnsTrue() { + newMeta.setTitle("New Title"); + boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags); + assertTrue(result, "Should return true when title value changes"); + } + + @Test + void testHasValueChanges_whenLockedFieldChanged_returnsFalse() { + existingMeta.setTitleLocked(true); + newMeta.setTitle("New Title"); + boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags); + assertFalse(result, "Should return false when locked field changes"); + } + + @Test + void testHasValueChanges_whenClearFlagSet_returnsTrue() { + clearFlags.setTitle(true); + boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags); + assertTrue(result, "Should return true when clear flag is set (even if values match)"); + } + + @Test + void testHasValueChangesForFileWrite_whenNoChanges_returnsFalse() { + boolean result = MetadataChangeDetector.hasValueChangesForFileWrite(newMeta, existingMeta, clearFlags); + assertFalse(result, "Should return false when no value changes exist for file write"); + } + + @Test + void testHasValueChangesForFileWrite_whenTitleChanged_returnsTrue() { + newMeta.setTitle("New Title"); + boolean result = MetadataChangeDetector.hasValueChangesForFileWrite(newMeta, existingMeta, clearFlags); + assertTrue(result, "Should return true when title value changes for file write"); + } + + @Test + void testHasValueChangesForFileWrite_excludesRatingsForFileWrite() { + // Change rating fields that should not be considered for file write + newMeta.setAmazonRating(4.8); + newMeta.setGoodreadsRating(4.4); + newMeta.setHardcoverRating(4.3); + boolean result = MetadataChangeDetector.hasValueChangesForFileWrite(newMeta, existingMeta, clearFlags); + assertFalse(result, "Should return false when only rating fields change for file write"); + } + + @Test + void testEdgeCase_nullToEmptyString_returnsFalse() { + existingMeta.setTitle(null); + newMeta.setTitle(""); + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertFalse(result, "Should return false for null to empty string transition"); + } + + @Test + void testEdgeCase_nullToEmptyCollection_returnsFalse() { + BookMetadataEntity testExisting = BookMetadataEntity.builder() + .bookId(1L) + .title("Original Title") + .subtitle("Original Subtitle") + .publisher("Original Publisher") + .authors(null) // null authors, this is what we're testing + .authorsLocked(false) + .categories(Set.of(CategoryEntity.builder().id(1L).name("Fiction").build())) + .categoriesLocked(false) + .moods(Set.of(MoodEntity.builder().id(1L).name("Dark").build())) + .moodsLocked(false) + .tags(Set.of(TagEntity.builder().id(1L).name("Thriller").build())) + .tagsLocked(false) + .titleLocked(false) + .subtitleLocked(false) + .publisherLocked(false) + .build(); + + BookMetadata testNew = BookMetadata.builder() + .bookId(1L) + .title("Original Title") + .subtitle("Original Subtitle") + .publisher("Original Publisher") + .authors(Set.of()) // empty set, this is what we're testing + .authorsLocked(false) + .categories(Set.of("Fiction")) + .categoriesLocked(false) + .moods(Set.of("Dark")) + .moodsLocked(false) + .tags(Set.of("Thriller")) + .tagsLocked(false) + .titleLocked(false) + .subtitleLocked(false) + .publisherLocked(false) + .build(); + + boolean result = MetadataChangeDetector.isDifferent(testNew, testExisting, clearFlags); + assertFalse(result, "Should return false because toNameSet converts null to empty set, so null → empty collection is no change"); + } + + @Test + void testEdgeCase_emptyStringToNull_returnsTrue() { + existingMeta.setTitle(""); + newMeta.setTitle(null); + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertTrue(result, "Should return true for empty string to null transition"); + } + + @Test + void testEdgeCase_emptyCollectionToNull_returnsTrue() { + BookMetadataEntity testExisting = BookMetadataEntity.builder() + .bookId(1L) + .title("Test Title") + .authors(Set.of()) // empty set, what we're testing + .authorsLocked(false) + .categories(Set.of(CategoryEntity.builder().id(1L).name("Fiction").build())) + .categoriesLocked(false) + .moods(Set.of(MoodEntity.builder().id(1L).name("Dark").build())) + .moodsLocked(false) + .tags(Set.of(TagEntity.builder().id(1L).name("Tag").build())) + .tagsLocked(false) + .titleLocked(false) + .build(); + + BookMetadata testNew = BookMetadata.builder() + .bookId(1L) + .title("Test Title") + .authors(null) // null, what we're testing + .authorsLocked(false) + .categories(Set.of("Fiction")) // Match existing + .categoriesLocked(false) + .moods(Set.of("Dark")) // Match existing + .moodsLocked(false) + .tags(Set.of("Tag")) // Match existing + .tagsLocked(false) + .titleLocked(false) + .build(); + boolean result = MetadataChangeDetector.isDifferent(testNew, testExisting, clearFlags); + assertTrue(result, "Should return true for empty collection to null transition"); + } + + @Test + @DisplayName("Locked field blocks value changes but still detects lock state changes") + void testIsDifferent_whenFieldLockedAndValueDifferent_stillDetectsLockChange() { + existingMeta.setTitleLocked(true); + newMeta.setTitle("New Title"); // value change (should be ignored due to lock) + newMeta.setTitleLocked(false); // lock change (should be detected) + + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertTrue(result, "Should detect lock change even if value change is blocked by lock"); + + boolean valueResult = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags); + assertFalse(valueResult, "Should not detect value change when field is locked"); + } + + @Test + void testIsDifferent_whenFieldLockedAndOnlyValueDifferent_returnsFalse() { + existingMeta.setTitleLocked(true); + newMeta.setTitle("New Title"); + newMeta.setTitleLocked(true); // lock unchanged + + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertFalse(result, "Should not detect value change when field is locked and lock is unchanged"); + } + + @Test + void testClearFlag_whenFieldUnlocked_triggersChange() { + BookMetadataEntity testExisting = BookMetadataEntity.builder() + .bookId(1L) + .title("Existing Title") + .titleLocked(false) // field is unlocked + .build(); + BookMetadata testNew = BookMetadata.builder() + .bookId(1L) + .title("Existing Title") // same title + .titleLocked(false) + .build(); + MetadataClearFlags testClearFlags = new MetadataClearFlags(); + testClearFlags.setTitle(true); // clear flag forces change detection + + boolean result = MetadataChangeDetector.hasValueChanges(testNew, testExisting, testClearFlags); + assertTrue(result, "Clear flag should trigger change when field is unlocked, even with identical values"); + } + + @Test + @DisplayName("Lock takes precedence over clear flag") + void testHasValueChanges_whenClearFlagTrue_lockStillTakesPrecedence() { + existingMeta.setTitleLocked(true); + newMeta.setTitle("New Title"); + clearFlags.setTitle(true); + + boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags); + assertFalse(result, "Lock should take precedence over clear flag"); + } + + @Test + void testClearFlag_whenExistingValueIsNull_returnsFalse() { + existingMeta.setTitle(null); + existingMeta.setTitleLocked(false); + newMeta.setTitle("New Title"); + clearFlags.setTitle(true); + + boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags); + assertFalse(result, "Clear flag with null existing value means nothing to clear"); + } + + @Test + void testAuthorsSetComparison_isOrderInsensitive() { + // Change order of authors in newMeta + newMeta.setAuthors(Set.of("Author Two", "Author One")); + // existingMeta has Set.of("Author One", "Author Two") from setup + + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertFalse(result, "Authors set comparison should be order insensitive"); + } + + @Test + void testIsDifferent_whenClearFlagTrue_andValuesIdentical_returnsTrue() { + // newMeta and existingMeta have identical title values + clearFlags.setTitle(true); // but clear flag forces change detection + + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertTrue(result, "isDifferent should return true when clear flag is set, even if values are identical"); + } + + @Test + @DisplayName("hasValueChangesForFileWrite() excludes certain fields from triggering file writes") + void testHasValueChangesForFileWrite_excludesPageCount() { + newMeta.setPageCount(999); + boolean result = MetadataChangeDetector.hasValueChangesForFileWrite(newMeta, existingMeta, clearFlags); + assertFalse(result, "PageCount should not trigger file write"); + } + + @Test + void testHasValueChangesForFileWrite_excludesMoods() { + newMeta.setMoods(Set.of("New Mood")); + boolean result = MetadataChangeDetector.hasValueChangesForFileWrite(newMeta, existingMeta, clearFlags); + assertFalse(result, "Moods should not trigger file write"); + } + + @Test + void testHasValueChangesForFileWrite_excludesTags() { + newMeta.setTags(Set.of("New Tag")); + boolean result = MetadataChangeDetector.hasValueChangesForFileWrite(newMeta, existingMeta, clearFlags); + assertFalse(result, "Tags should not trigger file write"); + } + + @Test + void testHasValueChangesForFileWrite_excludesRatingFields() { + newMeta.setAmazonRating(4.9); + newMeta.setGoodreadsRating(4.8); + newMeta.setHardcoverRating(4.7); + newMeta.setAmazonReviewCount(2000); + newMeta.setGoodreadsReviewCount(35000); + newMeta.setHardcoverReviewCount(800); + boolean result = MetadataChangeDetector.hasValueChangesForFileWrite(newMeta, existingMeta, clearFlags); + assertFalse(result, "Rating and review count fields should not trigger file write"); + } + + @Test + void testHasValueChangesForFileWrite_includesAuthors() { + newMeta.setAuthors(Set.of("New Author")); + boolean result = MetadataChangeDetector.hasValueChangesForFileWrite(newMeta, existingMeta, clearFlags); + assertTrue(result, "Authors change should trigger file write"); + } + + @Test + void testHasValueChangesForFileWrite_includesCategories() { + newMeta.setCategories(Set.of("New Category")); + boolean result = MetadataChangeDetector.hasValueChangesForFileWrite(newMeta, existingMeta, clearFlags); + assertTrue(result, "Categories change should trigger file write"); + } + + @Test + void testIsDifferent_whenBothSubtitleValuesNull_returnsFalse() { + existingMeta.setSubtitle(null); + newMeta.setSubtitle(null); + + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertFalse(result, "Should return false when both values are null"); + } + + @Test + void testIsDifferent_whenMultipleFieldsChange_returnsTrue() { + newMeta.setTitle("New Title"); + newMeta.setSubtitle("New Subtitle"); + newMeta.setPublisher("New Publisher"); + newMeta.setPageCount(999); + + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertTrue(result, "Should return true when multiple fields change simultaneously"); + } + + @Test + void testEdgeCase_whitespaceNormalization() { + existingMeta.setTitle(" Original Title "); + newMeta.setTitle("Original Title"); + boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); + assertFalse(result, "Should return false when strings are equal after whitespace normalization"); + } +}