Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Test fix #51

Merged
merged 2 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package it.gov.pagopa.common.configuration;
package it.gov.pagopa.common.mongo;

import com.mongodb.lang.NonNull;
import it.gov.pagopa.common.utils.CommonConstants;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package it.gov.pagopa.common.configuration;
package it.gov.pagopa.common.mongo;

import it.gov.pagopa.common.configuration.CustomReactiveMongoHealthIndicator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
Expand Down
2 changes: 0 additions & 2 deletions src/main/java/it/gov/pagopa/common/web/dto/ErrorDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,12 @@
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

@JsonInclude(JsonInclude.Include.NON_NULL)
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode
public class ErrorDTO implements ServiceExceptionPayload {

@NotBlank
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ public MessageProducer(StreamBridge streamBridge,
public void scheduleMessage(Message<MessageDTO> message) {
String messageId = message.getPayload().getMessageId();
log.info("[MESSAGE-CORE][SCHEDULE-MESSAGE] Scheduling message ID: {} to messageSenderQueue", messageId);

streamBridge.send("messageSender-out-0", binder, message);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,9 @@ public Mono<Void> enqueueMessage(MessageDTO messageDTO) {
log.info("[MESSAGE-PRODUCER][ENQUEUE] Enqueuing message with ID: {}", messageDTO.getMessageId());

return Mono.fromRunnable(() -> {
try {
Message<MessageDTO> message = createMessage(messageDTO);
log.info("[MESSAGE-PRODUCER][ENQUEUE] Message with ID: {} successfully created. Sending to message queue.", messageDTO.getMessageId());
messageProducer.scheduleMessage(message);
} catch (Exception e) {
log.error("[MESSAGE-PRODUCER][ENQUEUE] Error while creating or sending message with ID: {}. Error: {}", messageDTO.getMessageId(), e.getMessage());
}
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
class PerformanceLoggerTest {

//region mono ops
@Test
void testMonoLogTimingOnNext(){
testMonoLogTimingOnNext(null);
testMonoLogTimingOnNext(Object::toString);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,37 @@
package it.gov.pagopa.common.utils;



import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectReader;
import it.gov.pagopa.common.web.exception.EmdEncryptionException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.function.Consumer;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class CommonUtilitiesTest {

@Mock
private Message<String> messageMock;
@Mock
private ObjectReader objectReaderMock;

@Test
void createSHA256_Ko_NoSuchAlgorithm() {
try (MockedStatic<MessageDigest> mockedStatic = Mockito.mockStatic(MessageDigest.class)) {
Expand All @@ -30,12 +43,86 @@ void createSHA256_Ko_NoSuchAlgorithm() {
assertEquals("SHA-256 not available", exception.getCause().getMessage());
}
}

@Test
void createSHA256_Ok(){
void createSHA256_Ok() {
String toHash = "RSSMRA98B18L049O";
String hashedExpected = "0b393cbe68a39f26b90c80a8dc95abc0fe4c21821195b4671a374c1443f9a1bb";
String actualHash = CommonUtilities.createSHA256(toHash);
assertEquals(actualHash,hashedExpected);
assertEquals(hashedExpected, actualHash);
}

@Test
void deserializeMessage_Ko_JsonProcessingException() {
Consumer<Throwable> errorHandler = e -> Assertions.assertTrue(e instanceof JsonProcessingException);
when(messageMock.getPayload()).thenReturn("invalid payload");

try {
when(objectReaderMock.readValue("invalid payload")).thenThrow(new JsonProcessingException("Invalid JSON") {});

// Act
Object result = CommonUtilities.deserializeMessage(messageMock, objectReaderMock, errorHandler);

// Assert
Assertions.assertNull(result);
} catch (JsonProcessingException e) {
Assertions.fail("Exception should be handled in the method");
}
}

@Test
void deserializeMessage_Ok() {
// Setup
String validJson = "{\"name\":\"John\"}";
MyObject expectedObject = new MyObject("John");
Consumer<Throwable> errorHandler = e -> Assertions.fail("Should not have thrown an error");

when(messageMock.getPayload()).thenReturn(validJson);
try {
when(objectReaderMock.readValue(validJson)).thenReturn(expectedObject);

MyObject result = CommonUtilities.deserializeMessage(messageMock, objectReaderMock, errorHandler);

Assertions.assertNotNull(result);
assertEquals(expectedObject.name(), result.name());
} catch (JsonProcessingException e) {
Assertions.fail("Exception should not be thrown");
}
}

@Test
void readMessagePayload_StringPayload() {
String expectedPayload = "test message";
when(messageMock.getPayload()).thenReturn(expectedPayload);

String actualPayload = CommonUtilities.readMessagePayload(messageMock);

assertEquals(expectedPayload, actualPayload);
}

@Test
void getHeaderValue_Test() {
String headerName = "testHeader";
String headerValue = "headerValue";
MessageHeaders headers = new MessageHeaders(Map.of(headerName, headerValue));

when(messageMock.getHeaders()).thenReturn(headers);

Object result = CommonUtilities.getHeaderValue(messageMock, headerName);

assertEquals(headerValue, result);
}

@Test
void getByteArrayHeaderValue_Test() {
String headerName = "byteArrayHeader";
String headerValue = "headerValue";
MessageHeaders headers = new MessageHeaders(Map.of(headerName, headerValue.getBytes(StandardCharsets.UTF_8)));
when(messageMock.getHeaders()).thenReturn(headers);

String result = CommonUtilities.getByteArrayHeaderValue(messageMock, headerName);

assertEquals(headerValue, result);
}
record MyObject(String name) { }
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,39 @@ void handleExceptionClientExceptionNoBody() {

checkStackTraceSuppressedLog(memoryAppender,
"A ClientExceptionNoBody occurred handling request GET /test: HttpStatus 400 BAD_REQUEST - NOTFOUND ClientExceptionNoBody at it.gov.pagopa.common.web.exception.ErrorManagerTest\\$TestController.testEndpoint\\(ErrorManagerTest.java:[0-9]+\\)");

memoryAppender.reset();

Throwable throwable = new Exception("Cause of the exception");

Mockito.doThrow(
new ClientExceptionNoBody(HttpStatus.BAD_REQUEST, "ClientExceptionNoBody with Throwable", throwable))
.when(testControllerSpy).testEndpoint();

webTestClient.get()
.uri("/test")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isBadRequest();

checkStackTraceSuppressedLog(memoryAppender,
"Something went wrong handling request GET /test: HttpStatus 400 BAD_REQUEST - ClientExceptionNoBody with Throwable");

memoryAppender.reset();

Mockito.doThrow(
new ClientExceptionNoBody(HttpStatus.BAD_REQUEST, "ClientExceptionNoBody", true, throwable))
.when(testControllerSpy).testEndpoint();

webTestClient.get()
.uri("/test")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isBadRequest();

checkStackTraceSuppressedLog(memoryAppender,
"Something went wrong handling request GET /test: HttpStatus 400 BAD_REQUEST - ClientExceptionNoBody");

}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ static class ValidationDTO {
@Test
void testHandleValueNotValidException() {
String invalidJson = "{}";

webTestClient.put()
.uri("/test")
.contentType(MediaType.APPLICATION_JSON)
Expand All @@ -69,16 +68,13 @@ void testHandleValueNotValidException() {
}
@Test
void testHandleHeaderNotValidException() {
String invalidJson = "{}";

webTestClient.put()
.uri("/test")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(new ValidationDTO("data"))
.exchange()
.expectStatus().isBadRequest()
.expectBody(ErrorDTO.class)

.consumeWith(response -> {
ErrorDTO errorDTO = response.getResponseBody();
assertThat(errorDTO).isNotNull();
Expand All @@ -87,4 +83,21 @@ void testHandleHeaderNotValidException() {

});
}

@Test
void testHandleNoResourceFoundException() {
webTestClient.put()
.uri("/test/missing")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(new ValidationDTO("someData"))
.exchange()
.expectStatus().isNotFound() // Expect 404 Not Found
.expectBody(ErrorDTO.class)
.consumeWith(response -> {
ErrorDTO errorDTO = response.getResponseBody();
assertThat(errorDTO).isNotNull();
assertThat(errorDTO.getCode()).isEqualTo("INVALID_REQUEST"); // Check the code from ErrorDTO
assertThat(errorDTO.getMessage()).isEqualTo("Invalid request"); // Check the message from ErrorDTO
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import java.io.IOException;

import static it.gov.pagopa.message.utils.TestUtils.FISCAL_CODE;
import static it.gov.pagopa.message.utils.TestUtils.RESPONSE;
import static org.assertj.core.api.Assertions.assertThat;

@ExtendWith(MockitoExtension.class)
class CitizenConnectorImplTest {
Expand All @@ -42,10 +41,10 @@ void testCheckFiscalCode() {
.setBody(RESPONSE)
.addHeader("Content-Type", "application/json"));

Mono<String> resultMono = citizenConnector.checkFiscalCode(FISCAL_CODE);

String result = resultMono.block();
assertThat(result).isEqualTo(RESPONSE);
StepVerifier.create(citizenConnector.checkFiscalCode(FISCAL_CODE))
.expectNext(RESPONSE)
.verifyComplete();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,10 @@ class MessageProducerTest {
@InjectMocks
private MessageProducer messageProducer;



@Test
void testStreamBridgeSendCalled() {
messageProducer.scheduleMessage(QUEUE_MESSAGE);
verify(streamBridge, times(1)).send(eq("messageSender-out-0"), any(), eq(QUEUE_MESSAGE));

}
}

Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package it.gov.pagopa.message.service;

import it.gov.pagopa.message.connector.CitizenConnectorImpl;

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 @@ -11,6 +9,7 @@
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import static it.gov.pagopa.message.utils.TestUtils.FISCAL_CODE;
import static it.gov.pagopa.message.utils.TestUtils.MESSAGE_DTO;
Expand All @@ -35,17 +34,20 @@ void sendMessage_Ok() {
when(citizenConnector.checkFiscalCode(FISCAL_CODE)).thenReturn(Mono.just("OK"));
when(messageProducerService.enqueueMessage(MESSAGE_DTO)).thenReturn(Mono.empty());

Boolean result = messageCoreService.send(MESSAGE_DTO).block();
Assertions.assertEquals(true, result);

StepVerifier.create(messageCoreService.send(MESSAGE_DTO))
.expectNext(true)
.verifyComplete();

}

@Test
void sendMessage_Ko() {
when(citizenConnector.checkFiscalCode(FISCAL_CODE)).thenReturn(Mono.just("NO CHANNEL ENABLED"));

Boolean result = messageCoreService.send(MESSAGE_DTO).block();
Assertions.assertEquals(false,result);
StepVerifier.create(messageCoreService.send(MESSAGE_DTO))
.expectNext(false)
.verifyComplete();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import reactor.test.StepVerifier;

import static it.gov.pagopa.message.utils.TestUtils.MESSAGE_DTO;
import static org.mockito.ArgumentMatchers.any;
Expand All @@ -27,7 +28,8 @@ class MessageProducerServiceTest {

@Test
void sendMessage_OK(){
messageProducerService.enqueueMessage(MESSAGE_DTO).block();
StepVerifier.create(messageProducerService.enqueueMessage(MESSAGE_DTO))
.verifyComplete();
Mockito.verify(messageProducer,times(1)).scheduleMessage(any());
}

Expand Down
Loading