From cd95313dcef9c18e4f16322cb1fba470332b4a89 Mon Sep 17 00:00:00 2001 From: Tullio Ranieri Date: Fri, 7 Feb 2025 11:07:33 +0100 Subject: [PATCH 01/10] QA-5637 refactor code primo commit --- .../pa/AvanzamentoNotificheB2bSteps.java | 41 ++++++-- .../steps/pa/InvioNotificheB2bSteps.java | 98 +++++++++++++++---- 2 files changed, 115 insertions(+), 24 deletions(-) diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java index be31207c4..3a4f4082b 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java @@ -682,24 +682,53 @@ public void verificationDateScheduleRefinementWithSendAnalogFeedback(Integer des } public TimelineElementV26 readingEventUpToTheTimelineElementOfNotificationForCategory(String timelineEventCategory) { - PnPollingServiceTimelineSlowV26 timelineSlowV26 = (PnPollingServiceTimelineSlowV26) pnPollingFactory.getPollingService(PnPollingStrategy.TIMELINE_SLOW_V26); + PnPollingServiceTimelineSlowV26 timelineSlowV26 = + (PnPollingServiceTimelineSlowV26) pnPollingFactory.getPollingService(PnPollingStrategy.TIMELINE_SLOW_V26); - PnPollingResponseV26 pnPollingResponseV26 = timelineSlowV26.waitForEvent(sharedSteps.getIunVersionamento(), + PnPollingResponseV26 pnPollingResponseV26 = timelineSlowV26.waitForEvent( + sharedSteps.getIunVersionamento(), PnPollingParameter.builder() .value(timelineEventCategory) - .build()); + .build() + ); + + // Controllo NullPointerException + assertThat(pnPollingResponseV26) + .as("La risposta di polling non dovrebbe essere nulla") + .isNotNull(); + + assertThat(pnPollingResponseV26.getNotification()) + .as("La notifica nella risposta di polling non dovrebbe essere nulla") + .isNotNull(); + + assertThat(pnPollingResponseV26.getNotification().getTimeline()) + .as("La timeline della notifica non dovrebbe essere nulla") + .isNotNull(); + log.info("NOTIFICATION_TIMELINE: " + pnPollingResponseV26.getNotification().getTimeline()); + try { - Assertions.assertTrue(pnPollingResponseV26.getResult()); - Assertions.assertNotNull(pnPollingResponseV26.getTimelineElement()); + assertThat(pnPollingResponseV26.getResult()) + .as("Il risultato del polling dovrebbe essere valorizzato") + .isTrue(); + + assertThat(pnPollingResponseV26.getTimelineElement()) + .as("L'elemento della timeline non dovrebbe essere nullo") + .isNotNull(); + sharedSteps.setSentNotification(pnPollingResponseV26.getNotification()); + TimelineElementV26 timelineElement = pnPollingResponseV26.getTimelineElement(); log.info("TIMELINE_ELEMENT: " + timelineElement); sharedSteps.setTimelineElement(timelineElement); + + return timelineElement; + } catch (AssertionFailedError assertionFailedError) { sharedSteps.throwAssertFailerWithIUN(assertionFailedError); } - return pnPollingResponseV26.getTimelineElement(); + + return null; } public TimelineElementV26 readingEventUpToTheTimelineElementOfNotificationForCategoryExtraRapid(String timelineEventCategory) { diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java index 8395e2662..a95b70e97 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java @@ -30,7 +30,7 @@ import org.springframework.mail.javamail.JavaMailSender; import org.springframework.util.Base64Utils; import org.springframework.web.client.HttpStatusCodeException; - +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.time.*; @@ -1068,30 +1068,78 @@ public void presenzaAttachment(Integer numeroDocumenti, String tipologia) { @And("si verifica il contenuto degli attachments da inviare in via cartacea al destinatario {int} con {int} allegati") public void checkDocumentInviatiPaper(Integer destinatario, Integer allegati) { try { - this.documentiPec = pnExternalChannelsServiceClientImpl.getReceivedMessagesAnalogico(sharedSteps.getIunVersionamento(), destinatario); - Assertions.assertNotNull(documentiPec); + this.documentiPec = pnExternalChannelsServiceClientImpl.getReceivedMessagesAnalogico( + sharedSteps.getIunVersionamento(), destinatario + ); + + // Prevenzione NullPointerException + assertThat(documentiPec) + .as("La lista dei documenti analogici non dovrebbe essere nulla") + .isNotNull() + .isNotEmpty(); // Assicura che ci sia almeno un documento + log.info("documenti analogici : {}", documentiPec); - Assertions.assertEquals(allegati, documentiPec.get(0).getPaperEngageRequest().getAttachments().size()); + + // Prevenzione NullPointerException + ReceivedMessage firstDocument = documentiPec.get(0); + assertThat(firstDocument) + .as("Il primo documento ricevuto non dovrebbe essere nullo") + .isNotNull(); + + assertThat(firstDocument.getPaperEngageRequest()) + .as("Il PaperEngageRequest del primo documento non dovrebbe essere nullo") + .isNotNull(); + + assertThat(firstDocument.getPaperEngageRequest().getAttachments()) + .as("Gli allegati del PaperEngageRequest non dovrebbero essere nulli") + .isNotNull() + .hasSize(allegati); //* + } catch (AssertionFailedError assertionFailedError) { - String message = assertionFailedError.getMessage() + "Verifica Allegati analogici in errore "; + String message = assertionFailedError.getMessage() + " - Verifica Allegati analogici in errore."; throw new AssertionFailedError(message, assertionFailedError.getExpected(), assertionFailedError.getActual(), assertionFailedError.getCause()); } } @And("si verifica che il contenuto degli attachments da inviare in via cartacea abbia {int} attachment di tipo {string}") public void presenceAttachmentAnalogicFlow(Integer numeroDocumenti, String tipologia) { - List attachmentsUri = Optional.ofNullable(documentiPec.get(0)) - .map(ReceivedMessage::getPaperEngageRequest) - .map(PaperEngageRequest::getAttachments) - .orElse(List.of()) - .stream() - .map(PaperEngageRequestAttachments::getUri) - .filter(uri -> uri.contains(tipologia)) - .toList(); try { - Assertions.assertEquals(numeroDocumenti, attachmentsUri.size()); + // Prevenzione NullPointerException + assertThat(documentiPec) + .as("La lista dei documenti PEC non dovrebbe essere nulla") + .isNotNull() + .isNotEmpty(); + + ReceivedMessage firstDocument = documentiPec.get(0); + assertThat(firstDocument) + .as("Il primo documento ricevuto non dovrebbe essere nullo") + .isNotNull(); + + PaperEngageRequest paperEngageRequest = firstDocument.getPaperEngageRequest(); + assertThat(paperEngageRequest) + .as("Il PaperEngageRequest non dovrebbe essere nullo") + .isNotNull(); + + List attachments = paperEngageRequest.getAttachments(); + assertThat(attachments) + .as("La lista degli allegati non dovrebbe essere nulla") + .isNotNull(); + + List attachmentsUri = Optional.ofNullable(documentiPec.get(0)) + .map(ReceivedMessage::getPaperEngageRequest) + .map(PaperEngageRequest::getAttachments) + .orElse(List.of()) + .stream() + .map(PaperEngageRequestAttachments::getUri) + .filter(uri -> uri.contains(tipologia)) + .toList(); + + assertThat(attachmentsUri) + .as("Il numero di allegati ottenuto non corrisponde al valore atteso", tipologia, numeroDocumenti) + .hasSize(numeroDocumenti); + } catch (AssertionFailedError assertionFailedError) { - String message = assertionFailedError.getMessage() + "Verifica Allegati Cartacei in errore "; + String message = assertionFailedError.getMessage() + " - Verifica Allegati Cartacei in errore."; throw new AssertionFailedError(message, assertionFailedError.getExpected(), assertionFailedError.getActual(), assertionFailedError.getCause()); } } @@ -1099,9 +1147,23 @@ public void presenceAttachmentAnalogicFlow(Integer numeroDocumenti, String tipol @And("si verifica che il {int} documento arrivato sia di tipo {string}") public void checkIndexedDocument(Integer documentIndex, String tipologia) { ReceivedMessage firstDocumentReceived = documentiPec.get(0); - Assertions.assertNotNull(firstDocumentReceived.getPaperEngageRequest()); - Assertions.assertNotNull(firstDocumentReceived.getPaperEngageRequest().getAttachments()); - Assertions.assertTrue(firstDocumentReceived.getPaperEngageRequest().getAttachments().get(documentIndex - 1).getDocumentType().equals(tipologia)); + + assertThat(firstDocumentReceived.getPaperEngageRequest()) + .as("Il PaperEngageRequest non dovrebbe essere nullo") + .isNotNull(); + + assertThat(firstDocumentReceived.getPaperEngageRequest().getAttachments()) + .as("Gli allegati del PaperEngageRequest non dovrebbero essere nulli") + .isNotNull(); + + assertThat(firstDocumentReceived.getPaperEngageRequest().getAttachments()) + .as("L'indice fornito (%d) è fuori dai limiti della lista degli allegati", documentIndex) + .hasSizeGreaterThanOrEqualTo(documentIndex); + + assertThat(firstDocumentReceived.getPaperEngageRequest().getAttachments().get(documentIndex - 1).getDocumentType()) + .as("Il documento all'indice %d non è del tipo atteso: %s", documentIndex, tipologia) + .isEqualTo(tipologia); + log.info(firstDocumentReceived.toString()); } From d410dd58468dead846078f76c04aad9eec6016b2 Mon Sep 17 00:00:00 2001 From: Tullio Ranieri Date: Fri, 7 Feb 2025 11:42:42 +0100 Subject: [PATCH 02/10] QA-5637 refactor test : RETURNED-TO-SENDER_2 --- .../pa/AvanzamentoNotificheB2bSteps.java | 73 +++++++++++++++---- .../steps/pa/InvioNotificheB2bSteps.java | 4 +- 2 files changed, 63 insertions(+), 14 deletions(-) diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java index 3a4f4082b..8fd684683 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java @@ -136,24 +136,53 @@ public void readingEventsNotificationPA(String status, String pa) { public void readingEventUpToTheStatusOfNotification(String status) { PnPollingPredicate pnPollingPredicate = new PnPollingPredicate(); pnPollingPredicate.setNotificationStatusHistoryElementPredicateV26( - statusHistory -> statusHistory - .getStatus() - .getValue().equals(status) + statusHistory -> statusHistory.getStatus().getValue().equals(status) ); - PnPollingServiceStatusRapidV26 statusRapidV26 = (PnPollingServiceStatusRapidV26) pnPollingFactory.getPollingService(PnPollingStrategy.STATUS_RAPID_V26); + PnPollingServiceStatusRapidV26 statusRapidV26 = + (PnPollingServiceStatusRapidV26) pnPollingFactory.getPollingService(PnPollingStrategy.STATUS_RAPID_V26); - PnPollingResponseV26 pnPollingResponseV26 = statusRapidV26.waitForEvent(sharedSteps.getSentNotification().getIun(), + // Prevenzione NullPointerException + assertThat(sharedSteps.getSentNotification()) + .as("La notifica inviata non dovrebbe essere nulla") + .isNotNull(); + + PnPollingResponseV26 pnPollingResponseV26 = statusRapidV26.waitForEvent( + sharedSteps.getSentNotification().getIun(), PnPollingParameter.builder() .value(status) .pnPollingPredicate(pnPollingPredicate) - .build()); - log.info("NOTIFICATION_STATUS_HISTORY: " + pnPollingResponseV26.getNotification().getNotificationStatusHistory()); + .build() + ); + + // Prevenzione NullPointerException + assertThat(pnPollingResponseV26) + .as("La risposta di polling non dovrebbe essere nulla") + .isNotNull(); + + assertThat(pnPollingResponseV26.getNotification()) + .as("La notifica nella risposta di polling non dovrebbe essere nulla") + .isNotNull(); + + assertThat(pnPollingResponseV26.getNotification().getNotificationStatusHistory()) + .as("Lo storico degli stati della notifica non dovrebbe essere nullo") + .isNotNull(); + + log.info("NOTIFICATION_STATUS_HISTORY: {}", pnPollingResponseV26.getNotification().getNotificationStatusHistory()); + try { - Assertions.assertTrue(pnPollingResponseV26.getResult()); - Assertions.assertNotNull(pnPollingResponseV26.getNotificationStatusHistoryElement()); + assertThat(pnPollingResponseV26.getResult()) + .as("Il risultato del polling deve essere valorizzato") + .isTrue(); + + assertThat(pnPollingResponseV26.getNotificationStatusHistoryElement()) + .as("L'elemento dello storico degli stati non dovrebbe essere nullo") + .isNotNull(); + sharedSteps.setSentNotification(pnPollingResponseV26.getNotification()); - log.info("NOTIFICATION_STATUS_HISTORY_ELEMENT: " + pnPollingResponseV26.getNotificationStatusHistoryElement()); + + log.info("NOTIFICATION_STATUS_HISTORY_ELEMENT: {}", pnPollingResponseV26.getNotificationStatusHistoryElement()); + } catch (AssertionFailedError assertionFailedError) { sharedSteps.throwAssertFailerWithIUN(assertionFailedError); } @@ -3665,17 +3694,35 @@ public void checkLegalFactAllVersions(String timelineElementCategory, String leg log.info("LEGAL FACT CATEGORY = " + legalFact.getCategory()); log.info("LEGAL FACT URL: " + legalFact.getKey()); } + @Then("esiste l'elemento di timeline della notifica {string} abbia notificationCost uguale a {string} per l'utente {int}") public void TimelineElementOfNotificationUserCost(String timelineEventCategory, String cost, Integer destinatario) { + TimelineElementV26 event = readingEventUpToTheTimelineElementOfNotificationForCategoryUser(timelineEventCategory, destinatario); + + // Prevenzione NullPointerException + assertThat(event) + .as("L'evento della timeline non dovrebbe essere nullo per la categoria '%s' e destinatario '%d'", timelineEventCategory, destinatario) + .isNotNull(); + + assertThat(event.getDetails()) + .as("I dettagli dell'evento non dovrebbero essere nulli per la categoria '%s' e destinatario '%d'", timelineEventCategory, destinatario) + .isNotNull(); + Long notificationCost = event.getDetails().getNotificationCost(); if (cost.equalsIgnoreCase("null")) { - Assertions.assertNull(notificationCost); + assertThat(notificationCost) + .as("Il notificationCost dovrebbe essere null per la categoria '%s' e destinatario '%d'", timelineEventCategory, destinatario) + .isNull(); } else if (cost.equalsIgnoreCase("NotNull")) { - Assertions.assertNotNull(notificationCost); + assertThat(notificationCost) + .as("Il notificationCost non dovrebbe essere null per la categoria '%s' e destinatario '%d'", timelineEventCategory, destinatario) + .isNotNull(); } else { - Assertions.assertEquals(Long.parseLong(cost), notificationCost); + assertThat(notificationCost) + .as("Il notificationCost dovrebbe essere uguale a '%s' per la categoria '%s' e destinatario '%d'", cost, timelineEventCategory, destinatario) + .isEqualTo(Long.parseLong(cost)); } } diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java index a95b70e97..92fb5c8fa 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java @@ -364,7 +364,9 @@ public void retentionCheckLoadForTimelineElement(String documentType, String tim if (documentType.equals("ATTACHMENTS")) { for (int i = 0; i < sharedSteps.getSentNotification().getDocuments().size(); i++) { String key = sharedSteps.getSentNotification().getDocuments().get(i).getRef().getKey(); - Assertions.assertTrue(checkRetention(key, retentionTimeLoad, timelineElement.getTimestamp())); + assertThat(checkRetention(key, retentionTimeLoad, timelineElement.getTimestamp())) + .as("La verifica della retention ha fallito per la chiave '%s'", key) + .isTrue(); } } else { throw new IllegalArgumentException(); From 25055e8e973ad5c3339696dfdf3df3e4bdca0559 Mon Sep 17 00:00:00 2001 From: Tullio Ranieri Date: Mon, 10 Feb 2025 17:53:04 +0100 Subject: [PATCH 03/10] QA-5637 refactor code - using assertJ --- .../pa/AvanzamentoNotificheB2bSteps.java | 30 +- .../steps/pa/InvioNotificheB2bSteps.java | 379 +++++++++++------- 2 files changed, 255 insertions(+), 154 deletions(-) diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java index 8fd684683..006a1b6f1 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java @@ -6,6 +6,7 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.within; +import static org.assertj.core.api.SoftAssertions.assertSoftly; import static org.awaitility.Awaitility.await; import io.cucumber.datatable.DataTable; @@ -949,12 +950,33 @@ public void readingEventUpToTheTimelineElementOfNotificationAndCancel(String tim public void readingEventUpToTheTimelineElementOfNotificationWithDeliveryDetailCode(String timelineEventCategory, String deliveryDetailCode) { PnPollingResponseV26 pnPollingResponseV26 = getPollingResponse(timelineEventCategory, deliveryDetailCode); - log.info("NOTIFICATION_TIMELINE: " + pnPollingResponseV26.getNotification().getTimeline()); + assertThat(pnPollingResponseV26) + .as("La risposta del polling non deve essere nulla") + .isNotNull(); + + if (pnPollingResponseV26.getNotification() != null) { + log.info("NOTIFICATION_TIMELINE: {}", pnPollingResponseV26.getNotification().getTimeline()); + } + try { - Assertions.assertTrue(pnPollingResponseV26.getResult(), "Polling failed. IUN: " + sharedSteps.getSentNotification().getIun()); - Assertions.assertNotNull(pnPollingResponseV26.getTimelineElement(), "The timeline element was not found. IUN: " + sharedSteps.getSentNotification().getIun()); + assertSoftly(softly -> { + softly.assertThat(pnPollingResponseV26.getResult()) + .as("Verifica che il polling abbia avuto successo per IUN: " + + (sharedSteps.getSentNotification() != null ? sharedSteps.getSentNotification().getIun() : "UNKNOWN")) + .isTrue(); + + softly.assertThat(pnPollingResponseV26.getTimelineElement()) + .as("Verifica che l'elemento di timeline esista per IUN: " + + (sharedSteps.getSentNotification() != null ? sharedSteps.getSentNotification().getIun() : "UNKNOWN")) + .isNotNull(); + }); + sharedSteps.setSentNotification(pnPollingResponseV26.getNotification()); - log.info("TIMELINE_ELEMENT: " + pnPollingResponseV26.getTimelineElement()); + + if (pnPollingResponseV26.getTimelineElement() != null) { + log.info("TIMELINE_ELEMENT: {}", pnPollingResponseV26.getTimelineElement()); + } + } catch (AssertionFailedError assertionFailedError) { sharedSteps.throwAssertFailerWithIUN(assertionFailedError); } diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java index 92fb5c8fa..d89eb566d 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java @@ -30,7 +30,9 @@ import org.springframework.mail.javamail.JavaMailSender; import org.springframework.util.Base64Utils; import org.springframework.web.client.HttpStatusCodeException; + import static org.assertj.core.api.Assertions.assertThat; + import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.time.*; @@ -40,6 +42,8 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.SoftAssertions.assertSoftly; import static org.awaitility.Awaitility.await; @@ -71,14 +75,14 @@ public class InvioNotificheB2bSteps { @Autowired - public InvioNotificheB2bSteps(PnExternalServiceClientImpl safeStorageClient, SharedSteps sharedSteps,PnExternalChannelsServiceClientImpl pnExternalChannelsServiceClientImpl, JavaMailSender emailSender) { + public InvioNotificheB2bSteps(PnExternalServiceClientImpl safeStorageClient, SharedSteps sharedSteps, PnExternalChannelsServiceClientImpl pnExternalChannelsServiceClientImpl, JavaMailSender emailSender) { this.safeStorageClient = safeStorageClient; this.sharedSteps = sharedSteps; this.b2bUtils = sharedSteps.getB2bUtils(); this.b2bClient = sharedSteps.getB2bClient(); this.webPaClient = sharedSteps.getWebPaClient(); - this.pnPaymentInfoClientImpl =sharedSteps.getPnPaymentInfoClientImpl(); - this.pnExternalChannelsServiceClientImpl=pnExternalChannelsServiceClientImpl; + this.pnPaymentInfoClientImpl = sharedSteps.getPnPaymentInfoClientImpl(); + this.pnExternalChannelsServiceClientImpl = pnExternalChannelsServiceClientImpl; this.emailSender = emailSender; } @@ -103,23 +107,35 @@ public void notificationCanBeRetrievedWithIUNV2() { private void notificationCanBeRetrievedWithIUN(AtomicReference notificationByIun, Function getNotificationByIunFunction) { try { - if (sharedSteps.getSentNotification() != null) { - Assertions.assertDoesNotThrow(() -> - notificationByIun.set(getNotificationByIunFunction.apply(sharedSteps.getSentNotification().getIun())) - ); - } else if (sharedSteps.getSentNotificationV1() != null) { - Assertions.assertDoesNotThrow(() -> - notificationByIun.set(getNotificationByIunFunction.apply(sharedSteps.getSentNotificationV1().getIun())) - ); - } else if (sharedSteps.getSentNotificationV2() != null) { - Assertions.assertDoesNotThrow(() -> - notificationByIun.set(getNotificationByIunFunction.apply(sharedSteps.getSentNotificationV2().getIun())) - ); - } else { - Assertions.assertNotNull(notificationByIun.get()); - } - Assertions.assertNotNull(notificationByIun.get()); - } catch (AssertionFailedError assertionFailedError) { + assertSoftly(softly -> { + String iun = null; + + if (sharedSteps.getSentNotification() != null) { + iun = sharedSteps.getSentNotification().getIun(); + } else if (sharedSteps.getSentNotificationV1() != null) { + iun = sharedSteps.getSentNotificationV1().getIun(); + } else if (sharedSteps.getSentNotificationV2() != null) { + iun = sharedSteps.getSentNotificationV2().getIun(); + } + + softly.assertThat(iun) + .as("Verifica che l'IUN non sia nullo prima di cercare la notifica") + .isNotNull(); + + if (iun != null) { // Evita NPE prima di applicare la funzione + T notification = getNotificationByIunFunction.apply(iun); + softly.assertThat(notification) + .as("Verifica che la notifica sia stata recuperata con successo") + .isNotNull(); + + notificationByIun.set(notification); + } + + softly.assertThat(notificationByIun.get()) + .as("Verifica che notificationByIun non sia nulla dopo il recupero") + .isNotNull(); + }); + } catch (AssertionError assertionFailedError) { sharedSteps.throwAssertFailerWithIUN(assertionFailedError); } } @@ -148,11 +164,27 @@ public void notificationCanBeRetrievedWithIUNV1Error() { @And("la notifica può essere correttamente recuperata dal sistema tramite codice IUN web PA") public void notificationCanBeRetrievedWithIUNWebPA() { AtomicReference notificationByIun = new AtomicReference<>(); + + assertThat(sharedSteps.getSentNotification()) + .as("La notifica inviata non deve essere nulla prima di recuperare il codice IUN") + .isNotNull(); + + String iun = sharedSteps.getSentNotification().getIun(); + try { - Assertions.assertDoesNotThrow(() -> - notificationByIun.set(webPaClient.searchSentNotification(OffsetDateTime.now().minusDays(1), OffsetDateTime.now(),null,null,null,sharedSteps.getSentNotification().getIun(),1,null)) + notificationByIun.set( + webPaClient.searchSentNotification( + OffsetDateTime.now().minusDays(1), OffsetDateTime.now(), + null, null, null, iun, 1, null + ) ); - Assertions.assertNotNull(notificationByIun.get()); + + assertSoftly(softly -> { + softly.assertThat(notificationByIun.get()) + .as("La notifica con IUN " + iun + "deve essere trovata nel sistema", iun) + .isNotNull(); + }); + } catch (AssertionFailedError assertionFailedError) { sharedSteps.throwAssertFailerWithIUN(assertionFailedError); } @@ -165,31 +197,35 @@ public void notification120ggCanBeRetrievedWithIUNWebPA() { FullSentNotificationV26 notifica120 = null; - for(NotificationSearchRow notifiche :serarchedNotification){ + for (NotificationSearchRow notifiche : serarchedNotification) { - notifica120 = b2bClient.getSentNotification(notifiche.getIun()); + notifica120 = b2bClient.getSentNotification(notifiche.getIun()); - if(notifica120.getRecipients().get(0).getPayments() != null && notifica120.getRecipients().get(0).getPayments().get(0).getPagoPa() != null && notifica120.getRecipients().get(0).getPayments().get(0).getPagoPa().getNoticeCode() != null){ - break; - }else{ - notifica120=null; - } + if (notifica120.getRecipients().get(0).getPayments() != null && notifica120.getRecipients().get(0).getPayments().get(0).getPagoPa() != null && notifica120.getRecipients().get(0).getPayments().get(0).getPagoPa().getNoticeCode() != null) { + break; + } else { + notifica120 = null; + } - try { - await().atMost(sharedSteps.getWorkFlowWait(), TimeUnit.MILLISECONDS); - } catch (RuntimeException exc) { - log.error(exc.getMessage()); - throw exc; - } + try { + await().atMost(sharedSteps.getWorkFlowWait(), TimeUnit.MILLISECONDS); + } catch (RuntimeException exc) { + log.error(exc.getMessage()); + throw exc; } + } try { - Assertions.assertNotNull(notifica120); + assertThat(notifica120) + .as("La notifica dopo 120 giorni non deve essere nulla") + .isNotNull(); log.info("notifica dopo 120gg: {}", notifica120); - Assertions.assertNull(notifica120.getRecipients().get(0).getPayments().get(0).getPagoPa().getAttachment()); + assertThat(notifica120.getRecipients().get(0).getPayments().get(0).getPagoPa().getAttachment()) + .as("L'attachment del pagamento deve essere nullo") + .isNull(); sharedSteps.setSentNotification(notifica120); @@ -201,10 +237,8 @@ public void notification120ggCanBeRetrievedWithIUNWebPA() { } - - @And("recupero notifica del {string} lato web dalla PA {string} e verifica presenza pagamento per notifica che è arrivato fino al elemento {string} con feePolicy {string}") - public void notificationFromADateCanBeRetrievedWithIUNWebPA(String stringDate,String pa, String type, String feePolicy) { + public void notificationFromADateCanBeRetrievedWithIUNWebPA(String stringDate, String pa, String type, String feePolicy) { sharedSteps.selectPA(pa); LocalDate date = LocalDate.parse(stringDate); @@ -213,48 +247,61 @@ public void notificationFromADateCanBeRetrievedWithIUNWebPA(String stringDate,St List serarchedNotification = searchNotificationWebFromADate(offsetDateTime); FullSentNotificationV26 notifica = null; - for(NotificationSearchRow notifiche :serarchedNotification){ + for (NotificationSearchRow notifiche : serarchedNotification) { - notifica = b2bClient.getSentNotification(notifiche.getIun()); + notifica = b2bClient.getSentNotification(notifiche.getIun()); - if(!notifica.getRecipients().get(0).getPayments().isEmpty() && notifica.getRecipients().get(0).getPayments() != null && notifica.getRecipients().get(0).getPayments().get(0).getPagoPa() != null && notifica.getTimeline().toString().contains(type) && notifica.getNotificationFeePolicy().toString().equals(feePolicy) && notifica.getPaFee() == null){ - break; - }else{ - notifica=null; - } - await().atMost(sharedSteps.getWorkFlowWait(), TimeUnit.MILLISECONDS); + if (!notifica.getRecipients().get(0).getPayments().isEmpty() && notifica.getRecipients().get(0).getPayments() != null && notifica.getRecipients().get(0).getPayments().get(0).getPagoPa() != null && notifica.getTimeline().toString().contains(type) && notifica.getNotificationFeePolicy().toString().equals(feePolicy) && notifica.getPaFee() == null) { + break; + } else { + notifica = null; } + await().atMost(sharedSteps.getWorkFlowWait(), TimeUnit.MILLISECONDS); + } - try{ - Assertions.assertNotNull(notifica); + try { + assertThat(notifica) + .as("La notifica non deve essere nulla") + .isNotNull(); log.info("notifica trovata: {}", notifica); - notifica.setPaFee(100); - notifica.setVat(22); + notifica.setPaFee(100); + notifica.setVat(22); sharedSteps.setSentNotification(notifica); } catch (AssertionFailedError assertionFailedError) { - String message = assertionFailedError.getMessage() + - "{notifica : " + (notifica == null ? "NULL" : notifica) + " }"; - throw new AssertionFailedError(message, assertionFailedError.getExpected(), assertionFailedError.getActual(), assertionFailedError.getCause()); + String message = assertionFailedError.getMessage() + + "{notifica : " + (notifica == null ? "NULL" : notifica) + " }"; + throw new AssertionFailedError(message, assertionFailedError.getExpected(), assertionFailedError.getActual(), assertionFailedError.getCause()); } } -private List searchNotificationWebFromADate(OffsetDateTime data){ - AtomicReference notificationByIun = new AtomicReference<>(); + private List searchNotificationWebFromADate(OffsetDateTime data) { + AtomicReference notificationByIun = new AtomicReference<>(); - Assertions.assertDoesNotThrow(()-> - notificationByIun.set(webPaClient.searchSentNotification(data,data.plusDays(20),null,null,null,null,50,null)) - ); + Assertions.assertDoesNotThrow(() -> + notificationByIun.set(webPaClient.searchSentNotification(data, data.plusDays(20), null, null, null, null, 50, null)) + ); - Assertions.assertNotNull(notificationByIun.get()); - Assertions.assertNotNull(notificationByIun.get().getResultsPage()); - Assertions.assertTrue(notificationByIun.get().getResultsPage().size()>0); + assertSoftly(softly -> { + softly.assertThat(notificationByIun.get()) + .as("Verifica che la risposta della ricerca non sia nulla") + .isNotNull(); + + if (notificationByIun.get() != null) { + softly.assertThat(notificationByIun.get().getResultsPage()) + .as("Verifica che la lista dei risultati non sia nulla") + .isNotNull(); + + softly.assertThat(notificationByIun.get().getResultsPage()) + .as("Verifica che la lista dei risultati non sia vuota") + .isNotEmpty(); + } + }); - List ricercaNotifiche=notificationByIun.get().getResultsPage(); - return ricercaNotifiche; -} + return notificationByIun.get() != null ? notificationByIun.get().getResultsPage() : Collections.emptyList(); + } @Then("la notifica può essere correttamente recuperata dal sistema tramite Stato {string} dalla web PA {string}") public void notificationCanBeRetrievedWithStatusByWebPA(String status, String paType) { @@ -278,10 +325,27 @@ public void notificationCanBeRetrievedWithStatusByWebPA(String status, String pa AtomicReference notificationByIun = new AtomicReference<>(); try { - Assertions.assertDoesNotThrow(() -> - notificationByIun.set(webPaClient.searchSentNotification(OffsetDateTime.now().minusDays(1), OffsetDateTime.now(),null,notificationInternalStatus,null,null,1,null)) - ); - Assertions.assertNotNull(notificationByIun.get()); + assertThatCode(() -> + notificationByIun.set( + webPaClient.searchSentNotification( + OffsetDateTime.now().minusDays(1), + OffsetDateTime.now(), + null, + notificationInternalStatus, + null, + null, + 1, + null + ) + ) + ).as("Errore durante il recupero della notifica con stato interno: %s", notificationInternalStatus) + .doesNotThrowAnyException(); + + assertSoftly(softly -> { + softly.assertThat(notificationByIun.get()) + .as("La notifica recuperata non deve essere nulla") + .isNotNull(); + }); } catch (AssertionFailedError assertionFailedError) { sharedSteps.throwAssertFailerWithIUN(assertionFailedError); } @@ -324,7 +388,7 @@ public void preLoadingOfMetaDatiAttachmentF24() { AtomicReference notificationDocumentAtomic = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> notificationDocumentAtomic.set(b2bUtils.preloadMetadataAttachment(notificationPaymentAttachment))); try { - Thread.sleep( sharedSteps.getWait()); + Thread.sleep(sharedSteps.getWait()); } catch (InterruptedException e) { log.error("Thread.sleep error retry"); throw new RuntimeException(e); @@ -412,7 +476,6 @@ public void retentionCheckLoadForTimelineElementPAGOPA(String documentType, Stri } - @Given("viene letta la notifica {string} dal {string}") public void vieneLettaLaNotificaDal(String IUN, String pa) { sharedSteps.selectPA(pa); @@ -432,9 +495,9 @@ public void retrievalAttemptedIUN() { private void getNotificationByIun(String iun) { try { - if (!iun.isEmpty()){ + if (!iun.isEmpty()) { b2bUtils.getNotificationByIun(iun); - }else { + } else { b2bUtils.getNotificationByIun(new String(Base64Utils.decodeFromString(this.sharedSteps.getNewNotificationResponse().getNotificationRequestId()))); } } catch (HttpStatusCodeException e) { @@ -454,9 +517,9 @@ public void retrievalAttemptedIUNConV2(String iun) { private void getNotificationByIunVersioning(String iun, String version) { try { - if (version.equalsIgnoreCase("V1")){ + if (version.equalsIgnoreCase("V1")) { b2bUtils.getNotificationByIunV1(iun); - }else if (version.equalsIgnoreCase("V2")){ + } else if (version.equalsIgnoreCase("V2")) { b2bUtils.getNotificationByIunV2(iun); } } catch (HttpStatusCodeException e) { @@ -491,7 +554,7 @@ private void getDownloadFile(String type, String iun, int destinatario) { List documents = sharedSteps.getSentNotification().getDocuments(); this.downloadResponse = b2bClient .getSentNotificationDocument(sharedSteps.getSentNotification().getIun(), Integer.parseInt(documents.get(0).getDocIdx())); - }else { + } else { this.downloadResponse = b2bClient .getSentNotificationAttachment(iun, destinatario, type, 0); @@ -528,19 +591,35 @@ public void operationProducedAnError(String statusCode) { @Then("l'operazione ha prodotto un errore con status code {string} con messaggio di errore {string}") public void operationProducedAnErrorWithMessage(String statusCode, String errore) { HttpStatusCodeException httpStatusCodeException = this.sharedSteps.consumeNotificationError(); - Assertions.assertTrue((httpStatusCodeException != null) && - (httpStatusCodeException.getStatusCode().toString().substring(0, 3).equals(statusCode))); - byte[] responseBody = httpStatusCodeException.getResponseBodyAsByteArray(); - String responseBodyText = new String(responseBody, StandardCharsets.UTF_8); + assertSoftly(softly -> { + + softly.assertThat(httpStatusCodeException) + .as("Verifica che l'eccezione non sia nulla") + .isNotNull(); - Assertions.assertTrue(responseBodyText.contains(errore)) ; + if (httpStatusCodeException != null) { + softly.assertThat(httpStatusCodeException.getStatusCode().toString().substring(0, 3)) + .as("Verifica che lo status code sia '%s'", statusCode) + .isEqualTo(statusCode); + + byte[] responseBody = httpStatusCodeException.getResponseBodyAsByteArray(); + String responseBodyText = new String(responseBody, StandardCharsets.UTF_8); + + softly.assertThat(responseBodyText) + .as("Verifica che il messaggio di errore contenga: '%s'", errore) + .contains(errore); + } + }); } @Then("l'operazione non ha prodotto errori") public void operationProducedNotAnError() { HttpStatusCodeException httpStatusCodeException = this.sharedSteps.consumeNotificationError(); - Assertions.assertNull(httpStatusCodeException); + + assertThat(httpStatusCodeException) + .as("Verifica che non siano stati generati errori HTTP") + .isNull(); } @@ -573,11 +652,11 @@ public void correctAcquisitionNotificationV2Error() { private void verifyNotificationVersioning(String version) { try { - if (version.equalsIgnoreCase("V1")){ + if (version.equalsIgnoreCase("V1")) { b2bUtils.verifyNotificationV1(sharedSteps.getSentNotificationV1()); - }else if (version.equalsIgnoreCase("V2")){ + } else if (version.equalsIgnoreCase("V2")) { b2bUtils.verifyNotificationV2(sharedSteps.getSentNotificationV2()); - }else if (version.equalsIgnoreCase("V23")){ + } else if (version.equalsIgnoreCase("V23")) { b2bUtils.verifyNotification(sharedSteps.getSentNotification()); } } catch (AssertionFailedError assertionFailedError) { @@ -704,7 +783,7 @@ public void notificationCaNotBeCanceledWithIUN() { @And("la notifica non può essere annullata dal sistema tramite codice IUN più volte") public void notificationNotCanBeCanceledWithIUN() { Assertions.assertDoesNotThrow(() -> { - RequestStatus resp = Assertions.assertDoesNotThrow(() -> + RequestStatus resp = Assertions.assertDoesNotThrow(() -> b2bClient.notificationCancellation(sharedSteps.getSentNotification().getIun())); Assertions.assertNotNull(resp); @@ -736,8 +815,8 @@ public void laNotificaVienePagatasuCheckout() { } @Then("verifica stato pagamento di una notifica creditorTaxID {string} noticeCode {string} con errore {string}") - public void verificaStatoPagamentoNotifica(String creditorTaxID , String noticeCode,String codiceErrore) { - List paymentInfoRequestList= new ArrayList(); + public void verificaStatoPagamentoNotifica(String creditorTaxID, String noticeCode, String codiceErrore) { + List paymentInfoRequestList = new ArrayList(); PaymentInfoRequest paymentInfoRequest = new PaymentInfoRequest() .creditorTaxId(creditorTaxID) @@ -749,7 +828,7 @@ public void verificaStatoPagamentoNotifica(String creditorTaxID , String noticeC try { Assertions.assertDoesNotThrow(() -> { - paymentInfoResponse= pnPaymentInfoClientImpl.getPaymentInfoV21(paymentInfoRequestList); + paymentInfoResponse = pnPaymentInfoClientImpl.getPaymentInfoV21(paymentInfoRequestList); log.info("Informazioni sullo stato del Pagamento: " + paymentInfoResponse.toString()); }); Assertions.assertNotNull(paymentInfoResponse); @@ -765,7 +844,7 @@ public void verificaStatoPagamentoNotifica(String creditorTaxID , String noticeC @Then("verifica stato pagamento di una notifica con status {string}") public void verificaStatoPagamentoNotifica(String status) { - List paymentInfoRequestList= new ArrayList(); + List paymentInfoRequestList = new ArrayList(); PaymentInfoRequest paymentInfoRequest = new PaymentInfoRequest() .creditorTaxId(sharedSteps.getNotificationRequest().getRecipients().get(0).getPayments().get(0).getPagoPa().getCreditorTaxId()) @@ -777,12 +856,12 @@ public void verificaStatoPagamentoNotifica(String status) { try { Assertions.assertDoesNotThrow(() -> { - paymentInfoResponse= pnPaymentInfoClientImpl.getPaymentInfoV21(paymentInfoRequestList); + paymentInfoResponse = pnPaymentInfoClientImpl.getPaymentInfoV21(paymentInfoRequestList); }); Assertions.assertNotNull(paymentInfoResponse); log.info("Informazioni sullo stato del Pagamento: " + paymentInfoResponse); - Assertions.assertTrue(status.equalsIgnoreCase(paymentInfoResponse.get(0).getStatus().getValue())); + Assertions.assertTrue(status.equalsIgnoreCase(paymentInfoResponse.get(0).getStatus().getValue())); } catch (AssertionFailedError assertionFailedError) { @@ -806,7 +885,7 @@ public void laNotificaVienePagatasuCheckoutError(String codiceErrore) { } @And("l'avviso pagopa viene pagato correttamente su checkout creditorTaxID {string} noticeCode {string} con errore {string}") - public void laNotificaVienePagatasuCheckoutError(String creditorTaxID , String noticeCode,String codiceErrore) { + public void laNotificaVienePagatasuCheckoutError(String creditorTaxID, String noticeCode, String codiceErrore) { PaymentRequest paymentRequest = getPaymentRequest(null, noticeCode, creditorTaxID, @@ -821,7 +900,7 @@ public void laNotificaVienePagatasuCheckoutError(String creditorTaxID , String n @And("la notifica a 2 avvisi di pagamento con OpenApi V1") public void notificationCanBeRetrievePaymentV1() { AtomicReference notificationByIun = new AtomicReference<>(); - String iun =sharedSteps.getIunVersionamento(); + String iun = sharedSteps.getIunVersionamento(); try { Assertions.assertDoesNotThrow(() -> @@ -839,11 +918,11 @@ public void notificationCanBeRetrievePaymentV1() { @And("la notifica a 2 avvisi di pagamento con OpenApi V2") public void notificationCanBeRetrievePaymentV2() { AtomicReference notificationByIun = new AtomicReference<>(); - String iun =sharedSteps.getIunVersionamento(); + String iun = sharedSteps.getIunVersionamento(); try { Assertions.assertDoesNotThrow(() -> - notificationByIun.set(b2bUtils.getNotificationByIunV2(iun))); + notificationByIun.set(b2bUtils.getNotificationByIunV2(iun))); Assertions.assertNotNull(notificationByIun.get()); Assertions.assertNotNull(Objects.requireNonNull(notificationByIun.get().getRecipients().get(0).getPayment()).getNoticeCode()); @@ -857,7 +936,7 @@ public void notificationCanBeRetrievePaymentV2() { @And("la notifica a 1 avvisi di pagamento con OpenApi V1") public void notificationCanBeRetrievePayment1V1() { AtomicReference notificationByIun = new AtomicReference<>(); - String iun =sharedSteps.getIunVersionamento(); + String iun = sharedSteps.getIunVersionamento(); try { Assertions.assertDoesNotThrow(() -> notificationByIun.set(b2bUtils.getNotificationByIunV1(iun))); @@ -883,7 +962,7 @@ public void siEffettuaLaChiamataSuExternalRegPerRicevereLUrlDiCheckoutConNoticeC "Test Automation Desk", "https://api.uat.platform.pagopa.it"); - System.out.println("COSTO NOTIFICA: "+getPaymentInfoV21.get(0).getAmount()); + System.out.println("COSTO NOTIFICA: " + getPaymentInfoV21.get(0).getAmount()); verifyCheckoutCart(paymentRequest, null); } @@ -897,7 +976,7 @@ private void verifyCheckoutCart(PaymentRequest paymentRequest, String codiceErro }); Assertions.assertNotNull(paymentResponse); - if (codiceErrore != null){ + if (codiceErrore != null) { Assertions.assertTrue(codiceErrore.equalsIgnoreCase(paymentInfoResponse.get(0).getErrorCode())); Assertions.assertTrue(codiceErrore.equalsIgnoreCase(paymentResponse.getCheckoutUrl())); } @@ -909,15 +988,15 @@ private void verifyCheckoutCart(PaymentRequest paymentRequest, String codiceErro } @Then("si verifica che il phyicalAddress sia stato normalizzato correttamente con rimozione caratteri isoLatin1") - public void controlloCampiAddressNormalizzatore(){ - String regex= "[{}-~¡-ÿ^]"; - String regexCaratteriA= "[æ]"; + public void controlloCampiAddressNormalizzatore() { + String regex = "[{}-~¡-ÿ^]"; + String regexCaratteriA = "[æ]"; FullSentNotificationV26 timeline = sharedSteps.getSentNotification(); TimelineElementV26 timelineNormalizer = timeline.getTimeline().stream().filter(elem -> elem.getCategory().equals(TimelineElementCategoryV23.NORMALIZED_ADDRESS)).findAny().orElse(null); PhysicalAddress oldAddress = timelineNormalizer.getDetails().getOldAddress(); - PhysicalAddress normalizedAddress= timelineNormalizer.getDetails().getNormalizedAddress(); + PhysicalAddress normalizedAddress = timelineNormalizer.getDetails().getNormalizedAddress(); try { Assertions.assertNotNull(normalizedAddress); @@ -926,38 +1005,38 @@ public void controlloCampiAddressNormalizzatore(){ log.info("old address: {}", oldAddress); log.info("normalized address: {}", normalizedAddress); - PhysicalAddress newAddress= new PhysicalAddress() - .address(oldAddress.getAddress().replaceAll(regexCaratteriA,"A ").replaceAll(regex," ").toUpperCase()) - .municipality(oldAddress.getMunicipality().replaceAll(regexCaratteriA,"A ").replaceAll(regex," ").toUpperCase()) - .municipalityDetails(oldAddress.getMunicipalityDetails().replaceAll(regexCaratteriA,"A ").replaceAll(regex," ").toUpperCase()) - .province(oldAddress.getProvince().replaceAll(regexCaratteriA,"A ").replaceAll(regex," ").toUpperCase()) - .zip(oldAddress.getZip().replaceAll(regexCaratteriA,"A ").replaceAll(regex," ").toUpperCase()); + PhysicalAddress newAddress = new PhysicalAddress() + .address(oldAddress.getAddress().replaceAll(regexCaratteriA, "A ").replaceAll(regex, " ").toUpperCase()) + .municipality(oldAddress.getMunicipality().replaceAll(regexCaratteriA, "A ").replaceAll(regex, " ").toUpperCase()) + .municipalityDetails(oldAddress.getMunicipalityDetails().replaceAll(regexCaratteriA, "A ").replaceAll(regex, " ").toUpperCase()) + .province(oldAddress.getProvince().replaceAll(regexCaratteriA, "A ").replaceAll(regex, " ").toUpperCase()) + .zip(oldAddress.getZip().replaceAll(regexCaratteriA, "A ").replaceAll(regex, " ").toUpperCase()); - log.info(" newAddress: {}",newAddress); + log.info(" newAddress: {}", newAddress); - Assertions.assertEquals(newAddress.getAddress().toUpperCase(),normalizedAddress.getAddress()); - Assertions.assertEquals(newAddress.getMunicipality(),normalizedAddress.getMunicipality()); - Assertions.assertEquals(newAddress.getMunicipalityDetails(),normalizedAddress.getMunicipalityDetails()); - Assertions.assertEquals(newAddress.getProvince(),normalizedAddress.getProvince()); - Assertions.assertEquals(newAddress.getZip(),normalizedAddress.getZip()); + Assertions.assertEquals(newAddress.getAddress().toUpperCase(), normalizedAddress.getAddress()); + Assertions.assertEquals(newAddress.getMunicipality(), normalizedAddress.getMunicipality()); + Assertions.assertEquals(newAddress.getMunicipalityDetails(), normalizedAddress.getMunicipalityDetails()); + Assertions.assertEquals(newAddress.getProvince(), normalizedAddress.getProvince()); + Assertions.assertEquals(newAddress.getZip(), normalizedAddress.getZip()); - } catch(AssertionFailedError error) { + } catch (AssertionFailedError error) { sharedSteps.throwAssertFailerWithIUN(error); } } private PaymentRequest getPaymentRequest(NotificationPriceResponseV23 notificationPrice, String noticeNumber, String fiscalCode, String companyName, Integer amount, String description, String returnUrl) { - PaymentRequest paymentRequest= new PaymentRequest(); - PaymentNotice paymentNotice= new PaymentNotice(); + PaymentRequest paymentRequest = new PaymentRequest(); + PaymentNotice paymentNotice = new PaymentNotice(); paymentNotice.noticeNumber(noticeNumber); paymentNotice.fiscalCode(fiscalCode); paymentNotice.companyName(companyName); paymentNotice.description(description); - if(amount != null) { + if (amount != null) { paymentNotice.setAmount(amount); } - if(notificationPrice != null) { + if (notificationPrice != null) { paymentNotice.amount(notificationPrice.getTotalPrice()); } paymentRequest.paymentNotice(paymentNotice); @@ -984,10 +1063,10 @@ public void vieneCancellataLaNotificaConIUN(String iun) { @And("si verifica il contenuto degli attacchment da inviare nella pec del destinatario {int} con {int} allegati") public void vieneVerificatoIDocumentiInviatiDellaPecDelDestinatarioConNumeroDiAllegati(Integer destinatario, Integer allegati) { try { - this.documentiPec= pnExternalChannelsServiceClientImpl.getReceivedMessages(sharedSteps.getIunVersionamento(),destinatario); + this.documentiPec = pnExternalChannelsServiceClientImpl.getReceivedMessages(sharedSteps.getIunVersionamento(), destinatario); Assertions.assertNotNull(documentiPec); - log.info("documenti pec : {}",documentiPec); + log.info("documenti pec : {}", documentiPec); Assertions.assertEquals(allegati, documentiPec.get(0).getDigitalNotificationRequest().getAttachmentUrls().size()); } catch (AssertionFailedError assertionFailedError) { @@ -1002,10 +1081,10 @@ public void vieneVerificatoIDocumentiInviatiDellaPecDelDestinatarioConNumeroDiAl public void vieneVerificatoIDocumentiInviatiDellaPecDelDestinatario(Integer destinatario, String basePath) { try { pnExternalChannelsServiceClientImpl.switchBasePath(basePath); - this.documentiPec= pnExternalChannelsServiceClientImpl.getReceivedMessages(sharedSteps.getIunVersionamento(),destinatario); + this.documentiPec = pnExternalChannelsServiceClientImpl.getReceivedMessages(sharedSteps.getIunVersionamento(), destinatario); Assertions.assertNotNull(documentiPec); - log.info("documenti pec : {}",documentiPec); + log.info("documenti pec : {}", documentiPec); } catch (AssertionFailedError assertionFailedError) { String message = assertionFailedError.getMessage() + "Verifica Allegati pec in errore "; @@ -1019,25 +1098,25 @@ public void verificaSHAAllegatiPecDelDestinatario(Integer destinatario, String t try { //caricamento in Mappa di tutti i documenti della notifica - for(NotificationDocument documentNotifica : sharedSteps.getSentNotification().getDocuments()){ - sharedSteps.getMapAllegatiNotificaSha256().put(documentNotifica.getRef().getKey(),documentNotifica.getDigests().getSha256()); + for (NotificationDocument documentNotifica : sharedSteps.getSentNotification().getDocuments()) { + sharedSteps.getMapAllegatiNotificaSha256().put(documentNotifica.getRef().getKey(), documentNotifica.getDigests().getSha256()); } //caricamento in Mappa di tutti i documenti di pagamento della notifica - for(NotificationPaymentItem documentPagamento : sharedSteps.getSentNotification().getRecipients().get(destinatario).getPayments()){ - sharedSteps.getMapAllegatiNotificaSha256().put(documentPagamento.getPagoPa().getAttachment().getRef().getKey(),documentPagamento.getPagoPa().getAttachment().getDigests().getSha256()); + for (NotificationPaymentItem documentPagamento : sharedSteps.getSentNotification().getRecipients().get(destinatario).getPayments()) { + sharedSteps.getMapAllegatiNotificaSha256().put(documentPagamento.getPagoPa().getAttachment().getRef().getKey(), documentPagamento.getPagoPa().getAttachment().getDigests().getSha256()); } Assertions.assertTrue(!sharedSteps.getMapAllegatiNotificaSha256().isEmpty()); boolean checkAllegati = true; - for(ReceivedMessage documentPec : documentiPec){ - for(String documentPecKey : documentPec.getDigitalNotificationRequest().getAttachmentUrls()){ - if(documentPecKey.contains(tipoAttachment)){ + for (ReceivedMessage documentPec : documentiPec) { + for (String documentPecKey : documentPec.getDigitalNotificationRequest().getAttachmentUrls()) { + if (documentPecKey.contains(tipoAttachment)) { PnExternalServiceClientImpl.SafeStorageResponse safeStorageResponse = safeStorageClient.safeStorageInfo(documentPecKey.substring(14, documentPecKey.length())); Assertions.assertNotNull(safeStorageResponse); Assertions.assertNotNull(safeStorageResponse.getChecksum()); Assertions.assertNotNull(sharedSteps.getMapAllegatiNotificaSha256().get(safeStorageResponse.getKey())); - if (!safeStorageResponse.getChecksum().equals(sharedSteps.getMapAllegatiNotificaSha256().get(safeStorageResponse.getKey()))){ + if (!safeStorageResponse.getChecksum().equals(sharedSteps.getMapAllegatiNotificaSha256().get(safeStorageResponse.getKey()))) { checkAllegati = false; break; } @@ -1106,7 +1185,7 @@ public void checkDocumentInviatiPaper(Integer destinatario, Integer allegati) { @And("si verifica che il contenuto degli attachments da inviare in via cartacea abbia {int} attachment di tipo {string}") public void presenceAttachmentAnalogicFlow(Integer numeroDocumenti, String tipologia) { try { - // Prevenzione NullPointerException + assertThat(documentiPec) .as("La lista dei documenti PEC non dovrebbe essere nulla") .isNotNull() @@ -1186,14 +1265,14 @@ private void sendEmail() { @Given("si invia una email alla pec mittente e si attendono {int} minuti") public void siInviaUnaEmailAllaPecMittenteESiAttendonoMinuti(int wait) { Assertions.assertDoesNotThrow(this::sendEmail); - long waiting = ((wait*60)*1000); + long waiting = ((wait * 60) * 1000); Assertions.assertDoesNotThrow(() -> Thread.sleep(waiting)); } @Given("si richiama checkout con dati:") public void siRichiamaCheckoutConDati(Map dataCheckout) { PaymentRequest requestCheckout = creationPaymentRequest(dataCheckout); - try { + try { PaymentResponse responseCheckout = pnPaymentInfoClientImpl.checkoutCart(requestCheckout); Assertions.assertNotNull(responseCheckout); Assertions.assertNotNull(responseCheckout.getCheckoutUrl()); @@ -1217,9 +1296,9 @@ public PaymentRequest creationPaymentRequest(Map dataCheckout) { PaymentRequest requestCheckout = new PaymentRequest() .paymentNotice(new PaymentNotice() - .noticeNumber(dataCheckout.get("noticeCode")!=null? dataCheckout.get("noticeCode"): + .noticeNumber(dataCheckout.get("noticeCode") != null ? dataCheckout.get("noticeCode") : sharedSteps.getSentNotification().getRecipients().get(0).getPayments().get(0).getPagoPa().getNoticeCode()) - .fiscalCode(dataCheckout.get("fiscalCode")!=null? dataCheckout.get("fiscalCode"): + .fiscalCode(dataCheckout.get("fiscalCode") != null ? dataCheckout.get("fiscalCode") : sharedSteps.getSentNotification().getRecipients().get(0).getPayments().get(0).getPagoPa().getCreditorTaxId()) .amount(dataCheckout.get("amount") != null ? Integer.parseInt(dataCheckout.get("amount")) : null) .description(dataCheckout.get("description")) @@ -1230,16 +1309,14 @@ public PaymentRequest creationPaymentRequest(Map dataCheckout) { } - - @And("si verifica che negli url non contenga il docTag nel {string}") public void verificaNonPresenzaDocType(String type) { - boolean contieneDocTag=false; + boolean contieneDocTag = false; for (String attachmentUrl : getAttachemtListForTypeOfNotification(type)) { - if(attachmentUrl.contains("docTag")){ - contieneDocTag=true; + if (attachmentUrl.contains("docTag")) { + contieneDocTag = true; } } @@ -1254,15 +1331,16 @@ public void verificaNonPresenzaDocType(String type) { } - public List getAttachemtListForTypeOfNotification(String type){ - List attchmentNotification=new ArrayList<>(); - switch (type.toLowerCase()){ + public List getAttachemtListForTypeOfNotification(String type) { + List attchmentNotification = new ArrayList<>(); + switch (type.toLowerCase()) { case "analogico" -> { for (PaperEngageRequestAttachments attahment : documentiPec.get(0).getPaperEngageRequest().getAttachments()) { attchmentNotification.add(attahment.getUri()); } } - case "digitale" -> attchmentNotification= documentiPec.get(0).getDigitalNotificationRequest().getAttachmentUrls(); + case "digitale" -> + attchmentNotification = documentiPec.get(0).getDigitalNotificationRequest().getAttachmentUrls(); } return attchmentNotification; } @@ -1297,8 +1375,9 @@ private LegalFactDownloadMetadataResponse getLegalFactIdAAR(String aarType) { String finalKeySearch = keySearch; try { Assertions.assertDoesNotThrow(() -> { - legalFactDownloadMetadataResponse.set(this.b2bClient.getDownloadLegalFact(sharedSteps.getSentNotification().getIun(), finalKeySearch));}); - } catch (AssertionFailedError assertionFailedError) { + legalFactDownloadMetadataResponse.set(this.b2bClient.getDownloadLegalFact(sharedSteps.getSentNotification().getIun(), finalKeySearch)); + }); + } catch (AssertionFailedError assertionFailedError) { sharedSteps.throwAssertFailerWithIUN(assertionFailedError); } } From cbd70b39abc6df20775967951b50b65030902783 Mon Sep 17 00:00:00 2001 From: Tullio Ranieri Date: Thu, 13 Feb 2025 15:50:53 +0100 Subject: [PATCH 04/10] QA-5637 merging api payment bff --- .../it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java index bc3cf3f7d..ced760d84 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java @@ -5,6 +5,7 @@ import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; +import it.pagopa.pn.client.b2b.generated.openapi.clients.external.generate.model.external.bff.payment.*; import it.pagopa.pn.client.b2b.generated.openapi.clients.externalchannels.model.mock.pec.PaperEngageRequest; import it.pagopa.pn.client.b2b.generated.openapi.clients.externalchannels.model.mock.pec.PaperEngageRequestAttachments; import it.pagopa.pn.client.b2b.generated.openapi.clients.externalchannels.model.mock.pec.ReceivedMessage; From 6eccf73813d1ad3aff474763277622d33e67e0a5 Mon Sep 17 00:00:00 2001 From: Tullio Ranieri Date: Fri, 14 Feb 2025 09:16:16 +0100 Subject: [PATCH 05/10] QA-5637 refactor code - using assertJ --- .../steps/pa/InvioNotificheB2bSteps.java | 238 +++++++++++++----- 1 file changed, 177 insertions(+), 61 deletions(-) diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java index ced760d84..9814d2fd2 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java @@ -368,7 +368,9 @@ public void laNotificaVieneRecuperataDalSistemaTramiteCodiceIUN() { public void preLoadingOfDocument() { NotificationDocument notificationDocument = b2bUtils.newDocument("classpath:/sample.pdf"); AtomicReference notificationDocumentAtomic = new AtomicReference<>(); - Assertions.assertDoesNotThrow(() -> notificationDocumentAtomic.set(b2bUtils.preloadDocument(notificationDocument))); + assertThatCode(() -> notificationDocumentAtomic.set(b2bUtils.preloadDocument(notificationDocument))) + .as("Il caricamento e l'assegnazione del documento di notifica non devono generare eccezioni") + .doesNotThrowAnyException(); this.notificationDocumentPreload = notificationDocumentAtomic.get(); } @@ -377,7 +379,9 @@ public void preLoadingOfDocument() { public void preLoadingOfAttachment() { NotificationPaymentAttachment notificationPaymentAttachment = b2bUtils.newAttachment("classpath:/sample.pdf"); AtomicReference notificationDocumentAtomic = new AtomicReference<>(); - Assertions.assertDoesNotThrow(() -> notificationDocumentAtomic.set(b2bUtils.preloadAttachment(notificationPaymentAttachment))); + assertThatCode(() -> notificationDocumentAtomic.set(b2bUtils.preloadAttachment(notificationPaymentAttachment))) + .as("Il caricamento e l'assegnazione dell'allegato di notifica non devono generare eccezioni") + .doesNotThrowAnyException(); this.notificationPaymentAttachmentPreload = notificationDocumentAtomic.get(); } @@ -386,7 +390,9 @@ public void preLoadingOfAttachment() { public void preLoadingOfMetaDatiAttachmentF24() { NotificationMetadataAttachment notificationPaymentAttachment = b2bUtils.newMetadataAttachment("classpath:/METADATA_CORRETTO.json"); AtomicReference notificationDocumentAtomic = new AtomicReference<>(); - Assertions.assertDoesNotThrow(() -> notificationDocumentAtomic.set(b2bUtils.preloadMetadataAttachment(notificationPaymentAttachment))); + assertThatCode(() -> notificationDocumentAtomic.set(b2bUtils.preloadMetadataAttachment(notificationPaymentAttachment))) + .as("Il caricamento e l'assegnazione dei metadati dell'allegato di notifica non devono generare eccezioni") + .doesNotThrowAnyException(); try { Thread.sleep(sharedSteps.getWait()); } catch (InterruptedException e) { @@ -405,7 +411,9 @@ public void retentionCheckPreload(String documentType) { case "F24" -> this.notificationMetadataAttachment.getRef().getKey(); default -> throw new IllegalArgumentException(); }; - Assertions.assertTrue(checkRetetion(key, retentionTimePreLoad)); + assertThat(checkRetetion(key, retentionTimePreLoad)) + .as("La verifica della retention per la chiave "+key+" con il tempo di retention deve restituire true", key, retentionTimePreLoad) + .isTrue(); } @@ -419,7 +427,9 @@ public void retentionCheckLoad(String documentType) { sharedSteps.getSentNotification().getRecipients().get(0).getPayments().get(0).getF24().getMetadataAttachment().getRef().getKey(); default -> throw new IllegalArgumentException(); }; - Assertions.assertTrue(checkRetetion(key, retentionTimeLoad)); + assertThat(checkRetetion(key, retentionTimeLoad)) + .as("La verifica della retention per la chiave "+key+" con il tempo di retention deve restituire true", key, retentionTimeLoad) + .isTrue(); } @And("viene effettuato un controllo sulla durata della retention di {string} per l'elemento di timeline {string}") @@ -443,7 +453,13 @@ public void retentionCheckLoadForTimelineElementF24(String documentType, String if (documentType.equals("ATTACHMENTS")) { for (int i = 0; i < sharedSteps.getSentNotification().getRecipients().get(0).getPayments().size(); i++) { String key = sharedSteps.getSentNotification().getRecipients().get(0).getPayments().get(i).getF24().getMetadataAttachment().getRef().getKey(); - Assertions.assertTrue(checkRetention(key, retentionTimeLoad, timelineElement.getTimestamp())); + + assertThat(timelineElement.getTimestamp()).as("Il timestamp dell'elemento della timeline non deve essere nullo").isNotNull(); + + assertThat(checkRetention(key, retentionTimeLoad, timelineElement.getTimestamp())) + .as("La verifica della retention per la chiave con tempo di retention e il timestamp deve restituire true", + key, retentionTimeLoad, timelineElement.getTimestamp()) + .isTrue(); } } else { throw new IllegalArgumentException(); @@ -454,9 +470,19 @@ public void retentionCheckLoadForTimelineElementF24(String documentType, String public void attachmentCheckLoadForTimelineElementF24(String documentType, String timelineEventCategory, String doc, @Transpose DataTest dataFromTest) throws RuntimeException { TimelineElementV26 timelineElement = sharedSteps.getTimelineElementByEventId(timelineEventCategory, dataFromTest); if (documentType.equals("ATTACHMENTS")) { - Assertions.assertNotNull(timelineElement.getDetails().getAttachments()); - Assertions.assertTrue(doc.equalsIgnoreCase(timelineElement.getDetails().getAttachments().get(0).getDocumentType())); - Assertions.assertTrue(timelineElement.getDetails().getAttachments().get(0).getUrl().contains(".zip")); + assertSoftly(softly -> { + softly.assertThat(timelineElement.getDetails().getAttachments()) + .as("La lista degli allegati non deve essere nulla") + .isNotNull(); + + softly.assertThat(timelineElement.getDetails().getAttachments().get(0).getDocumentType()) + .as("Il tipo di documento dell'allegato deve essere uguale a '%s'", doc) + .isEqualToIgnoringCase(doc); + + softly.assertThat(timelineElement.getDetails().getAttachments().get(0).getUrl()) + .as("L'URL dell'allegato deve contenere '.zip'") + .contains(".zip"); + }); } else { throw new IllegalArgumentException(); } @@ -468,7 +494,11 @@ public void retentionCheckLoadForTimelineElementPAGOPA(String documentType, Stri if (documentType.equals("ATTACHMENTS")) { for (int i = 0; i < sharedSteps.getSentNotification().getRecipients().get(0).getPayments().size(); i++) { String key = sharedSteps.getSentNotification().getRecipients().get(0).getPayments().get(i).getPagoPa().getAttachment().getRef().getKey(); - Assertions.assertTrue(checkRetention(key, retentionTimeLoad, timelineElement.getTimestamp())); + + assertThat(checkRetention(key, retentionTimeLoad, timelineElement.getTimestamp())) + .as("La verifica della retention per la chiave con tempo di retention e il timestamp deve restituire true", + key, retentionTimeLoad, timelineElement.getTimestamp()) + .isTrue(); } } else { throw new IllegalArgumentException(); @@ -578,14 +608,21 @@ private void getDownloadFile(String type, String iun, int destinatario) { @Then("il download si conclude correttamente") public void correctlyDownload() { - Assertions.assertEquals(this.sha256DocumentDownload, this.downloadResponse.getSha256()); + assertThat(this.downloadResponse.getSha256()) + .as("L'hash SHA-256 del documento scaricato e diverso dal quello ricevuto in risposta", this.sha256DocumentDownload, this.downloadResponse.getSha256()) + .isEqualTo(this.sha256DocumentDownload); } @Then("l'operazione ha prodotto un errore con status code {string}") public void operationProducedAnError(String statusCode) { HttpStatusCodeException httpStatusCodeException = this.sharedSteps.consumeNotificationError(); - Assertions.assertTrue((httpStatusCodeException != null) && - (httpStatusCodeException.getStatusCode().toString().substring(0, 3).equals(statusCode))); + assertThat(httpStatusCodeException) + .as("L'eccezione httpStatusCodeException non dovrebbe essere nulla") + .isNotNull(); + + assertThat(httpStatusCodeException.getStatusCode().toString().substring(0, 3)) + .as("Il codice di stato HTTP non corrisponde a quello atteso", statusCode, httpStatusCodeException.getStatusCode().toString().substring(0, 3)) + .isEqualTo(statusCode); } @Then("l'operazione ha prodotto un errore con status code {string} con messaggio di errore {string}") @@ -625,18 +662,24 @@ public void operationProducedNotAnError() { @Then("si verifica la corretta acquisizione della notifica") public void correctAcquisitionNotification() { - Assertions.assertDoesNotThrow(() -> verifyNotificationVersioning("V23")); + assertThatCode(() -> verifyNotificationVersioning("V23")) + .as("La verifica della versione della notifica non deve generare eccezioni per la versione 'V23'") + .doesNotThrowAnyException(); } @Then("si verifica la corretta acquisizione della notifica V1") public void correctAcquisitionNotificationV1() { - Assertions.assertDoesNotThrow(() -> verifyNotificationVersioning("V1")); + assertThatCode(() -> verifyNotificationVersioning("V1")) + .as("La verifica della versione della notifica non deve generare eccezioni per la versione 'V23'") + .doesNotThrowAnyException(); } @Then("si verifica la corretta acquisizione della notifica V2") public void correctAcquisitionNotificationV2() { - Assertions.assertDoesNotThrow(() -> verifyNotificationVersioning("V2")); + assertThatCode(() -> verifyNotificationVersioning("V2")) + .as("La verifica della versione della notifica non deve generare eccezioni per la versione 'V23'") + .doesNotThrowAnyException(); } @Then("si verifica lo scarto dell' acquisizione della notifica V1") @@ -664,26 +707,33 @@ private void verifyNotificationVersioning(String version) { } } - @Then("si verifica la corretta acquisizione della notifica con verifica sha256 del allegato di pagamento {string}") - public void correctAcquisitionNotificationVerifySha256AllegatiPagamento(String attachnament) { - Assertions.assertDoesNotThrow(() -> b2bUtils.verifyNotificationAndSha256AllegatiPagamento(sharedSteps.getSentNotification(), attachnament)); + @Then("si verifica la corretta acquisizione della notifica con verifica sha256 dell'allegato di pagamento {string}") + public void correctAcquisitionNotificationVerifySha256AllegatiPagamento(String attachment) { + assertThatCode(() -> b2bUtils.verifyNotificationAndSha256AllegatiPagamento(sharedSteps.getSentNotification(), attachment)) + .as("Verifica fallita per la notifica e l'hash SHA-256 dell'allegato di pagamento . Assicurati che non vengano sollevate eccezioni.", attachment) + .doesNotThrowAnyException(); } @And("viene controllato la presenza del taxonomyCode") public void checkTaxonomyCode() { - Assertions.assertNotNull(this.sharedSteps.getSentNotification().getTaxonomyCode()); + assertThat(this.sharedSteps.getSentNotification().getTaxonomyCode()) + .as("Il taxonomyCode nella notifica inviata non dovrebbe essere nullo") + .isNotNull(); + if (this.sharedSteps.getNotificationRequest().getTaxonomyCode() != null) { - Assertions.assertEquals(this.sharedSteps.getNotificationRequest().getTaxonomyCode(), - this.sharedSteps.getSentNotification().getTaxonomyCode()); + assertThat(this.sharedSteps.getNotificationRequest().getTaxonomyCode()) + .as("Il taxonomyCode nella richiesta di notifica dovrebbe essere uguale al taxonomyCode nella notifica inviata") + .isEqualTo(this.sharedSteps.getSentNotification().getTaxonomyCode()); } - } @And("vengono prodotte le evidenze: metadati e requestID") public void evidenceProduced() { - Assertions.assertNotNull(this.sharedSteps.getNewNotificationResponse()); + assertThat(this.sharedSteps.getNewNotificationResponse()) + .as("La risposta della nuova notifica non dovrebbe essere nulla") + .isNotNull(); log.info("METADATI: " + '\n' + this.sharedSteps.getNewNotificationResponse()); log.info("REQUEST-ID: " + '\n' + this.sharedSteps.getNewNotificationResponse().getNotificationRequestId()); } @@ -691,9 +741,20 @@ public void evidenceProduced() { @Then("si verifica la corretta acquisizione della richiesta di invio notifica") public void correctAcquisitionRequest() { - Assertions.assertNotNull(this.sharedSteps.getNewNotificationResponse()); - Assertions.assertNotNull(this.sharedSteps.getNewNotificationResponse().getNotificationRequestId()); - Assertions.assertNotNull(b2bClient.getNotificationRequestStatus(this.sharedSteps.getNewNotificationResponse().getNotificationRequestId())); + assertSoftly(softly -> { + softly.assertThat(this.sharedSteps.getNewNotificationResponse()) + .as("La risposta della nuova notifica non dovrebbe essere nulla") + .isNotNull(); + + softly.assertThat(this.sharedSteps.getNewNotificationResponse().getNotificationRequestId()) + .as("L'ID della richiesta di notifica non dovrebbe essere nullo") + .isNotNull(); + + softly.assertThat(b2bClient.getNotificationRequestStatus(this.sharedSteps.getNewNotificationResponse().getNotificationRequestId())) + .as("Lo stato della richiesta di notifica non dovrebbe essere nullo.", + this.sharedSteps.getNewNotificationResponse().getNotificationRequestId()) + .isNotNull(); + }); } @@ -736,9 +797,11 @@ private boolean checkRetention(String fileKey, Integer retentionTime, OffsetDate @And("l'importo della notifica è {int}") public void priceNotificationVerify(Integer price) { try { - Assertions.assertEquals(this.sharedSteps.getSentNotification().getAmount(), price); - } catch (AssertionFailedError assertionFailedError) { - sharedSteps.throwAssertFailerWithIUN(assertionFailedError); + assertThat(this.sharedSteps.getSentNotification().getAmount()) + .as("L'importo della notifica dovrebbe essere uguale a "+price, price) + .isEqualTo(price); + } catch (AssertionError assertionError) { + sharedSteps.throwAssertFailerWithIUN(assertionError); } } @@ -765,7 +828,9 @@ public void vieneVerificatoLoStatoDiAccettazioneConPaProtocolNumber() { private void verifyStatus(String notificationRequestId, String paProtocolNumber, String idempotenceToken) { NewNotificationRequestStatusResponseV23 newNotificationRequestStatusResponse = Assertions.assertDoesNotThrow(() -> this.b2bClient.getNotificationRequestStatusAllParam(notificationRequestId, paProtocolNumber, idempotenceToken)); - Assertions.assertNotNull(newNotificationRequestStatusResponse.getNotificationRequestStatus()); + assertThat(newNotificationRequestStatusResponse.getNotificationRequestStatus()) + .as("Lo stato della richiesta di notifica non dovrebbe essere nullo") + .isNotNull(); log.debug(newNotificationRequestStatusResponse.getNotificationRequestStatus()); } @@ -782,15 +847,22 @@ public void notificationCaNotBeCanceledWithIUN() { //Annullamento Notifica @And("la notifica non può essere annullata dal sistema tramite codice IUN più volte") public void notificationNotCanBeCanceledWithIUN() { - Assertions.assertDoesNotThrow(() -> { - RequestStatus resp = Assertions.assertDoesNotThrow(() -> - b2bClient.notificationCancellation(sharedSteps.getSentNotification().getIun())); - - Assertions.assertNotNull(resp); - Assertions.assertNotNull(resp.getDetails()); - Assertions.assertFalse(resp.getDetails().isEmpty()); - Assertions.assertTrue("NOTIFICATION_ALREADY_CANCELLED".equalsIgnoreCase(resp.getDetails().get(0).getCode())); - + assertSoftly(softly -> { + softly.assertThatCode(() -> { + RequestStatus resp = b2bClient.notificationCancellation(sharedSteps.getSentNotification().getIun()); + softly.assertThat(resp) + .as("La risposta alla cancellazione della notifica non dovrebbe essere nulla") + .isNotNull(); + softly.assertThat(resp.getDetails()) + .as("I dettagli della risposta non dovrebbero essere nulli") + .isNotNull(); + softly.assertThat(resp.getDetails()) + .as("I dettagli della risposta non dovrebbero essere vuoti") + .isNotEmpty(); + softly.assertThat(resp.getDetails().get(0).getCode()) + .as("Il codice nella risposta dovrebbe essere 'NOTIFICATION_ALREADY_CANCELLED'") + .isEqualToIgnoringCase("NOTIFICATION_ALREADY_CANCELLED"); + }).as("La cancellazione della notifica non dovrebbe generare eccezioni").doesNotThrowAnyException(); }); } @@ -831,8 +903,14 @@ public void verificaStatoPagamentoNotifica(String creditorTaxID, String noticeCo paymentInfoResponse = pnPaymentInfoClientImpl.getPaymentInfoV21(paymentInfoRequestList); log.info("Informazioni sullo stato del Pagamento: " + paymentInfoResponse.toString()); }); - Assertions.assertNotNull(paymentInfoResponse); - Assertions.assertTrue(codiceErrore.equalsIgnoreCase(paymentInfoResponse.get(0).getErrorCode())); + assertThat(paymentInfoResponse) + .as("La risposta del pagamento non dovrebbe essere nulla") + .isNotNull(); + + assertThat(paymentInfoResponse.get(0).getErrorCode()) + .as("Il codice errore nella risposta dovrebbe essere uguale a '%s'", codiceErrore) + .isEqualToIgnoringCase(codiceErrore); + } catch (AssertionFailedError assertionFailedError) { @@ -855,13 +933,21 @@ public void verificaStatoPagamentoNotifica(String status) { log.info("Messaggio json da allegare: " + paymentInfoRequest); try { - Assertions.assertDoesNotThrow(() -> { + assertThatCode(() -> { paymentInfoResponse = pnPaymentInfoClientImpl.getPaymentInfoV21(paymentInfoRequestList); + }) + .as("La chiamata al servizio di pagamento non dovrebbe generare eccezioni") + .doesNotThrowAnyException(); - }); - Assertions.assertNotNull(paymentInfoResponse); - log.info("Informazioni sullo stato del Pagamento: " + paymentInfoResponse); - Assertions.assertTrue(status.equalsIgnoreCase(paymentInfoResponse.get(0).getStatus().getValue())); + assertThat(paymentInfoResponse) + .as("La risposta del pagamento non dovrebbe essere nulla") + .isNotNull(); + + log.info("Informazioni sullo stato del Pagamento: {}", paymentInfoResponse); + + assertThat(paymentInfoResponse.get(0).getStatus().getValue()) + .as("Lo stato nella risposta dovrebbe essere uguale a "+status , status) + .isEqualToIgnoringCase(status); } catch (AssertionFailedError assertionFailedError) { @@ -903,12 +989,23 @@ public void notificationCanBeRetrievePaymentV1() { String iun = sharedSteps.getIunVersionamento(); try { - Assertions.assertDoesNotThrow(() -> - notificationByIun.set(b2bUtils.getNotificationByIunV1(iun))); + assertThatCode(() -> { + notificationByIun.set(b2bUtils.getNotificationByIunV1(iun)); + }) + .as("La chiamata per ottenere la notifica per l'IUN non dovrebbe generare eccezioni") + .doesNotThrowAnyException(); - Assertions.assertNotNull(notificationByIun.get()); - Assertions.assertNotNull(Objects.requireNonNull(notificationByIun.get().getRecipients().get(0).getPayment()).getNoticeCode()); - Assertions.assertNotNull(Objects.requireNonNull(notificationByIun.get().getRecipients().get(0).getPayment()).getNoticeCodeAlternative()); + assertThat(notificationByIun.get()) + .as("La notifica recuperata non dovrebbe essere nulla") + .isNotNull(); + + assertThat(notificationByIun.get().getRecipients()) + .as("I destinatari della notifica non dovrebbero essere nulli o vuoti") + .isNotEmpty(); + + assertThat(notificationByIun.get().getRecipients().get(0).getPayment()) + .as("Il pagamento del primo destinatario della notifica non dovrebbe essere nullo") + .isNotNull(); } catch (AssertionFailedError assertionFailedError) { sharedSteps.throwAssertFailerWithIUN(assertionFailedError); @@ -921,12 +1018,20 @@ public void notificationCanBeRetrievePaymentV2() { String iun = sharedSteps.getIunVersionamento(); try { - Assertions.assertDoesNotThrow(() -> - notificationByIun.set(b2bUtils.getNotificationByIunV2(iun))); - Assertions.assertNotNull(notificationByIun.get()); - Assertions.assertNotNull(Objects.requireNonNull(notificationByIun.get().getRecipients().get(0).getPayment()).getNoticeCode()); - Assertions.assertNotNull(Objects.requireNonNull(notificationByIun.get().getRecipients().get(0).getPayment()).getNoticeCodeAlternative()); + assertThatCode(() -> { + notificationByIun.set(b2bUtils.getNotificationByIunV2(iun)); + }) + .as("La chiamata per ottenere la notifica per l'IUN non dovrebbe generare eccezioni") + .doesNotThrowAnyException(); + + assertThat(notificationByIun.get().getRecipients().get(0).getPayment().getNoticeCode()) + .as("Il codice della notifica del pagamento non dovrebbe essere nullo") + .isNotNull(); + + assertThat(notificationByIun.get().getRecipients().get(0).getPayment().getNoticeCodeAlternative()) + .as("Il codice alternativo della notifica del pagamento non dovrebbe essere nullo") + .isNotNull(); } catch (AssertionFailedError assertionFailedError) { sharedSteps.throwAssertFailerWithIUN(assertionFailedError); @@ -938,10 +1043,21 @@ public void notificationCanBeRetrievePayment1V1() { AtomicReference notificationByIun = new AtomicReference<>(); String iun = sharedSteps.getIunVersionamento(); try { - Assertions.assertDoesNotThrow(() -> - notificationByIun.set(b2bUtils.getNotificationByIunV1(iun))); - Assertions.assertNotNull(notificationByIun.get()); - Assertions.assertNotNull(Objects.requireNonNull(notificationByIun.get().getRecipients().get(0).getPayment()).getNoticeCode()); + assertThatCode(() -> { + notificationByIun.set(b2bUtils.getNotificationByIunV1(iun)); + }) + .as("La chiamata per ottenere la notifica tramite IUN non dovrebbe generare eccezioni") + .doesNotThrowAnyException(); + + assertThat(notificationByIun.get()) + .as("La notifica recuperata non dovrebbe essere nulla") + .isNotNull(); + + assertThat(notificationByIun.get().getRecipients().get(0).getPayment().getNoticeCode()) + .as("Il codice della notifica del pagamento non dovrebbe essere nullo") + .isNotNull(); + + } catch (AssertionFailedError assertionFailedError) { sharedSteps.throwAssertFailerWithIUN(assertionFailedError); } From 776b6debfc25a461d8a9b3bd97ffd1edbc3bef67 Mon Sep 17 00:00:00 2001 From: Tullio Ranieri Date: Mon, 17 Feb 2025 10:22:34 +0100 Subject: [PATCH 06/10] QA-5537 keep doing refactor assert --- .../pa/AvanzamentoNotificheB2bSteps.java | 65 +++------------- .../steps/pa/InvioNotificheB2bSteps.java | 78 +++++++++---------- 2 files changed, 45 insertions(+), 98 deletions(-) diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java index 006a1b6f1..2c3664e4a 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java @@ -143,34 +143,13 @@ public void readingEventUpToTheStatusOfNotification(String status) { PnPollingServiceStatusRapidV26 statusRapidV26 = (PnPollingServiceStatusRapidV26) pnPollingFactory.getPollingService(PnPollingStrategy.STATUS_RAPID_V26); - // Prevenzione NullPointerException - assertThat(sharedSteps.getSentNotification()) - .as("La notifica inviata non dovrebbe essere nulla") - .isNotNull(); - - PnPollingResponseV26 pnPollingResponseV26 = statusRapidV26.waitForEvent( - sharedSteps.getSentNotification().getIun(), + //NPE + PnPollingResponseV26 pnPollingResponseV26 = statusRapidV26.waitForEvent(sharedSteps.getSentNotification().getIun(), PnPollingParameter.builder() .value(status) .pnPollingPredicate(pnPollingPredicate) - .build() - ); - - // Prevenzione NullPointerException - assertThat(pnPollingResponseV26) - .as("La risposta di polling non dovrebbe essere nulla") - .isNotNull(); - - assertThat(pnPollingResponseV26.getNotification()) - .as("La notifica nella risposta di polling non dovrebbe essere nulla") - .isNotNull(); - - assertThat(pnPollingResponseV26.getNotification().getNotificationStatusHistory()) - .as("Lo storico degli stati della notifica non dovrebbe essere nullo") - .isNotNull(); - - log.info("NOTIFICATION_STATUS_HISTORY: {}", pnPollingResponseV26.getNotification().getNotificationStatusHistory()); - + .build()); + log.info("NOTIFICATION_STATUS_HISTORY: " + pnPollingResponseV26.getNotification().getNotificationStatusHistory()); try { assertThat(pnPollingResponseV26.getResult()) .as("Il risultato del polling deve essere valorizzato") @@ -719,24 +698,9 @@ public TimelineElementV26 readingEventUpToTheTimelineElementOfNotificationForCat sharedSteps.getIunVersionamento(), PnPollingParameter.builder() .value(timelineEventCategory) - .build() - ); - - // Controllo NullPointerException - assertThat(pnPollingResponseV26) - .as("La risposta di polling non dovrebbe essere nulla") - .isNotNull(); - - assertThat(pnPollingResponseV26.getNotification()) - .as("La notifica nella risposta di polling non dovrebbe essere nulla") - .isNotNull(); - - assertThat(pnPollingResponseV26.getNotification().getTimeline()) - .as("La timeline della notifica non dovrebbe essere nulla") - .isNotNull(); - + .build()); log.info("NOTIFICATION_TIMELINE: " + pnPollingResponseV26.getNotification().getTimeline()); - +//NPE try { assertThat(pnPollingResponseV26.getResult()) .as("Il risultato del polling dovrebbe essere valorizzato") @@ -950,13 +914,11 @@ public void readingEventUpToTheTimelineElementOfNotificationAndCancel(String tim public void readingEventUpToTheTimelineElementOfNotificationWithDeliveryDetailCode(String timelineEventCategory, String deliveryDetailCode) { PnPollingResponseV26 pnPollingResponseV26 = getPollingResponse(timelineEventCategory, deliveryDetailCode); - assertThat(pnPollingResponseV26) - .as("La risposta del polling non deve essere nulla") - .isNotNull(); - if (pnPollingResponseV26.getNotification() != null) { + + Objects.requireNonNull( pnPollingResponseV26.getNotification(), "La notifica non può essere null"); log.info("NOTIFICATION_TIMELINE: {}", pnPollingResponseV26.getNotification().getTimeline()); - } + try { assertSoftly(softly -> { @@ -3722,14 +3684,7 @@ public void TimelineElementOfNotificationUserCost(String timelineEventCategory, TimelineElementV26 event = readingEventUpToTheTimelineElementOfNotificationForCategoryUser(timelineEventCategory, destinatario); - // Prevenzione NullPointerException - assertThat(event) - .as("L'evento della timeline non dovrebbe essere nullo per la categoria '%s' e destinatario '%d'", timelineEventCategory, destinatario) - .isNotNull(); - - assertThat(event.getDetails()) - .as("I dettagli dell'evento non dovrebbero essere nulli per la categoria '%s' e destinatario '%d'", timelineEventCategory, destinatario) - .isNotNull(); + //NPE Long notificationCost = event.getDetails().getNotificationCost(); diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java index 9814d2fd2..9ccf787c1 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java @@ -1163,10 +1163,11 @@ private BffPaymentRequest getPaymentRequest(NotificationPriceResponseV23 notific @Given("viene cancellata la notifica con IUN {string}") public void vieneCancellataLaNotificaConIUN(String iun) { b2bClient.setApiKeys(SettableApiKey.ApiKeyType.GA); - Assertions.assertDoesNotThrow(() -> { + Assertions.assertDoesNotThrow(() -> { RequestStatus resp = Assertions.assertDoesNotThrow(() -> b2bClient.notificationCancellation(iun)); + Assertions.assertNotNull(resp); Assertions.assertNotNull(resp.getDetails()); Assertions.assertTrue(resp.getDetails().size() > 0); @@ -1229,9 +1230,20 @@ public void verificaSHAAllegatiPecDelDestinatario(Integer destinatario, String t for (String documentPecKey : documentPec.getDigitalNotificationRequest().getAttachmentUrls()) { if (documentPecKey.contains(tipoAttachment)) { PnExternalServiceClientImpl.SafeStorageResponse safeStorageResponse = safeStorageClient.safeStorageInfo(documentPecKey.substring(14, documentPecKey.length())); - Assertions.assertNotNull(safeStorageResponse); - Assertions.assertNotNull(safeStorageResponse.getChecksum()); - Assertions.assertNotNull(sharedSteps.getMapAllegatiNotificaSha256().get(safeStorageResponse.getKey())); + assertSoftly(softly -> { + + softly.assertThat(safeStorageResponse) + .as("Il safeStorageResponse non dovrebbe essere nullo") + .isNotNull(); + + softly.assertThat(safeStorageResponse.getChecksum()) + .as("Il checksum non dovrebbe essere nullo") + .isNotNull(); + + softly.assertThat(sharedSteps.getMapAllegatiNotificaSha256().get(safeStorageResponse.getKey())) + .as("Il valore per la chiave %s non dovrebbe essere nullo", safeStorageResponse.getKey()) + .isNotNull(); + }); if (!safeStorageResponse.getChecksum().equals(sharedSteps.getMapAllegatiNotificaSha256().get(safeStorageResponse.getKey()))) { checkAllegati = false; break; @@ -1269,7 +1281,6 @@ public void checkDocumentInviatiPaper(Integer destinatario, Integer allegati) { sharedSteps.getIunVersionamento(), destinatario ); - // Prevenzione NullPointerException assertThat(documentiPec) .as("La lista dei documenti analogici non dovrebbe essere nulla") .isNotNull() @@ -1277,7 +1288,6 @@ public void checkDocumentInviatiPaper(Integer destinatario, Integer allegati) { log.info("documenti analogici : {}", documentiPec); - // Prevenzione NullPointerException ReceivedMessage firstDocument = documentiPec.get(0); assertThat(firstDocument) .as("Il primo documento ricevuto non dovrebbe essere nullo") @@ -1300,41 +1310,16 @@ public void checkDocumentInviatiPaper(Integer destinatario, Integer allegati) { @And("si verifica che il contenuto degli attachments da inviare in via cartacea abbia {int} attachment di tipo {string}") public void presenceAttachmentAnalogicFlow(Integer numeroDocumenti, String tipologia) { + List attachmentsUri = Optional.ofNullable(documentiPec.get(0)) + .map(ReceivedMessage::getPaperEngageRequest) + .map(PaperEngageRequest::getAttachments) + .orElse(List.of()) + .stream() + .map(PaperEngageRequestAttachments::getUri) + .filter(uri -> uri.contains(tipologia)) + .toList(); try { - - assertThat(documentiPec) - .as("La lista dei documenti PEC non dovrebbe essere nulla") - .isNotNull() - .isNotEmpty(); - - ReceivedMessage firstDocument = documentiPec.get(0); - assertThat(firstDocument) - .as("Il primo documento ricevuto non dovrebbe essere nullo") - .isNotNull(); - - PaperEngageRequest paperEngageRequest = firstDocument.getPaperEngageRequest(); - assertThat(paperEngageRequest) - .as("Il PaperEngageRequest non dovrebbe essere nullo") - .isNotNull(); - - List attachments = paperEngageRequest.getAttachments(); - assertThat(attachments) - .as("La lista degli allegati non dovrebbe essere nulla") - .isNotNull(); - - List attachmentsUri = Optional.ofNullable(documentiPec.get(0)) - .map(ReceivedMessage::getPaperEngageRequest) - .map(PaperEngageRequest::getAttachments) - .orElse(List.of()) - .stream() - .map(PaperEngageRequestAttachments::getUri) - .filter(uri -> uri.contains(tipologia)) - .toList(); - - assertThat(attachmentsUri) - .as("Il numero di allegati ottenuto non corrisponde al valore atteso", tipologia, numeroDocumenti) - .hasSize(numeroDocumenti); - + Assertions.assertEquals(numeroDocumenti, attachmentsUri.size()); } catch (AssertionFailedError assertionFailedError) { String message = assertionFailedError.getMessage() + " - Verifica Allegati Cartacei in errore."; throw new AssertionFailedError(message, assertionFailedError.getExpected(), assertionFailedError.getActual(), assertionFailedError.getCause()); @@ -1354,7 +1339,7 @@ public void checkIndexedDocument(Integer documentIndex, String tipologia) { .isNotNull(); assertThat(firstDocumentReceived.getPaperEngageRequest().getAttachments()) - .as("L'indice fornito (%d) è fuori dai limiti della lista degli allegati", documentIndex) + .as("L'indice fornito è fuori dai limiti della lista degli allegati", documentIndex) .hasSizeGreaterThanOrEqualTo(documentIndex); assertThat(firstDocumentReceived.getPaperEngageRequest().getAttachments().get(documentIndex - 1).getDocumentType()) @@ -1390,8 +1375,15 @@ public void siRichiamaCheckoutConDati(Map dataCheckout) { BffPaymentRequest requestCheckout = creationPaymentRequest(dataCheckout); try { BffPaymentResponse responseCheckout = pnPaymentInfoClientImpl.checkoutCart(requestCheckout); - Assertions.assertNotNull(responseCheckout); - Assertions.assertNotNull(responseCheckout.getCheckoutUrl()); + + assertThat(responseCheckout) + .as("Il responseCheckout non dovrebbe essere nullo") + .isNotNull(); + + assertThat(responseCheckout.getCheckoutUrl()) + .as("La checkoutUrl non dovrebbe essere nulla") + .isNotNull(); + log.info("response checkout: {}", responseCheckout); } catch (AssertionFailedError error) { throw error; From e59d0dbde48b963dd1a1afde1d54e62cfbcb1434 Mon Sep 17 00:00:00 2001 From: Tullio Ranieri Date: Tue, 18 Feb 2025 10:11:44 +0100 Subject: [PATCH 07/10] QA-5537 keep doing refactor assert --- .../steps/pa/InvioNotificheB2bSteps.java | 91 +++++++++++-------- 1 file changed, 54 insertions(+), 37 deletions(-) diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java index 9ccf787c1..8a8178849 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java @@ -22,6 +22,7 @@ import it.pagopa.pn.cucumber.steps.SharedSteps; import it.pagopa.pn.cucumber.utils.DataTest; import lombok.extern.slf4j.Slf4j; +import org.assertj.core.api.SoftAssertions; import org.junit.jupiter.api.Assertions; import org.opentest4j.AssertionFailedError; import org.springframework.beans.factory.annotation.Autowired; @@ -107,36 +108,33 @@ public void notificationCanBeRetrievedWithIUNV2() { private void notificationCanBeRetrievedWithIUN(AtomicReference notificationByIun, Function getNotificationByIunFunction) { try { - assertSoftly(softly -> { - String iun = null; - - if (sharedSteps.getSentNotification() != null) { - iun = sharedSteps.getSentNotification().getIun(); - } else if (sharedSteps.getSentNotificationV1() != null) { - iun = sharedSteps.getSentNotificationV1().getIun(); - } else if (sharedSteps.getSentNotificationV2() != null) { - iun = sharedSteps.getSentNotificationV2().getIun(); - } - - softly.assertThat(iun) - .as("Verifica che l'IUN non sia nullo prima di cercare la notifica") + if (sharedSteps.getSentNotification() != null) { + assertThatCode(() -> + notificationByIun.set(getNotificationByIunFunction.apply(sharedSteps.getSentNotification().getIun())) + ).as("Il recupero della notifica con IUN '%s' non deve generare eccezioni", sharedSteps.getSentNotification().getIun()) + .doesNotThrowAnyException(); + } else if (sharedSteps.getSentNotificationV1() != null) { + assertThatCode(() -> + notificationByIun.set(getNotificationByIunFunction.apply(sharedSteps.getSentNotificationV1().getIun())) + ).as("Il recupero della notifica con IUN '%s' non deve generare eccezioni", sharedSteps.getSentNotificationV1().getIun()) + .doesNotThrowAnyException(); + } else if (sharedSteps.getSentNotificationV2() != null) { + assertThatCode(() -> + notificationByIun.set(getNotificationByIunFunction.apply(sharedSteps.getSentNotificationV2().getIun())) + ).as("Il recupero della notifica con IUN '%s' non deve generare eccezioni", sharedSteps.getSentNotificationV2().getIun()) + .doesNotThrowAnyException(); + } else { + assertThat(notificationByIun.get()) + .as("La notifica recuperata con IUN non deve essere nulla quando nessuna notifica inviata è disponibile") .isNotNull(); + } - if (iun != null) { // Evita NPE prima di applicare la funzione - T notification = getNotificationByIunFunction.apply(iun); - softly.assertThat(notification) - .as("Verifica che la notifica sia stata recuperata con successo") - .isNotNull(); - - notificationByIun.set(notification); - } + assertThat(notificationByIun.get()) + .as("La notifica recuperata con IUN non deve essere nulla dopo il recupero") + .isNotNull(); - softly.assertThat(notificationByIun.get()) - .as("Verifica che notificationByIun non sia nulla dopo il recupero") - .isNotNull(); - }); - } catch (AssertionError assertionFailedError) { - sharedSteps.throwAssertFailerWithIUN(assertionFailedError); + } catch (AssertionError assertionError) { + sharedSteps.throwAssertFailerWithIUN(assertionError); } } @@ -280,8 +278,9 @@ public void notificationFromADateCanBeRetrievedWithIUNWebPA(String stringDate, S private List searchNotificationWebFromADate(OffsetDateTime data) { AtomicReference notificationByIun = new AtomicReference<>(); - Assertions.assertDoesNotThrow(() -> - notificationByIun.set(webPaClient.searchSentNotification(data, data.plusDays(20), null, null, null, null, 50, null)) + Objects.requireNonNull( + webPaClient.searchSentNotification(data, data.plusDays(20), null, null, null, null, 50, null), + "Il risultato della ricerca delle notifiche inviate non deve essere nullo" ); assertSoftly(softly -> { @@ -1130,11 +1129,29 @@ public void controlloCampiAddressNormalizzatore() { log.info(" newAddress: {}", newAddress); - Assertions.assertEquals(newAddress.getAddress().toUpperCase(), normalizedAddress.getAddress()); - Assertions.assertEquals(newAddress.getMunicipality(), normalizedAddress.getMunicipality()); - Assertions.assertEquals(newAddress.getMunicipalityDetails(), normalizedAddress.getMunicipalityDetails()); - Assertions.assertEquals(newAddress.getProvince(), normalizedAddress.getProvince()); - Assertions.assertEquals(newAddress.getZip(), normalizedAddress.getZip()); + SoftAssertions softly = new SoftAssertions(); + + softly.assertThat(newAddress.getAddress().toUpperCase()) + .as("Confronto tra gli indirizzi normalizzati") + .isEqualTo(normalizedAddress.getAddress()); + + softly.assertThat(newAddress.getMunicipality()) + .as("Confronto tra i comuni normalizzati") + .isEqualTo(normalizedAddress.getMunicipality()); + + softly.assertThat(newAddress.getMunicipalityDetails()) + .as("Confronto tra i dettagli del comune normalizzati") + .isEqualTo(normalizedAddress.getMunicipalityDetails()); + + softly.assertThat(newAddress.getProvince()) + .as("Confronto tra le province normalizzate") + .isEqualTo(normalizedAddress.getProvince()); + + softly.assertThat(newAddress.getZip()) + .as("Confronto tra i CAP normalizzati") + .isEqualTo(normalizedAddress.getZip()); + + softly.assertAll(); } catch (AssertionFailedError error) { @@ -1282,9 +1299,9 @@ public void checkDocumentInviatiPaper(Integer destinatario, Integer allegati) { ); assertThat(documentiPec) - .as("La lista dei documenti analogici non dovrebbe essere nulla") + .as("La lista dei documenti analogici non dovrebbe essere nulla, l'API con Endpoint: /historical/received-message/"+sharedSteps.getIunVersionamento() +"/" +allegati) .isNotNull() - .isNotEmpty(); // Assicura che ci sia almeno un documento + .isNotEmpty(); log.info("documenti analogici : {}", documentiPec); @@ -1300,7 +1317,7 @@ public void checkDocumentInviatiPaper(Integer destinatario, Integer allegati) { assertThat(firstDocument.getPaperEngageRequest().getAttachments()) .as("Gli allegati del PaperEngageRequest non dovrebbero essere nulli") .isNotNull() - .hasSize(allegati); //* + .hasSize(allegati); } catch (AssertionFailedError assertionFailedError) { String message = assertionFailedError.getMessage() + " - Verifica Allegati analogici in errore."; From c49fabf3aca8a3f426c24636ed5f26b99c77d224 Mon Sep 17 00:00:00 2001 From: Tullio Ranieri Date: Wed, 19 Feb 2025 09:55:52 +0100 Subject: [PATCH 08/10] QA-5537 changed AssertionFailedError with AssertionError --- .../pa/AvanzamentoNotificheB2bSteps.java | 17 ++- .../steps/pa/InvioNotificheB2bSteps.java | 117 ++++++++---------- 2 files changed, 63 insertions(+), 71 deletions(-) diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java index 2c3664e4a..fbb49439b 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java @@ -143,7 +143,6 @@ public void readingEventUpToTheStatusOfNotification(String status) { PnPollingServiceStatusRapidV26 statusRapidV26 = (PnPollingServiceStatusRapidV26) pnPollingFactory.getPollingService(PnPollingStrategy.STATUS_RAPID_V26); - //NPE PnPollingResponseV26 pnPollingResponseV26 = statusRapidV26.waitForEvent(sharedSteps.getSentNotification().getIun(), PnPollingParameter.builder() .value(status) @@ -163,8 +162,8 @@ public void readingEventUpToTheStatusOfNotification(String status) { log.info("NOTIFICATION_STATUS_HISTORY_ELEMENT: {}", pnPollingResponseV26.getNotificationStatusHistoryElement()); - } catch (AssertionFailedError assertionFailedError) { - sharedSteps.throwAssertFailerWithIUN(assertionFailedError); + } catch (AssertionError assertionError) { + sharedSteps.throwAssertFailerWithIUN(assertionError); } } @@ -700,7 +699,7 @@ public TimelineElementV26 readingEventUpToTheTimelineElementOfNotificationForCat .value(timelineEventCategory) .build()); log.info("NOTIFICATION_TIMELINE: " + pnPollingResponseV26.getNotification().getTimeline()); -//NPE + try { assertThat(pnPollingResponseV26.getResult()) .as("Il risultato del polling dovrebbe essere valorizzato") @@ -718,8 +717,8 @@ public TimelineElementV26 readingEventUpToTheTimelineElementOfNotificationForCat return timelineElement; - } catch (AssertionFailedError assertionFailedError) { - sharedSteps.throwAssertFailerWithIUN(assertionFailedError); + } catch (AssertionError assertionError) { + sharedSteps.throwAssertFailerWithIUN(assertionError); } return null; @@ -939,8 +938,8 @@ public void readingEventUpToTheTimelineElementOfNotificationWithDeliveryDetailCo log.info("TIMELINE_ELEMENT: {}", pnPollingResponseV26.getTimelineElement()); } - } catch (AssertionFailedError assertionFailedError) { - sharedSteps.throwAssertFailerWithIUN(assertionFailedError); + } catch (AssertionError assertionError) { + sharedSteps.throwAssertFailerWithIUN(assertionError); } } @@ -3684,7 +3683,7 @@ public void TimelineElementOfNotificationUserCost(String timelineEventCategory, TimelineElementV26 event = readingEventUpToTheTimelineElementOfNotificationForCategoryUser(timelineEventCategory, destinatario); - //NPE + Long notificationCost = event.getDetails().getNotificationCost(); diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java index 8a8178849..d36144afa 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java @@ -134,7 +134,7 @@ private void notificationCanBeRetrievedWithIUN(AtomicReference notificati .isNotNull(); } catch (AssertionError assertionError) { - sharedSteps.throwAssertFailerWithIUN(assertionError); + sharedSteps.throwAssertFailerWithIUN(assertionError);//note } } @@ -183,8 +183,8 @@ public void notificationCanBeRetrievedWithIUNWebPA() { .isNotNull(); }); - } catch (AssertionFailedError assertionFailedError) { - sharedSteps.throwAssertFailerWithIUN(assertionFailedError); + } catch (AssertionError assertionError) { + sharedSteps.throwAssertFailerWithIUN(assertionError); } } @@ -227,10 +227,10 @@ public void notification120ggCanBeRetrievedWithIUNWebPA() { sharedSteps.setSentNotification(notifica120); - } catch (AssertionFailedError assertionFailedError) { - String message = assertionFailedError.getMessage() + + } catch (AssertionError assertionError) { + String message = assertionError.getMessage() + "{notifica : " + (notifica120 == null ? "NULL" : notifica120) + " }"; - throw new AssertionFailedError(message, assertionFailedError.getExpected(), assertionFailedError.getActual(), assertionFailedError.getCause()); + throw new AssertionError(message, assertionError); } } @@ -267,11 +267,10 @@ public void notificationFromADateCanBeRetrievedWithIUNWebPA(String stringDate, S notifica.setVat(22); sharedSteps.setSentNotification(notifica); - } catch (AssertionFailedError assertionFailedError) { - - String message = assertionFailedError.getMessage() + + } catch (AssertionError assertionError) { + String message = assertionError.getMessage() + "{notifica : " + (notifica == null ? "NULL" : notifica) + " }"; - throw new AssertionFailedError(message, assertionFailedError.getExpected(), assertionFailedError.getActual(), assertionFailedError.getCause()); + throw new AssertionError(message, assertionError); } } @@ -345,9 +344,10 @@ public void notificationCanBeRetrievedWithStatusByWebPA(String status, String pa .as("La notifica recuperata non deve essere nulla") .isNotNull(); }); - } catch (AssertionFailedError assertionFailedError) { - sharedSteps.throwAssertFailerWithIUN(assertionFailedError); + } catch (AssertionError assertionError) { + sharedSteps.throwAssertFailerWithIUN(assertionError); } + } @@ -437,8 +437,10 @@ public void retentionCheckLoadForTimelineElement(String documentType, String tim if (documentType.equals("ATTACHMENTS")) { for (int i = 0; i < sharedSteps.getSentNotification().getDocuments().size(); i++) { String key = sharedSteps.getSentNotification().getDocuments().get(i).getRef().getKey(); + assertThat(checkRetention(key, retentionTimeLoad, timelineElement.getTimestamp())) - .as("La verifica della retention ha fallito per la chiave '%s'", key) + .as("La verifica della retention ha fallito per la chiave '%s'. retentionTimeLoad: %d, timelineElement.getTimestamp: %s", + key, retentionTimeLoad, timelineElement.getTimestamp()) .isTrue(); } } else { @@ -568,7 +570,7 @@ public void documentDownloadPerDestinatario(String type, int destinatario) { @When("viene richiesto il download del documento {string} inesistente") public void documentAbsentDownload(String type) { - getDownloadFile(type, sharedSteps.getSentNotification().getIun(), 0); + getDownloadFile(type, sharedSteps.getSentNotification().getIun(), 0);//note } @When("viene richiesto il download del documento {string} inesistente per il destinatario {int}") @@ -911,11 +913,10 @@ public void verificaStatoPagamentoNotifica(String creditorTaxID, String noticeCo .isEqualToIgnoringCase(codiceErrore); - } catch (AssertionFailedError assertionFailedError) { - - String message = assertionFailedError.getMessage() + - "{Informazioni sullo stato del Pagamento: " + (paymentInfoResponse == null ? "NULL" : paymentInfoResponse.toString()) + " }"; - throw new AssertionFailedError(message, assertionFailedError.getExpected(), assertionFailedError.getActual(), assertionFailedError.getCause()); + } catch (AssertionError assertionError) { + String message = assertionError.getMessage() + + "{Informazioni sullo stato del Pagamento: " + (paymentInfoResponse == null ? "NULL" : paymentInfoResponse) + " }"; + throw new AssertionError(message, assertionError); } } @@ -948,11 +949,10 @@ public void verificaStatoPagamentoNotifica(String status) { .as("Lo stato nella risposta dovrebbe essere uguale a "+status , status) .isEqualToIgnoringCase(status); - } catch (AssertionFailedError assertionFailedError) { - - String message = assertionFailedError.getMessage() + + } catch (AssertionError assertionError) { + String message = assertionError.getMessage() + "{Informazioni sullo stato del Pagamento: " + (paymentInfoResponse == null ? "NULL" : paymentInfoResponse.toString()) + " }"; - throw new AssertionFailedError(message, assertionFailedError.getExpected(), assertionFailedError.getActual(), assertionFailedError.getCause()); + throw new AssertionError(message, assertionError); } } @@ -1006,9 +1006,10 @@ public void notificationCanBeRetrievePaymentV1() { .as("Il pagamento del primo destinatario della notifica non dovrebbe essere nullo") .isNotNull(); - } catch (AssertionFailedError assertionFailedError) { - sharedSteps.throwAssertFailerWithIUN(assertionFailedError); + } catch (AssertionError assertionError) { + sharedSteps.throwAssertFailerWithIUN(assertionError); } + } @And("la notifica a 2 avvisi di pagamento con OpenApi V2") @@ -1032,9 +1033,10 @@ public void notificationCanBeRetrievePaymentV2() { .as("Il codice alternativo della notifica del pagamento non dovrebbe essere nullo") .isNotNull(); - } catch (AssertionFailedError assertionFailedError) { - sharedSteps.throwAssertFailerWithIUN(assertionFailedError); + } catch (AssertionError assertionError) { + sharedSteps.throwAssertFailerWithIUN(assertionError); } + } @And("la notifica a 1 avvisi di pagamento con OpenApi V1") @@ -1057,9 +1059,10 @@ public void notificationCanBeRetrievePayment1V1() { .isNotNull(); - } catch (AssertionFailedError assertionFailedError) { - sharedSteps.throwAssertFailerWithIUN(assertionFailedError); + } catch (AssertionError assertionError) { + sharedSteps.throwAssertFailerWithIUN(assertionError); } + } @And("Si effettua la chiamata su external-reg per ricevere l'url di checkout con noticeCode {string} e creditorTaxId {string}") @@ -1095,11 +1098,12 @@ private void verifyCheckoutCart(BffPaymentRequest paymentRequest, String codiceE Assertions.assertTrue(codiceErrore.equalsIgnoreCase(paymentInfoResponse.get(0).getErrorCode())); Assertions.assertTrue(codiceErrore.equalsIgnoreCase(paymentResponse.getCheckoutUrl())); } - } catch (AssertionFailedError assertionFailedError) { - String message = assertionFailedError.getMessage() + + } catch (AssertionError assertionError) { + String message = assertionError.getMessage() + "{la posizione debitoria " + (paymentResponse == null ? "NULL" : paymentResponse.toString()) + " }"; - throw new AssertionFailedError(message, assertionFailedError.getExpected(), assertionFailedError.getActual(), assertionFailedError.getCause()); + throw new AssertionError(message, assertionError); } + } @Then("si verifica che il phyicalAddress sia stato normalizzato correttamente con rimozione caratteri isoLatin1") @@ -1154,9 +1158,10 @@ public void controlloCampiAddressNormalizzatore() { softly.assertAll(); - } catch (AssertionFailedError error) { + } catch (AssertionError error) { sharedSteps.throwAssertFailerWithIUN(error); } + } private BffPaymentRequest getPaymentRequest(NotificationPriceResponseV23 notificationPrice, String noticeNumber, String fiscalCode, String companyName, Integer amount, String description, String returnUrl) { @@ -1270,11 +1275,12 @@ public void verificaSHAAllegatiPecDelDestinatario(Integer destinatario, String t } Assertions.assertTrue(checkAllegati); - } catch (AssertionFailedError assertionFailedError) { - String message = assertionFailedError.getMessage() + - "Verifica Allegati pec in errore "; - throw new AssertionFailedError(message, assertionFailedError.getExpected(), assertionFailedError.getActual(), assertionFailedError.getCause()); + } catch (AssertionError assertionError) { + String message = assertionError.getMessage() + + " Verifica Allegati pec in errore."; + throw new AssertionError(message, assertionError); } + } @And("si verifica il contenuto della pec abbia {int} attachment di tipo {string}") @@ -1294,33 +1300,18 @@ public void presenzaAttachment(Integer numeroDocumenti, String tipologia) { @And("si verifica il contenuto degli attachments da inviare in via cartacea al destinatario {int} con {int} allegati") public void checkDocumentInviatiPaper(Integer destinatario, Integer allegati) { try { - this.documentiPec = pnExternalChannelsServiceClientImpl.getReceivedMessagesAnalogico( - sharedSteps.getIunVersionamento(), destinatario - ); + this.documentiPec = pnExternalChannelsServiceClientImpl.getReceivedMessagesAnalogico(sharedSteps.getIunVersionamento(), destinatario); - assertThat(documentiPec) - .as("La lista dei documenti analogici non dovrebbe essere nulla, l'API con Endpoint: /historical/received-message/"+sharedSteps.getIunVersionamento() +"/" +allegati) - .isNotNull() - .isNotEmpty(); - log.info("documenti analogici : {}", documentiPec); - - ReceivedMessage firstDocument = documentiPec.get(0); - assertThat(firstDocument) - .as("Il primo documento ricevuto non dovrebbe essere nullo") - .isNotNull(); + Assertions.assertNotNull(documentiPec, "La lista dei documenti PEC ricevuti è nulla o vuota per il destinatario " + destinatario+" l'API con Endpoint: /historical/received-message/"+sharedSteps.getIunVersionamento() +"/"+destinatario+" Non ha restituito risultati"); - assertThat(firstDocument.getPaperEngageRequest()) - .as("Il PaperEngageRequest del primo documento non dovrebbe essere nullo") - .isNotNull(); + log.info("documenti analogici : {}", documentiPec); - assertThat(firstDocument.getPaperEngageRequest().getAttachments()) - .as("Gli allegati del PaperEngageRequest non dovrebbero essere nulli") - .isNotNull() - .hasSize(allegati); + Assertions.assertEquals(allegati, documentiPec.get(0).getPaperEngageRequest().getAttachments().size(), + "Il numero di allegati ricevuti è diverso da quello atteso. Expected: " + allegati + ", Actual: " + documentiPec.get(0).getPaperEngageRequest().getAttachments().size()); } catch (AssertionFailedError assertionFailedError) { - String message = assertionFailedError.getMessage() + " - Verifica Allegati analogici in errore."; + String message = assertionFailedError.getMessage() + " Verifica Allegati analogici in errore "; throw new AssertionFailedError(message, assertionFailedError.getExpected(), assertionFailedError.getActual(), assertionFailedError.getCause()); } } @@ -1336,7 +1327,8 @@ public void presenceAttachmentAnalogicFlow(Integer numeroDocumenti, String tipol .filter(uri -> uri.contains(tipologia)) .toList(); try { - Assertions.assertEquals(numeroDocumenti, attachmentsUri.size()); + Assertions.assertEquals(numeroDocumenti, attachmentsUri.size(), + "Il numero di allegati di tipo '" + tipologia + "' è diverso da quello atteso. Expected: " + numeroDocumenti + ", Actual: " + attachmentsUri.size()); } catch (AssertionFailedError assertionFailedError) { String message = assertionFailedError.getMessage() + " - Verifica Allegati Cartacei in errore."; throw new AssertionFailedError(message, assertionFailedError.getExpected(), assertionFailedError.getActual(), assertionFailedError.getCause()); @@ -1402,9 +1394,10 @@ public void siRichiamaCheckoutConDati(Map dataCheckout) { .isNotNull(); log.info("response checkout: {}", responseCheckout); - } catch (AssertionFailedError error) { - throw error; - } + } catch (AssertionError error) { + throw error; + } + } @Given("si richiama checkout con restituzione errore") From 04a5551f65e945f53befc00abe35333dcab5d668 Mon Sep 17 00:00:00 2001 From: Tullio Ranieri Date: Wed, 19 Feb 2025 12:57:43 +0100 Subject: [PATCH 09/10] QA-5637 removed comments --- .../pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java index d36144afa..7a41963df 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/InvioNotificheB2bSteps.java @@ -134,7 +134,7 @@ private void notificationCanBeRetrievedWithIUN(AtomicReference notificati .isNotNull(); } catch (AssertionError assertionError) { - sharedSteps.throwAssertFailerWithIUN(assertionError);//note + sharedSteps.throwAssertFailerWithIUN(assertionError); } } @@ -570,7 +570,7 @@ public void documentDownloadPerDestinatario(String type, int destinatario) { @When("viene richiesto il download del documento {string} inesistente") public void documentAbsentDownload(String type) { - getDownloadFile(type, sharedSteps.getSentNotification().getIun(), 0);//note + getDownloadFile(type, sharedSteps.getSentNotification().getIun(), 0); } @When("viene richiesto il download del documento {string} inesistente per il destinatario {int}") @@ -633,7 +633,7 @@ public void operationProducedAnErrorWithMessage(String statusCode, String errore assertSoftly(softly -> { softly.assertThat(httpStatusCodeException) - .as("Verifica che l'eccezione non sia nulla") + .as("Verifica che l' http status code dell'eccezione in SharedSteps non sia nulla") .isNotNull(); if (httpStatusCodeException != null) { From 6612c374a23ada3aad55a3d2972da68fc24d0dd7 Mon Sep 17 00:00:00 2001 From: Tullio Ranieri Date: Wed, 5 Mar 2025 09:17:37 +0100 Subject: [PATCH 10/10] QA-5637 refactor error message --- .../pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java b/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java index 39c33f1b9..78e7ff5de 100644 --- a/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java +++ b/src/test/java/it/pagopa/pn/cucumber/steps/pa/AvanzamentoNotificheB2bSteps.java @@ -718,7 +718,7 @@ public TimelineElementV26 readingEventUpToTheTimelineElementOfNotificationForCat try { assertThat(pnPollingResponseV26.getResult()) - .as("Il risultato del polling dovrebbe essere valorizzato") + .as("Il risultato del polling dovrebbe essere valorizzato, Primo controllo: Verificare che l'elemento sia presente in timeline e le tempistiche con cui viene prodotto") .isTrue(); assertThat(pnPollingResponseV26.getTimelineElement())