Skip to content

Commit

Permalink
update test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
quanpham-axonivy committed Dec 16, 2024
1 parent c02eb3b commit cc64d49
Show file tree
Hide file tree
Showing 4 changed files with 145 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
public class LoggableAspect {

@Value("${loggable.log-path}")
private String logFilePath;
public String logFilePath;

private static final String REQUESTED_BY = "marketplace-website";

Expand Down Expand Up @@ -58,7 +58,7 @@ private Map<String, String> extractHeaders(HttpServletRequest request, MethodSig
"timestamp", escapeXml(getCurrentTimestamp()),
"user-agent", escapeXml(request.getHeader(CommonConstants.USER_AGENT)),
"arguments", escapeXml(getArgumentsString(signature.getParameterNames(), joinPoint.getArgs())),
"x-requested-by", escapeXml(request.getHeader(CommonConstants.REQUESTED_BY))
"X-Requested-By", escapeXml(request.getHeader(CommonConstants.REQUESTED_BY))
);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package com.axonivy.market.logging;

import com.axonivy.market.constants.CommonConstants;
import com.axonivy.market.exceptions.model.MissingHeaderException;
import com.axonivy.market.util.LoggingUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class LoggableAspectTest {

@Mock
private HttpServletRequest request;

private LoggableAspect loggableAspect;

@BeforeEach
void setUp() throws IOException {
MockitoAnnotations.openMocks(this);
loggableAspect = new LoggableAspect();
loggableAspect.logFilePath = Files.createTempDirectory("logs").toString(); // Use temp directory for tests
}

@Test
void testLogFileCreation() throws Exception {
mockRequestAttributes("marketplace-website", "test-agent");
MethodSignature signature = mockMethodSignature();

loggableAspect.logMethodCall(mockJoinPoint(signature));

Path logFilePath = Path.of(loggableAspect.logFilePath, "log-" + LoggingUtils.getCurrentDate() + ".xml");
assertTrue(Files.exists(logFilePath), "Log file should be created");

String content = Files.readString(logFilePath);
assertTrue(content.contains("<Logs>"), "Log file should contain log entries");
}

@Test
void testMissingHeaderException() {
mockRequestAttributes("invalid-source", "mock-agent");
MethodSignature signature = mockMethodSignature();

assertThrows(MissingHeaderException.class, () -> {
loggableAspect.logMethodCall(mockJoinPoint(signature));
});
}

private JoinPoint mockJoinPoint(MethodSignature signature) {
JoinPoint joinPoint = mock(JoinPoint.class);
when(joinPoint.getSignature()).thenReturn(signature);
when(joinPoint.getArgs()).thenReturn(new Object[]{"arg1", "arg2"}); // Example arguments
return joinPoint;
}

private void mockRequestAttributes(String requestedBy, String userAgent) {
when(request.getHeader(CommonConstants.REQUESTED_BY)).thenReturn(requestedBy);
when(request.getHeader(CommonConstants.USER_AGENT)).thenReturn(userAgent);
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
}

private MethodSignature mockMethodSignature() {
MethodSignature signature = mock(MethodSignature.class);
when(signature.getMethod()).thenReturn(this.getClass().getMethods()[0]); // Use any available method
return signature;
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.axonivy.market.util;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
Expand All @@ -9,6 +8,8 @@
import java.io.IOException;
import java.nio.file.Files;

import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(MockitoExtension.class)
class FileUtilsTest {

Expand All @@ -17,20 +18,40 @@ class FileUtilsTest {
@Test
void testCreateFile() throws IOException {
File createdFile = FileUtils.createFile(FILE_PATH);
Assertions.assertTrue(createdFile.exists(), "File should exist");
Assertions.assertTrue(createdFile.isFile(), "Should be a file");
assertTrue(createdFile.exists(), "File should exist");
assertTrue(createdFile.isFile(), "Should be a file");

createdFile.delete();
}

@Test
void testFailedToCreateDirectory() throws IOException {
File createdFile = new File("testDirAsFile");
try {
if (!createdFile.exists()) {
assertTrue(createdFile.createNewFile(), "Setup failed: could not create file");
}

IOException exception = assertThrows(IOException.class, () -> {
FileUtils.createFile("testDirAsFile/subDir/testFile.txt");
});
assertTrue(exception.getMessage().contains("Failed to create directory"),
"Exception message does not contain expected text");
} catch (IOException e) {
fail("Setup failed: " + e.getMessage());
} finally {
createdFile.delete();
}
}

@Test
void testWriteFile() throws IOException {
File createdFile = FileUtils.createFile(FILE_PATH);
String content = "Hello, world!";
FileUtils.writeToFile(createdFile, content);

String fileContent = Files.readString(createdFile.toPath());
Assertions.assertEquals(content, fileContent, "File content should match the written content");
assertEquals(content, fileContent, "File content should match the written content");

createdFile.delete();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,43 @@
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

@ExtendWith(MockitoExtension.class)
class LoggingUtilsTest {

@Test
void testEscapeXml() {
void testEscapeXmlSuccess() {
String input = "<Test'& \"Method>";
String expectedValue = "&lt;Test&apos;&amp; &quot;Method&gt;";
String result = LoggingUtils.escapeXml(input);
Assertions.assertEquals(expectedValue, result);
}

@Test
void testEscapeXmlOnNullValue() {
String expectedValue = "";
String result = LoggingUtils.escapeXml(null);
Assertions.assertEquals(expectedValue, result);
}

@Test
void testGetArgumentsString() {
String expectedValue = "a: random, b: sample";
String result = LoggingUtils.getArgumentsString(new String[]{"a", "b"}, new String[]{"random", "sample"});
Assertions.assertEquals(expectedValue, result);
}

@Test
void testGetArgumentsStringOnNullValue() {
String expectedValue = "No arguments";
String result = LoggingUtils.getArgumentsString(null, null);
Assertions.assertEquals(expectedValue, result);
}

@Test
void testBuildLogEntry() {
Map<String, String> given = Map.of(
Expand All @@ -43,4 +60,22 @@ void testBuildLogEntry() {
Assertions.assertEquals(expected, result);
}

@Test
void testGetCurrentDate() {
String expectedDate = LocalDate.now().toString();
String actualDate = LoggingUtils.getCurrentDate();

Assertions.assertEquals(expectedDate, actualDate, "The returned date does not match the current date");
}

@Test
void testGetCurrentTimestamp() {
String expectedTimestamp = LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String actualTimestamp = LoggingUtils.getCurrentTimestamp();

Assertions.assertEquals(expectedTimestamp.substring(0, 19), actualTimestamp.substring(0, 19),
"The returned timestamp does not match the expected format or value");
}

}

0 comments on commit cc64d49

Please sign in to comment.