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

[PAGOPA-1837] Refactoring JUnit tests #27

Merged
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
Expand Up @@ -3,7 +3,12 @@
import it.gov.pagopa.gen.wispconverter.client.cache.model.ServiceDto;
import it.gov.pagopa.gen.wispconverter.client.cache.model.StationDto;
import it.gov.pagopa.gen.wispconverter.client.gpd.api.DebtPositionsApiApi;
import it.gov.pagopa.gen.wispconverter.client.gpd.model.*;
import it.gov.pagopa.gen.wispconverter.client.gpd.model.MultiplePaymentPositionModelDto;
import it.gov.pagopa.gen.wispconverter.client.gpd.model.PaymentOptionModelDto;
import it.gov.pagopa.gen.wispconverter.client.gpd.model.PaymentPositionModelBaseResponseDto;
import it.gov.pagopa.gen.wispconverter.client.gpd.model.PaymentPositionModelDto;
import it.gov.pagopa.gen.wispconverter.client.gpd.model.TransferMetadataModelDto;
import it.gov.pagopa.gen.wispconverter.client.gpd.model.TransferModelDto;
import it.gov.pagopa.gen.wispconverter.client.iuvgenerator.api.GenerationApi;
import it.gov.pagopa.gen.wispconverter.client.iuvgenerator.model.IUVGenerationResponseDto;
import it.gov.pagopa.wispconverter.exception.AppErrorCodeMessageEnum;
Expand Down Expand Up @@ -64,6 +69,8 @@ public class DebtPositionService {

private final Pattern taxonomyPattern = Pattern.compile("([^/]++/[^/]++)/?");

private static final String REST_CLIENT_LOG_STRING = "RestClientException ERROR [%s] - %s";

@Value("${wisp-converter.poste-italiane.abi-code}")
private String posteItalianeABICode;

Expand Down Expand Up @@ -439,7 +446,7 @@ private void handleValidPaymentPosition(DebtPositionsApiApi gpdClientInstance, S
generateREForUpdatedPaymentPosition(sessionData, iuv);

} catch (RestClientException e) {
throw new AppException(AppErrorCodeMessageEnum.CLIENT_GPD, String.format("RestClientException ERROR [%s] - %s", e.getCause().getClass().getCanonicalName(), e.getMessage()));
throw new AppException(AppErrorCodeMessageEnum.CLIENT_GPD, String.format(REST_CLIENT_LOG_STRING, e.getCause().getClass().getCanonicalName(), e.getMessage()));
}
}

