From 5277cf2b59263f309b3e5de7283fe19d53a842d8 Mon Sep 17 00:00:00 2001 From: jimdouk Date: Thu, 6 Jun 2024 12:54:12 +0300 Subject: [PATCH] Add junit tests for utils classes --- .../software/SPDF/utils/ErrorUtilsTest.java | 45 +++++++ .../software/SPDF/utils/FileToPdfTest.java | 36 ++++++ .../SPDF/utils/ImageProcessingUtilsTest.java | 76 ++++++++++++ .../software/SPDF/utils/PdfUtilsTest.java | 60 ++++++++++ .../SPDF/utils/ProcessExecutorTest.java | 51 ++++++++ .../SPDF/utils/PropertyConfigsTest.java | 69 +++++++++++ .../SPDF/utils/RequestUriUtilsTest.java | 26 ++++ .../SPDF/utils/SPdfApplicationTest.java | 76 ++++++++++++ .../software/SPDF/utils/UrlUtilsTest.java | 26 ++++ .../SPDF/utils/WebResponseUtilsTest.java | 111 ++++++++++++++++++ 10 files changed, 576 insertions(+) create mode 100644 src/test/java/stirling/software/SPDF/utils/ErrorUtilsTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/FileToPdfTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/ImageProcessingUtilsTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/PdfUtilsTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/ProcessExecutorTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/PropertyConfigsTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/RequestUriUtilsTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/SPdfApplicationTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/UrlUtilsTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/WebResponseUtilsTest.java diff --git a/src/test/java/stirling/software/SPDF/utils/ErrorUtilsTest.java b/src/test/java/stirling/software/SPDF/utils/ErrorUtilsTest.java new file mode 100644 index 00000000..414540dd --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/ErrorUtilsTest.java @@ -0,0 +1,45 @@ +package stirling.software.SPDF.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.springframework.ui.Model; +import org.springframework.web.servlet.ModelAndView; + +public class ErrorUtilsTest { + + @Test + public void testExceptionToModel() { + // Create a mock Model + Model model = new org.springframework.ui.ExtendedModelMap(); + + // Create a test exception + Exception ex = new Exception("Test Exception"); + + // Call the method under test + Model resultModel = ErrorUtils.exceptionToModel(model, ex); + + // Verify the result + assertNotNull(resultModel); + assertEquals("Test Exception", resultModel.getAttribute("errorMessage")); + assertNotNull(resultModel.getAttribute("stackTrace")); + } + + @Test + public void testExceptionToModelView() { + // Create a mock Model + Model model = new org.springframework.ui.ExtendedModelMap(); + + // Create a test exception + Exception ex = new Exception("Test Exception"); + + // Call the method under test + ModelAndView modelAndView = ErrorUtils.exceptionToModelView(model, ex); + + // Verify the result + assertNotNull(modelAndView); + assertEquals("Test Exception", modelAndView.getModel().get("errorMessage")); + assertNotNull(modelAndView.getModel().get("stackTrace")); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/FileToPdfTest.java b/src/test/java/stirling/software/SPDF/utils/FileToPdfTest.java new file mode 100644 index 00000000..66c19539 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/FileToPdfTest.java @@ -0,0 +1,36 @@ +package stirling.software.SPDF.utils; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; + +import org.junit.jupiter.api.Test; + +import stirling.software.SPDF.model.api.converters.HTMLToPdfRequest; + +public class FileToPdfTest { + + @Test + public void testConvertHtmlToPdf() { + HTMLToPdfRequest request = new HTMLToPdfRequest(); + byte[] fileBytes = new byte[10]; // Sample file bytes + String fileName = "test.html"; // Sample file name + boolean htmlFormatsInstalled = true; // Sample boolean value + + // Check if the method throws IOException + assertThrows(IOException.class, () -> { + FileToPdf.convertHtmlToPdf(request, fileBytes, fileName, htmlFormatsInstalled); + }); + } + + @Test + public void testConvertBookTypeToPdf() { + byte[] bytes = new byte[10]; // Sample bytes + String originalFilename = "test.epub"; // Sample original filename + + // Check if the method throws IOException + assertThrows(IOException.class, () -> { + FileToPdf.convertBookTypeToPdf(bytes, originalFilename); + }); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/ImageProcessingUtilsTest.java b/src/test/java/stirling/software/SPDF/utils/ImageProcessingUtilsTest.java new file mode 100644 index 00000000..da990c1c --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/ImageProcessingUtilsTest.java @@ -0,0 +1,76 @@ +package stirling.software.SPDF.utils; + +import org.junit.jupiter.api.Test; + +import java.awt.image.BufferedImage; +import java.awt.Color; + +import static org.junit.jupiter.api.Assertions.*; + +public class ImageProcessingUtilsTest { + + @Test + void testConvertColorTypeToGreyscale() { + BufferedImage sourceImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); + fillImageWithColor(sourceImage, Color.RED); + + BufferedImage convertedImage = ImageProcessingUtils.convertColorType(sourceImage, "greyscale"); + + assertNotNull(convertedImage); + assertEquals(BufferedImage.TYPE_BYTE_GRAY, convertedImage.getType()); + assertEquals(sourceImage.getWidth(), convertedImage.getWidth()); + assertEquals(sourceImage.getHeight(), convertedImage.getHeight()); + + // Check if a pixel is correctly converted to greyscale + Color grey = new Color(convertedImage.getRGB(0, 0)); + assertEquals(grey.getRed(), grey.getGreen()); + assertEquals(grey.getGreen(), grey.getBlue()); + } + + @Test + void testConvertColorTypeToBlackWhite() { + BufferedImage sourceImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); + fillImageWithColor(sourceImage, Color.RED); + + BufferedImage convertedImage = ImageProcessingUtils.convertColorType(sourceImage, "blackwhite"); + + assertNotNull(convertedImage); + assertEquals(BufferedImage.TYPE_BYTE_BINARY, convertedImage.getType()); + assertEquals(sourceImage.getWidth(), convertedImage.getWidth()); + assertEquals(sourceImage.getHeight(), convertedImage.getHeight()); + + // Check if a pixel is converted correctly (binary image will be either black or white) + int rgb = convertedImage.getRGB(0, 0); + assertTrue(rgb == Color.BLACK.getRGB() || rgb == Color.WHITE.getRGB()); + } + + @Test + void testConvertColorTypeToFullColor() { + BufferedImage sourceImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); + fillImageWithColor(sourceImage, Color.RED); + + BufferedImage convertedImage = ImageProcessingUtils.convertColorType(sourceImage, "fullcolor"); + + assertNotNull(convertedImage); + assertEquals(sourceImage, convertedImage); + } + + @Test + void testConvertColorTypeInvalid() { + BufferedImage sourceImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); + fillImageWithColor(sourceImage, Color.RED); + + BufferedImage convertedImage = ImageProcessingUtils.convertColorType(sourceImage, "invalidtype"); + + assertNotNull(convertedImage); + assertEquals(sourceImage, convertedImage); + } + + private void fillImageWithColor(BufferedImage image, Color color) { + for (int y = 0; y < image.getHeight(); y++) { + for (int x = 0; x < image.getWidth(); x++) { + image.setRGB(x, y, color.getRGB()); + } + } + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/PdfUtilsTest.java b/src/test/java/stirling/software/SPDF/utils/PdfUtilsTest.java new file mode 100644 index 00000000..03a52663 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/PdfUtilsTest.java @@ -0,0 +1,60 @@ +package stirling.software.SPDF.utils; + +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.pdmodel.PDResources; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import stirling.software.SPDF.model.PdfMetadata; + +import java.io.IOException; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.*; +import org.apache.pdfbox.pdmodel.common.PDRectangle; +import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; +import org.apache.pdfbox.cos.COSName; + +public class PdfUtilsTest { + + @Test + void testTextToPageSize() { + assertEquals(PDRectangle.A4, PdfUtils.textToPageSize("A4")); + assertEquals(PDRectangle.LETTER, PdfUtils.textToPageSize("LETTER")); + assertThrows(IllegalArgumentException.class, () -> PdfUtils.textToPageSize("INVALID")); + } + + @Test + void testHasImagesOnPage() throws IOException { + // Mock a PDPage and its resources + PDPage page = Mockito.mock(PDPage.class); + PDResources resources = Mockito.mock(PDResources.class); + Mockito.when(page.getResources()).thenReturn(resources); + + // Case 1: No images in resources + Mockito.when(resources.getXObjectNames()).thenReturn(Collections.emptySet()); + assertFalse(PdfUtils.hasImagesOnPage(page)); + + // Case 2: Resources with an image + Set xObjectNames = new HashSet<>(); + COSName cosName = Mockito.mock(COSName.class); + xObjectNames.add(cosName); + + PDImageXObject imageXObject = Mockito.mock(PDImageXObject.class); + Mockito.when(resources.getXObjectNames()).thenReturn(xObjectNames); + Mockito.when(resources.getXObject(cosName)).thenReturn(imageXObject); + + assertTrue(PdfUtils.hasImagesOnPage(page)); + } + + @Test + void testExtractMetadataFromPdf() throws IOException { + PDDocument document = Mockito.mock(PDDocument.class); + Mockito.when(document.getDocumentInformation()).thenReturn(Mockito.mock(org.apache.pdfbox.pdmodel.PDDocumentInformation.class)); + PdfMetadata metadata = PdfUtils.extractMetadataFromPdf(document); + + assertNotNull(metadata); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/ProcessExecutorTest.java b/src/test/java/stirling/software/SPDF/utils/ProcessExecutorTest.java new file mode 100644 index 00000000..02f846c7 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/ProcessExecutorTest.java @@ -0,0 +1,51 @@ +package stirling.software.SPDF.utils; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class ProcessExecutorTest { + + private ProcessExecutor processExecutor; + + @BeforeEach + public void setUp() { + // Initialize the ProcessExecutor instance + processExecutor = ProcessExecutor.getInstance(ProcessExecutor.Processes.LIBRE_OFFICE); + } + + @Test + public void testRunCommandWithOutputHandling() throws IOException, InterruptedException { + // Mock the command to execute + List command = new ArrayList<>(); + command.add("java"); + command.add("-version"); + + // Execute the command + ProcessExecutor.ProcessExecutorResult result = processExecutor.runCommandWithOutputHandling(command); + + // Check the exit code and output messages + assertEquals(0, result.getRc()); + assertNotNull(result.getMessages()); // Check if messages are not null + } + + @Test + public void testRunCommandWithOutputHandling_Error() { + // Mock the command to execute + List command = new ArrayList<>(); + command.add("nonexistent-command"); + + // Execute the command and expect an IOException + IOException thrown = assertThrows(IOException.class, () -> { + processExecutor.runCommandWithOutputHandling(command); + }); + + // Check the exception message to ensure it is about the nonexistent command + assertTrue(thrown.getMessage().contains("CreateProcess error=2, The system cannot find the file specified")); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/PropertyConfigsTest.java b/src/test/java/stirling/software/SPDF/utils/PropertyConfigsTest.java new file mode 100644 index 00000000..7909f1d9 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/PropertyConfigsTest.java @@ -0,0 +1,69 @@ +package stirling.software.SPDF.utils; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PropertyConfigsTest { + + @Test + public void testGetBooleanValue_WithKeys() { + // Define keys and default value + List keys = Arrays.asList("test.key1", "test.key2", "test.key3"); + boolean defaultValue = false; + + // Set property for one of the keys + System.setProperty("test.key2", "true"); + + // Call the method under test + boolean result = PropertyConfigs.getBooleanValue(keys, defaultValue); + + // Verify the result + assertEquals(true, result); + } + + @Test + public void testGetStringValue_WithKeys() { + // Define keys and default value + List keys = Arrays.asList("test.key1", "test.key2", "test.key3"); + String defaultValue = "default"; + + // Set property for one of the keys + System.setProperty("test.key2", "value"); + + // Call the method under test + String result = PropertyConfigs.getStringValue(keys, defaultValue); + + // Verify the result + assertEquals("value", result); + } + + @Test + public void testGetBooleanValue_WithKey() { + // Define key and default value + String key = "test.key"; + boolean defaultValue = true; + + // Call the method under test + boolean result = PropertyConfigs.getBooleanValue(key, defaultValue); + + // Verify the result + assertEquals(true, result); + } + + @Test + public void testGetStringValue_WithKey() { + // Define key and default value + String key = "test.key"; + String defaultValue = "default"; + + // Call the method under test + String result = PropertyConfigs.getStringValue(key, defaultValue); + + // Verify the result + assertEquals("default", result); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/RequestUriUtilsTest.java b/src/test/java/stirling/software/SPDF/utils/RequestUriUtilsTest.java new file mode 100644 index 00000000..5fdf5856 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/RequestUriUtilsTest.java @@ -0,0 +1,26 @@ +package stirling.software.SPDF.utils; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +public class RequestUriUtilsTest { + + @Test + public void testIsStaticResource() { + assertTrue(RequestUriUtils.isStaticResource("/css/styles.css")); + assertTrue(RequestUriUtils.isStaticResource("/js/script.js")); + assertTrue(RequestUriUtils.isStaticResource("/images/logo.png")); + assertTrue(RequestUriUtils.isStaticResource("/public/index.html")); + assertTrue(RequestUriUtils.isStaticResource("/pdfjs/pdf.worker.js")); + assertTrue(RequestUriUtils.isStaticResource("/api/v1/info/status")); + assertTrue(RequestUriUtils.isStaticResource("/some-path/icon.svg")); + assertFalse(RequestUriUtils.isStaticResource("/api/v1/users")); + assertFalse(RequestUriUtils.isStaticResource("/api/v1/orders")); + assertFalse(RequestUriUtils.isStaticResource("/")); + assertFalse(RequestUriUtils.isStaticResource("/login")); + assertFalse(RequestUriUtils.isStaticResource("/register")); + assertFalse(RequestUriUtils.isStaticResource("/api/v1/products")); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/SPdfApplicationTest.java b/src/test/java/stirling/software/SPDF/utils/SPdfApplicationTest.java new file mode 100644 index 00000000..e37e74b6 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/SPdfApplicationTest.java @@ -0,0 +1,76 @@ +package stirling.software.SPDF.utils; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.core.env.Environment; + +import stirling.software.SPDF.SPdfApplication; +import stirling.software.SPDF.model.ApplicationProperties; + +@ExtendWith(MockitoExtension.class) +public class SPdfApplicationTest { + + @Mock + private Environment env; + + @Mock + private ApplicationProperties applicationProperties; + + @InjectMocks + private SPdfApplication sPdfApplication; + + @BeforeEach + public void setUp() { + sPdfApplication = new SPdfApplication(); + sPdfApplication.setServerPortStatic("8080"); + } + + @Test + public void testSetServerPortStatic() { + sPdfApplication.setServerPortStatic("9090"); + assertEquals("9090", SPdfApplication.getStaticPort()); + } + + @Test + public void testMainApplicationStartup() throws IOException, InterruptedException { + // Setup mock environment for the main method + Path settingsPath = Paths.get("configs/settings.yml"); + Path customSettingsPath = Paths.get("configs/custom_settings.yml"); + + // Ensure the files do not exist for the test + if (Files.exists(settingsPath)) { + Files.delete(settingsPath); + } + if (Files.exists(customSettingsPath)) { + Files.delete(customSettingsPath); + } + + // Run the main method + SPdfApplication.main(new String[]{}); + + // Verify that the directories were created + assertTrue(Files.exists(Path.of("customFiles/static/"))); + assertTrue(Files.exists(Path.of("customFiles/templates/"))); + } + + @Test + public void testGetStaticPort() { + assertEquals("8080", SPdfApplication.getStaticPort()); + } + + @Test + public void testGetNonStaticPort() { + assertEquals("8080", sPdfApplication.getNonStaticPort()); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/UrlUtilsTest.java b/src/test/java/stirling/software/SPDF/utils/UrlUtilsTest.java new file mode 100644 index 00000000..c17c0e74 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/UrlUtilsTest.java @@ -0,0 +1,26 @@ +package stirling.software.SPDF.utils; + +import jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class UrlUtilsTest { + + @Test + void testGetOrigin() { + // Mock HttpServletRequest + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Mockito.when(request.getScheme()).thenReturn("http"); + Mockito.when(request.getServerName()).thenReturn("localhost"); + Mockito.when(request.getServerPort()).thenReturn(8080); + Mockito.when(request.getContextPath()).thenReturn("/myapp"); + + // Call the method under test + String origin = UrlUtils.getOrigin(request); + + // Assert the result + assertEquals("http://localhost:8080/myapp", origin); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/WebResponseUtilsTest.java b/src/test/java/stirling/software/SPDF/utils/WebResponseUtilsTest.java new file mode 100644 index 00000000..68ff619d --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/WebResponseUtilsTest.java @@ -0,0 +1,111 @@ +package stirling.software.SPDF.utils; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.apache.pdfbox.pdmodel.PDDocument; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockMultipartFile; + +public class WebResponseUtilsTest { + + @Test + public void testBoasToWebResponse() { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + baos.write("Sample PDF content".getBytes()); + String docName = "sample.pdf"; + + ResponseEntity responseEntity = WebResponseUtils.boasToWebResponse(baos, docName); + + assertNotNull(responseEntity); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + + HttpHeaders headers = responseEntity.getHeaders(); + assertNotNull(headers); + assertEquals(MediaType.APPLICATION_PDF, headers.getContentType()); + assertNotNull(headers.getContentDisposition()); + //assertEquals("attachment; filename=\"sample.pdf\"", headers.getContentDisposition().toString()); + + } catch (IOException e) { + fail("Exception thrown: " + e.getMessage()); + } + } + + @Test + public void testMultiPartFileToWebResponse() { + try { + byte[] fileContent = "Sample file content".getBytes(); + MockMultipartFile file = new MockMultipartFile("file", "sample.txt", "text/plain", fileContent); + + ResponseEntity responseEntity = WebResponseUtils.multiPartFileToWebResponse(file); + + assertNotNull(responseEntity); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + + HttpHeaders headers = responseEntity.getHeaders(); + assertNotNull(headers); + assertEquals(MediaType.TEXT_PLAIN, headers.getContentType()); + assertNotNull(headers.getContentDisposition()); + + } catch (IOException e) { + fail("Exception thrown: " + e.getMessage()); + } + } + + @Test + public void testBytesToWebResponse() { + try { + byte[] bytes = "Sample bytes".getBytes(); + String docName = "sample.txt"; + MediaType mediaType = MediaType.TEXT_PLAIN; + + ResponseEntity responseEntity = WebResponseUtils.bytesToWebResponse(bytes, docName, mediaType); + + assertNotNull(responseEntity); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + + HttpHeaders headers = responseEntity.getHeaders(); + assertNotNull(headers); + assertEquals(MediaType.TEXT_PLAIN, headers.getContentType()); + assertNotNull(headers.getContentDisposition()); + + + } catch (IOException e) { + fail("Exception thrown: " + e.getMessage()); + } + } + + @Test + public void testPdfDocToWebResponse() { + try { + PDDocument document = new PDDocument(); + document.addPage(new org.apache.pdfbox.pdmodel.PDPage()); + String docName = "sample.pdf"; + + ResponseEntity responseEntity = WebResponseUtils.pdfDocToWebResponse(document, docName); + + assertNotNull(responseEntity); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + + HttpHeaders headers = responseEntity.getHeaders(); + assertNotNull(headers); + assertEquals(MediaType.APPLICATION_PDF, headers.getContentType()); + assertNotNull(headers.getContentDisposition()); + + + } catch (IOException e) { + fail("Exception thrown: " + e.getMessage()); + } + } +}