1
0
mirror of https://github.com/Stirling-Tools/Stirling-PDF.git synced 2024-11-14 11:30:12 +01:00

Merge pull request #1385 from jimdouk/main

Enhance Test Coverage for SPDF/Utils Classes
This commit is contained in:
Anthony Stirling 2024-06-07 09:38:56 +01:00 committed by GitHub
commit fc0878704d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 580 additions and 0 deletions

View File

@ -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"));
}
}

View File

@ -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);
});
}
}

View File

@ -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());
}
}
}
}

View File

@ -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<COSName> 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);
}
}

View File

@ -0,0 +1,55 @@
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<String> 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<String> command = new ArrayList<>();
command.add("nonexistent-command");
// Execute the command and expect an IOException
IOException thrown = assertThrows(IOException.class, () -> {
processExecutor.runCommandWithOutputHandling(command);
});
// Log the actual error message
System.out.println("Caught IOException: " + thrown.getMessage());
// Check the exception message to ensure it indicates the command was not found
String errorMessage = thrown.getMessage();
assertTrue(errorMessage.contains("error=2") || errorMessage.contains("No such file or directory"), "Unexpected error message: " + errorMessage);
}
}

View File

@ -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<String> 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<String> 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);
}
}

View File

@ -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"));
}
}

View File

@ -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());
}
}

View File

@ -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);
}
}

View File

@ -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<byte[]> 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<byte[]> 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<byte[]> 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<byte[]> 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());
}
}
}