Expand Down Expand Up @@ -534,7 +541,7 @@ private String generateNavCodeFromIuvGenerator(String creditorInstitutionId) {

} catch (RestClientException e) {
throw new AppException(AppErrorCodeMessageEnum.CLIENT_IUVGENERATOR,
String.format("RestClientException ERROR [%s] - %s", e.getCause().getClass().getCanonicalName(), e.getMessage()));
String.format(REST_CLIENT_LOG_STRING, e.getCause().getClass().getCanonicalName(), e.getMessage()));
}
return navCode;
}
Expand All @@ -559,7 +566,7 @@ private void handlePaymentPositionInsertion(DebtPositionsApiApi gpdClientInstanc
generateREForBulkInsert(extractedPaymentPositions);

} catch (RestClientException e) {
throw new AppException(AppErrorCodeMessageEnum.CLIENT_GPD, String.format("RestClientException ERROR [%s] - %s", e.getCause().getClass().getCanonicalName(), e.getMessage()));
throw new AppException(AppErrorCodeMessageEnum.CLIENT_GPD, String.format(REST_CLIENT_LOG_STRING, e.getCause().getClass().getCanonicalName(), e.getMessage()));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,6 @@ public void paaInviaRTOk(String payload) {
gov.telematici.pagamenti.ws.papernodo.ObjectFactory objectFactory = new gov.telematici.pagamenti.ws.papernodo.ObjectFactory();

sessionData.getAllRPTs().forEach(rpt -> {
Instant now = Instant.now();
PaymentServiceProviderDto psp = psps.get(rpt.getRpt().getPayeeInstitution().getSubjectUniqueIdentifier().getCode());

IntestazionePPT intestazionePPT = generateIntestazionePPT(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ public void post(){
.connectionString(connectionString)
.processor()
.queueName(queueName)
.processMessage(context -> processMessage(context))
.processError(context -> processError(context))
.processMessage(this::processMessage)
.processError(this::processError)
.buildProcessorClient();
}

Expand Down Expand Up @@ -99,7 +99,7 @@ public void processMessage(ServiceBusReceivedMessageContext context) {
null
);

Boolean ok = false;
boolean ok = false;
try{
log.debug("[{}]Sending receipt",receiptId);
paaInviaRTService.send(url,receipt.getPayload());
Expand Down Expand Up @@ -157,4 +157,4 @@ public void processError(ServiceBusErrorContext context) {
reason, context.getException().toString());
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public abstract class AbstractAppClientLoggingInterceptor implements ClientHttpR
private boolean responsePretty;
private boolean mustPersistEventOnRE;

public AbstractAppClientLoggingInterceptor(RequestResponseLoggingProperties clientLoggingProperties, ReService reService, ClientServiceEnum clientServiceEnum) {
protected AbstractAppClientLoggingInterceptor(RequestResponseLoggingProperties clientLoggingProperties, ReService reService, ClientServiceEnum clientServiceEnum) {
this.reService = reService;
this.clientServiceEnum = clientServiceEnum;
this.mustPersistEventOnRE = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -367,10 +367,12 @@ private void handleMDCSessionContent(HttpServletRequest request, Trace trace) {

String queryString = request.getQueryString();

// include sessionID in MDC
Matcher sessionIdMatcher = this.sessionIdPattern.matcher(queryString);
if (sessionIdMatcher.find()) {
MDC.put(Constants.MDC_SESSION_ID, sessionIdMatcher.group(1));
if(queryString != null) {
// include sessionID in MDC
Matcher sessionIdMatcher = this.sessionIdPattern.matcher(queryString);
if (sessionIdMatcher.find()) {
MDC.put(Constants.MDC_SESSION_ID, sessionIdMatcher.group(1));
}
}
}
}
4 changes: 1 addition & 3 deletions src/test/java/it/gov/pagopa/wispconverter/HomeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

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

@ActiveProfiles(profiles = "test")
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
Expand Down Expand Up @@ -61,7 +59,7 @@ void slash() throws Exception {
void info() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/info").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andDo(
(result) -> {
result -> {
assertNotNull(result);
assertNotNull(result.getResponse());
final String content = result.getResponse().getContentAsString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ void swaggerSpringPlugin() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/v3/api-docs").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().is2xxSuccessful())
.andDo(
(result) -> {
result -> {
assertNotNull(result);
assertNotNull(result.getResponse());
final String content = result.getResponse().getContentAsString();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package it.gov.pagopa.wispconverter;
package it.gov.pagopa.wispconverter.consumer;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
Expand All @@ -25,7 +25,7 @@
class ConsumerTest {

@Test
void ok() throws Exception {
void ok() {

ServiceBusReceivedMessageContext messageContext = mock(ServiceBusReceivedMessageContext.class);
ServiceBusReceivedMessage message = mock(ServiceBusReceivedMessage.class);
Expand Down Expand Up @@ -54,7 +54,7 @@ void ok() throws Exception {
}

@Test
void moreThanMax() throws Exception {
void moreThanMax() {

ServiceBusReceivedMessageContext messageContext = mock(ServiceBusReceivedMessageContext.class);
ServiceBusReceivedMessage message = mock(ServiceBusReceivedMessage.class);
Expand Down Expand Up @@ -84,7 +84,7 @@ void moreThanMax() throws Exception {
}

@Test
void koSendToPa() throws Exception {
void koSendToPa() {

ServiceBusSenderClient serviceBusSenderClient = mock(ServiceBusSenderClient.class);

Expand Down Expand Up @@ -114,13 +114,13 @@ void koSendToPa() throws Exception {

rtConsumer.processMessage(messageContext);

assertEquals(receipt.getRetry(),1);
assertEquals(1,receipt.getRetry());
verify(rtRequestRepository,times(1)).save(receipt);
verify(serviceBusSenderClient,times(1)).sendMessage(any());

}
@Test
public void testprocesserror(){
void testprocesserror(){
ServiceBusErrorContext serviceBusErrorContext = mock(ServiceBusErrorContext.class);
when(serviceBusErrorContext.getException())
.thenReturn(new ServiceBusException(new RuntimeException(),ServiceBusErrorSource.UNKNOWN));
Expand All @@ -129,7 +129,7 @@ public void testprocesserror(){
assertTrue(true);
}
@Test
public void testprocesserror2(){
void testprocesserror2(){
ServiceBusErrorContext serviceBusErrorContext = mock(ServiceBusErrorContext.class);
when(serviceBusErrorContext.getException())
.thenReturn(new ServiceBusException(new AmqpException(true, AmqpErrorCondition.MESSAGE_LOCK_LOST,"",null),ServiceBusErrorSource.UNKNOWN));
Expand All @@ -138,7 +138,7 @@ public void testprocesserror2(){
assertTrue(true);
}
@Test
public void testprocesserror3(){
void testprocesserror3(){
ServiceBusErrorContext serviceBusErrorContext = mock(ServiceBusErrorContext.class);
when(serviceBusErrorContext.getException())
.thenReturn(new ServiceBusException(new AmqpException(true, AmqpErrorCondition.UNAUTHORIZED_ACCESS,"",null),ServiceBusErrorSource.UNKNOWN));
Expand All @@ -147,7 +147,7 @@ public void testprocesserror3(){
assertTrue(true);
}
@Test
public void testprocesserror4(){
void testprocesserror4(){
ServiceBusErrorContext serviceBusErrorContext = mock(ServiceBusErrorContext.class);
when(serviceBusErrorContext.getException())
.thenReturn(new ServiceBusException(new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR,"",null),ServiceBusErrorSource.UNKNOWN));
Expand All @@ -156,7 +156,7 @@ public void testprocesserror4(){
assertTrue(true);
}
@Test
public void testprocesserror5(){
void testprocesserror5(){
ServiceBusErrorContext serviceBusErrorContext = mock(ServiceBusErrorContext.class);
when(serviceBusErrorContext.getException())
.thenReturn(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package it.gov.pagopa.wispconverter;
package it.gov.pagopa.wispconverter.endpoint;

import static it.gov.pagopa.wispconverter.ConstantsTestHelper.REDIRECT_PATH;
import static it.gov.pagopa.wispconverter.exception.AppErrorCodeMessageEnum.VALIDATION_INVALID_MULTIBENEFICIARY_CART;
import static it.gov.pagopa.wispconverter.utils.ConstantsTestHelper.REDIRECT_PATH;
import static it.gov.pagopa.wispconverter.utils.TestUtils.getPaymentPositionModelDto;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
Expand All @@ -10,13 +10,18 @@
import com.azure.messaging.servicebus.ServiceBusSenderClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import it.gov.pagopa.gen.wispconverter.client.iuvgenerator.model.IUVGenerationResponseDto;
import it.gov.pagopa.wispconverter.Application;
import it.gov.pagopa.wispconverter.repository.RPTRequestRepository;
import it.gov.pagopa.wispconverter.repository.RTRequestRepository;
import it.gov.pagopa.wispconverter.repository.ReEventRepository;
import it.gov.pagopa.wispconverter.repository.model.RPTRequestEntity;
import it.gov.pagopa.wispconverter.service.ConfigCacheService;
import it.gov.pagopa.wispconverter.utils.TestUtils;

import java.net.URI;
import java.util.*;

import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
Expand Down Expand Up @@ -68,12 +73,14 @@ void success() throws Exception {
org.springframework.test.util.ReflectionTestUtils.setField(configCacheService, "configData",TestUtils.configData(station));
HttpHeaders headers = new HttpHeaders();
headers.add("location","locationheader");
TestUtils.setMock(checkoutClient, ResponseEntity.status(HttpStatus.FOUND).headers(headers).build());

it.gov.pagopa.gen.wispconverter.client.checkout.model.CartResponseDto cartResponseDto = new it.gov.pagopa.gen.wispconverter.client.checkout.model.CartResponseDto();
cartResponseDto.setCheckoutRedirectUrl(URI.create("http://www.google.com"));
TestUtils.setMock(checkoutClient, ResponseEntity.status(HttpStatus.FOUND).headers(headers).body(cartResponseDto));
it.gov.pagopa.gen.wispconverter.client.iuvgenerator.model.IUVGenerationResponseDto iuvGenerationModelResponseDto = new IUVGenerationResponseDto();
iuvGenerationModelResponseDto.setIuv("00000000");
TestUtils.setMock(iuveneratorClient,ResponseEntity.ok().body(iuvGenerationModelResponseDto));
TestUtils.setMock(gpdClient,ResponseEntity.ok().build());
TestUtils.setMockGetExceptionNotFound(gpdClient);
TestUtils.setMockPost(gpdClient,ResponseEntity.ok().body(getPaymentPositionModelDto()));
TestUtils.setMock(decouplerCachingClient,ResponseEntity.ok().build());
when(rptRequestRepository.findById(any())).thenReturn(
Optional.of(
Expand All @@ -90,73 +97,34 @@ void success() throws Exception {


mvc.perform(MockMvcRequestBuilders.get(REDIRECT_PATH + "?sessionId=aaaaaaaaaaaa").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().is2xxSuccessful())
.andExpect(MockMvcResultMatchers.status().is(HttpStatus.FOUND.value()))
.andDo(
(result) -> {
assertNotNull(result);
assertNotNull(result.getResponse());
result -> {
Assert.assertNotNull(result);
Assert.assertNotNull(result.getResponse());
});

verify(checkoutClient,times(1)).invokeAPI(any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any());
verify(iuveneratorClient,times(1)).invokeAPI(any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any());
verify(gpdClient,times(1)).invokeAPI(any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any());
verify(decouplerCachingClient,times(1)).invokeAPI(any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any());
}

@Test
void success_multibeneficiario() throws Exception {
String station = "mystation";
org.springframework.test.util.ReflectionTestUtils.setField(configCacheService, "configData",TestUtils.configData(station));
HttpHeaders headers = new HttpHeaders();
headers.add("location","locationheader");
TestUtils.setMock(checkoutClient, ResponseEntity.status(HttpStatus.FOUND).headers(headers).build());

IUVGenerationResponseDto iuvGenerationModelResponseDto = new IUVGenerationResponseDto();
iuvGenerationModelResponseDto.setIuv("00000000");
TestUtils.setMock(iuveneratorClient,ResponseEntity.ok().body(iuvGenerationModelResponseDto));
TestUtils.setMock(gpdClient,ResponseEntity.ok().build());
TestUtils.setMock(decouplerCachingClient,ResponseEntity.ok().build());
when(rptRequestRepository.findById(any())).thenReturn(
Optional.of(
RPTRequestEntity.builder().primitive("nodoInviaCarrelloRPT")
.payload(
TestUtils.zipAndEncode(TestUtils.getCarrelloPayload(2,station,
"100.00",true
))
).build()
)
);
when(redisSimpleTemplate.opsForValue()).thenReturn(mock(ValueOperations.class));



mvc.perform(MockMvcRequestBuilders.get(REDIRECT_PATH + "?sessionId=aaaaaaaaaaaa").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().is2xxSuccessful())
.andDo(
(result) -> {
assertNotNull(result);
assertNotNull(result.getResponse());
});

verify(checkoutClient,times(1)).invokeAPI(any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any());
verify(iuveneratorClient,times(1)).invokeAPI(any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any());
verify(gpdClient,times(1)).invokeAPI(any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any());
verify(gpdClient,times(2)).invokeAPI(any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any());
verify(decouplerCachingClient,times(1)).invokeAPI(any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any(),any());
}

@Test
void fail_multibeneficiario_less_rpts() throws Exception {
String station = "mystation";
TestUtils.setMock(cacheClient,ResponseEntity.ok().body(TestUtils.configData(station)));
org.springframework.test.util.ReflectionTestUtils.setField(configCacheService, "configCacheClient",cacheClient);

org.springframework.test.util.ReflectionTestUtils.setField(configCacheService, "configData",TestUtils.configData(station));
HttpHeaders headers = new HttpHeaders();
headers.add("location","locationheader");
TestUtils.setMock(checkoutClient, ResponseEntity.status(HttpStatus.FOUND).headers(headers).build());

IUVGenerationResponseDto iuvGenerationModelResponseDto = new IUVGenerationResponseDto();
it.gov.pagopa.gen.wispconverter.client.checkout.model.CartResponseDto cartResponseDto = new it.gov.pagopa.gen.wispconverter.client.checkout.model.CartResponseDto();
cartResponseDto.setCheckoutRedirectUrl(URI.create("http://www.google.com"));
TestUtils.setMock(checkoutClient, ResponseEntity.status(HttpStatus.FOUND).headers(headers).body(cartResponseDto));
it.gov.pagopa.gen.wispconverter.client.iuvgenerator.model.IUVGenerationResponseDto iuvGenerationModelResponseDto = new IUVGenerationResponseDto();
iuvGenerationModelResponseDto.setIuv("00000000");
TestUtils.setMock(iuveneratorClient,ResponseEntity.ok().body(iuvGenerationModelResponseDto));
TestUtils.setMock(gpdClient,ResponseEntity.ok().build());
TestUtils.setMockGetExceptionNotFound(gpdClient);
TestUtils.setMockPost(gpdClient,ResponseEntity.ok().body(getPaymentPositionModelDto()));
TestUtils.setMock(decouplerCachingClient,ResponseEntity.ok().build());
when(rptRequestRepository.findById(any())).thenReturn(
Optional.of(
Expand All @@ -176,7 +144,7 @@ void fail_multibeneficiario_less_rpts() throws Exception {
mvc.perform(MockMvcRequestBuilders.get(REDIRECT_PATH + "?sessionId=aaaaaaaaaaaa").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().is2xxSuccessful())
.andDo(
(result) -> {
result -> {
assertNotNull(result);
assertNotNull(result.getResponse());
assertTrue(result.getResponse().getContentAsString().contains("Riprova, oppure contatta l'assistenza"));
Expand Down
Loading
Loading