From 69c655ba0306000c08da4ad79735c588043efc8b Mon Sep 17 00:00:00 2001 From: Vitolo-Andrea <157486351+Vitolo-Andrea@users.noreply.github.com> Date: Tue, 6 Feb 2024 17:17:44 +0100 Subject: [PATCH 01/16] [IDP-2288] Changed test class name (#249) --- ...onsumerConfigIntegrationTestDeprecated.java} | 12 +++++++----- ...onsumerConfigIntegrationTestDeprecated.java} | 3 ++- ...ityProcessorConfigFamilyTestDeprecated.java} | 7 ++++--- ...tyProcessorConfigRankingTestDeprecated.java} | 7 ++++--- ...ssibilityProcessorConfigTestDeprecated.java} | 17 +++++++++-------- ...FamilyMockRestClientImplTestDeprecated.java} | 3 ++- ...oapClientImplIntegrationTestDeprecated.java} | 3 ++- ...IseeConsultationSoapClientImplSSLKOTest.java | 2 +- ...iaCodeServiceIntegrationTestDeprecated.java} | 3 ++- ...rieverServiceIntegrationTestDeprecated.java} | 3 ++- ...HolderServiceIntegrationTestDeprecated.java} | 3 ++- 11 files changed, 37 insertions(+), 26 deletions(-) rename src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/{BeneficiaryRuleBuilderConsumerConfigIntegrationTest.java => BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.java} (97%) rename src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/{CommandConsumerConfigIntegrationTest.java => CommandConsumerConfigIntegrationTestDeprecated.java} (98%) rename src/test/java/it/gov/pagopa/admissibility/connector/event/processor/{AdmissibilityProcessorConfigFamilyTest.java => AdmissibilityProcessorConfigFamilyTestDeprecated.java} (98%) rename src/test/java/it/gov/pagopa/admissibility/connector/event/processor/{AdmissibilityProcessorConfigRankingTest.java => AdmissibilityProcessorConfigRankingTestDeprecated.java} (96%) rename src/test/java/it/gov/pagopa/admissibility/connector/event/processor/{AdmissibilityProcessorConfigTest.java => AdmissibilityProcessorConfigTestDeprecated.java} (98%) rename src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/{FamilyMockRestClientImplTest.java => FamilyMockRestClientImplTestDeprecated.java} (87%) rename src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/{IseeConsultationSoapClientImplIntegrationTest.java => IseeConsultationSoapClientImplIntegrationTestDeprecated.java} (96%) rename src/test/java/it/gov/pagopa/admissibility/service/{CriteriaCodeServiceIntegrationTest.java => CriteriaCodeServiceIntegrationTestDeprecated.java} (90%) rename src/test/java/it/gov/pagopa/admissibility/service/onboarding/{AuthoritiesDataRetrieverServiceIntegrationTest.java => AuthoritiesDataRetrieverServiceIntegrationTestDeprecated.java} (96%) rename src/test/java/it/gov/pagopa/admissibility/service/onboarding/{OnboardingContextHolderServiceIntegrationTest.java => OnboardingContextHolderServiceIntegrationTestDeprecated.java} (98%) diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/BeneficiaryRuleBuilderConsumerConfigIntegrationTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.java similarity index 97% rename from src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/BeneficiaryRuleBuilderConsumerConfigIntegrationTest.java rename to src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.java index 30e2daa4..9ac6afe6 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/BeneficiaryRuleBuilderConsumerConfigIntegrationTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.java @@ -40,7 +40,8 @@ "logging.level.it.gov.pagopa.common.reactive.kafka.consumer.BaseKafkaConsumer=WARN", "logging.level.it.gov.pagopa.common.reactive.utils.PerformanceLogger=WARN", }) -public class BeneficiaryRuleBuilderConsumerConfigIntegrationTest extends BaseIntegrationTest { +@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) +public class BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated extends BaseIntegrationTest { @SpyBean private KieContainerBuilderService kieContainerBuilderServiceSpy; @@ -108,7 +109,7 @@ Time spent to assert drools rule count (from previous check): %d millis ); long timeCommitCheckStart = System.currentTimeMillis(); - final Map srcCommitOffsets = kafkaTestUtilitiesService.checkCommittedOffsets(topicBeneficiaryRuleConsumer, groupIdBeneficiaryRuleConsumer,initiativePayloads.size()+1); // +1 due to other applicationName useCase + final Map srcCommitOffsets = kafkaTestUtilitiesService.checkCommittedOffsets(topicBeneficiaryRuleConsumer, groupIdBeneficiaryRuleConsumer, initiativePayloads.size() + 1); // +1 due to other applicationName useCase long timeCommitCheckEnd = System.currentTimeMillis(); System.out.printf(""" ************************ @@ -170,19 +171,20 @@ private void checkInitiativeCounters(int expectedInitiativeNumber) { //region not valid useCases // all use cases configured must have a unique id recognized by the regexp errorUseCaseIdPatternMatch private final List, Consumer>>> errorUseCases = new ArrayList<>(); + { String useCaseJsonNotExpected = "{\"initiativeId\":\"INITIATIVEID_0\",unexpectedStructure:0}"; errorUseCases.add(Pair.of( () -> useCaseJsonNotExpected, errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_RULE_BUILD] Unexpected JSON", useCaseJsonNotExpected) )); - + String jsonNotValid = "{\"initiativeId\":\"INITIATIVEID_1\",invalidJson"; errorUseCases.add(Pair.of( () -> jsonNotValid, errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_RULE_BUILD] Unexpected JSON", jsonNotValid) )); - + String criteriaCodeNotValid = TestUtils.jsonSerializer(Initiative2BuildDTOFaker.mockInstanceBuilder(errorUseCases.size()) .beneficiaryRule(InitiativeBeneficiaryRuleDTO.builder() .automatedCriteria(List.of( @@ -202,7 +204,7 @@ private void checkInitiativeCounters(int expectedInitiativeNumber) { .build()); errorUseCases.add(Pair.of( () -> { - Mockito.doReturn(Mono.error(new RuntimeException("DUMMYEXCEPTION"))).when(droolsRuleRepositorySpy).save(Mockito.argThat(i->errorWhenSavingUseCaseId.equals(i.getId()))); + Mockito.doReturn(Mono.error(new RuntimeException("DUMMYEXCEPTION"))).when(droolsRuleRepositorySpy).save(Mockito.argThat(i -> errorWhenSavingUseCaseId.equals(i.getId()))); return droolRuleSaveInError; }, errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_RULE_BUILD] An error occurred handling initiative", droolRuleSaveInError) diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/CommandConsumerConfigIntegrationTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/CommandConsumerConfigIntegrationTestDeprecated.java similarity index 98% rename from src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/CommandConsumerConfigIntegrationTest.java rename to src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/CommandConsumerConfigIntegrationTestDeprecated.java index 1759c36d..202bd5e0 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/CommandConsumerConfigIntegrationTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/CommandConsumerConfigIntegrationTestDeprecated.java @@ -38,7 +38,8 @@ "logging.level.it.gov.pagopa.admissibility.service.onboarding.OnboardingContextHolderServiceImpl=WARN", "logging.level.it.gov.pagopa.common.reactive.utils.PerformanceLogger=WARN" }) -class CommandConsumerConfigIntegrationTest extends BaseIntegrationTest { +@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) +class CommandConsumerConfigIntegrationTestDeprecated extends BaseIntegrationTest { private final String INITIATIVEID = "INITIATIVEID_%d"; private final Set INITIATIVES_DELETED = new HashSet<>(); @SpyBean diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigFamilyTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigFamilyTestDeprecated.java similarity index 98% rename from src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigFamilyTest.java rename to src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigFamilyTestDeprecated.java index 4cc5c0a7..befba8a1 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigFamilyTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigFamilyTestDeprecated.java @@ -1,7 +1,7 @@ package it.gov.pagopa.admissibility.connector.event.processor; import com.fasterxml.jackson.core.JsonProcessingException; -import it.gov.pagopa.admissibility.connector.event.consumer.BeneficiaryRuleBuilderConsumerConfigIntegrationTest; +import it.gov.pagopa.admissibility.connector.event.consumer.BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated; import it.gov.pagopa.admissibility.connector.repository.InitiativeCountersRepository; import it.gov.pagopa.admissibility.connector.repository.OnboardingFamiliesRepository; import it.gov.pagopa.admissibility.dto.onboarding.*; @@ -42,7 +42,8 @@ import java.util.stream.IntStream; @ContextConfiguration -class AdmissibilityProcessorConfigFamilyTest extends BaseAdmissibilityProcessorConfigTest { +@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) +class AdmissibilityProcessorConfigFamilyTestDeprecated extends BaseAdmissibilityProcessorConfigTest { @TestConfiguration static class MediatorSpyConfiguration extends BaseAdmissibilityProcessorConfigTest.MediatorSpyConfiguration {} @@ -165,7 +166,7 @@ private void publishOnboardingRules() { .peek(i -> kafkaTestUtilitiesService.publishIntoEmbeddedKafka(topicBeneficiaryRuleConsumer, null, null, i)) .toList(); - BeneficiaryRuleBuilderConsumerConfigIntegrationTest.waitForKieContainerBuild(expectedRules[0], onboardingContextHolderServiceSpy); + BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.waitForKieContainerBuild(expectedRules[0], onboardingContextHolderServiceSpy); MongoTestUtilitiesService.stopAndPrintMongoCommands(); } diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigRankingTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigRankingTestDeprecated.java similarity index 96% rename from src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigRankingTest.java rename to src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigRankingTestDeprecated.java index 60756b7e..8b55e3bb 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigRankingTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigRankingTestDeprecated.java @@ -1,7 +1,7 @@ package it.gov.pagopa.admissibility.connector.event.processor; import com.fasterxml.jackson.core.JsonProcessingException; -import it.gov.pagopa.admissibility.connector.event.consumer.BeneficiaryRuleBuilderConsumerConfigIntegrationTest; +import it.gov.pagopa.admissibility.connector.event.consumer.BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated; import it.gov.pagopa.admissibility.dto.onboarding.OnboardingDTO; import it.gov.pagopa.admissibility.dto.onboarding.RankingRequestDTO; import it.gov.pagopa.admissibility.dto.onboarding.extra.BirthDate; @@ -35,7 +35,8 @@ import java.util.stream.IntStream; @ContextConfiguration -class AdmissibilityProcessorConfigRankingTest extends BaseAdmissibilityProcessorConfigTest { +@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) +class AdmissibilityProcessorConfigRankingTestDeprecated extends BaseAdmissibilityProcessorConfigTest { private static final String INITIATIVEID = "INITIATIVEID_0"; @@ -120,7 +121,7 @@ private void publishOnboardingRules(int onboardingsNumber) { .peek(i -> expectedRules[0] += i.getBeneficiaryRule().getAutomatedCriteria().size()) .forEach(i -> kafkaTestUtilitiesService.publishIntoEmbeddedKafka(topicBeneficiaryRuleConsumer, null, null, i)); - BeneficiaryRuleBuilderConsumerConfigIntegrationTest.waitForKieContainerBuild(expectedRules[0], onboardingContextHolderServiceSpy); + BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.waitForKieContainerBuild(expectedRules[0], onboardingContextHolderServiceSpy); MongoTestUtilitiesService.stopAndPrintMongoCommands(); } diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigTestDeprecated.java similarity index 98% rename from src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigTest.java rename to src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigTestDeprecated.java index af76af0c..95d0028b 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigTestDeprecated.java @@ -2,9 +2,9 @@ import com.fasterxml.jackson.core.JsonProcessingException; import it.gov.pagopa.admissibility.config.PagoPaAnprPdndConfig; -import it.gov.pagopa.admissibility.connector.event.consumer.BeneficiaryRuleBuilderConsumerConfigIntegrationTest; +import it.gov.pagopa.admissibility.connector.event.consumer.BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated; import it.gov.pagopa.admissibility.connector.rest.anpr.service.AnprC001RestClientImplIntegrationTest; -import it.gov.pagopa.admissibility.connector.soap.inps.service.IseeConsultationSoapClientImplIntegrationTest; +import it.gov.pagopa.admissibility.connector.soap.inps.service.IseeConsultationSoapClientImplIntegrationTestDeprecated; import it.gov.pagopa.admissibility.drools.model.filter.FilterOperator; import it.gov.pagopa.admissibility.dto.onboarding.EvaluationCompletedDTO; import it.gov.pagopa.admissibility.dto.onboarding.OnboardingDTO; @@ -58,7 +58,7 @@ import java.util.stream.IntStream; import java.util.stream.Stream; -@ContextConfiguration(classes = {AdmissibilityProcessorConfigTest.MediatorSpyConfiguration.class}) +@ContextConfiguration(classes = {AdmissibilityProcessorConfigTestDeprecated.MediatorSpyConfiguration.class}) @TestPropertySource(properties = { "logging.level.it.gov.pagopa.admissibility.service.onboarding.check.OnboardingInitiativeCheck=OFF", "logging.level.it.gov.pagopa.admissibility.service.onboarding.OnboardingContextHolderServiceImpl=OFF", @@ -66,14 +66,15 @@ "logging.level.it.gov.pagopa.admissibility.connector.soap.inps.service.IseeConsultationSoapClientImpl=OFF", "logging.level.it.gov.pagopa.common.reactive.pdnd.service.BaseRestPdndServiceClient=OFF", }) -class AdmissibilityProcessorConfigTest extends BaseAdmissibilityProcessorConfigTest { +@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) +class AdmissibilityProcessorConfigTestDeprecated extends BaseAdmissibilityProcessorConfigTest { public static final String CF_AUTHORITIES_DATA_ALLOWED = "CF_OK_2"; public static final String CF_INVALID_REQUEST = AnprC001RestClientImplIntegrationTest.FISCAL_CODE_INVALIDREQUEST; - public static final String CF_INPS_RETRY = IseeConsultationSoapClientImplIntegrationTest.FISCAL_CODE_RETRY; - public static final String CF_INPS_UNEXPECTED_RESULTCODE = IseeConsultationSoapClientImplIntegrationTest.FISCAL_CODE_UNEXPECTED_RESULT_CODE; + public static final String CF_INPS_RETRY = IseeConsultationSoapClientImplIntegrationTestDeprecated.FISCAL_CODE_RETRY; + public static final String CF_INPS_UNEXPECTED_RESULTCODE = IseeConsultationSoapClientImplIntegrationTestDeprecated.FISCAL_CODE_UNEXPECTED_RESULT_CODE; public static final String CF_NOT_FOUND = AnprC001RestClientImplIntegrationTest.FISCAL_CODE_NOTFOUND; public static final String CF_ANPR_TOO_MANY_REQUESTS = AnprC001RestClientImplIntegrationTest.FISCAL_CODE_TOOMANYREQUESTS; - public static final String CF_INPS_TOO_MANY_REQUESTS = IseeConsultationSoapClientImplIntegrationTest.FISCAL_CODE_TOOMANYREQUESTS; + public static final String CF_INPS_TOO_MANY_REQUESTS = IseeConsultationSoapClientImplIntegrationTestDeprecated.FISCAL_CODE_TOOMANYREQUESTS; private static final String INITIATIVEID_EXHAUSTED = "EXHAUSTED_INITIATIVE_ID"; private static final String INITIATIVEID_FAILING_BUDGET_RESERVATION = "FAILING_BUDGET_RESERVATION"; @@ -352,7 +353,7 @@ private void publishOnboardingRules(int validOnboardings) { .peek(i -> expectedRules[0] += i.getBeneficiaryRule().getAutomatedCriteria().size()) .forEach(i -> kafkaTestUtilitiesService.publishIntoEmbeddedKafka(topicBeneficiaryRuleConsumer, null, null, i)); - BeneficiaryRuleBuilderConsumerConfigIntegrationTest.waitForKieContainerBuild(expectedRules[0], onboardingContextHolderServiceSpy); + BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.waitForKieContainerBuild(expectedRules[0], onboardingContextHolderServiceSpy); MongoTestUtilitiesService.stopAndPrintMongoCommands(); } diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestDeprecated.java similarity index 87% rename from src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java rename to src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestDeprecated.java index 3711e45b..7acb5035 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestDeprecated.java @@ -12,7 +12,8 @@ "app.idpay-mock.retry.max-attempts=1", "app.idpay-mock.retry.delay-millis=100" }) -class FamilyMockRestClientImplTest extends BaseIntegrationTest { +@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) +class FamilyMockRestClientImplTestDeprecated extends BaseIntegrationTest { @Autowired diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTestDeprecated.java similarity index 96% rename from src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTest.java rename to src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTestDeprecated.java index 7cc6d253..3fe2dc20 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTestDeprecated.java @@ -20,7 +20,8 @@ "logging.level.it.gov.pagopa.common.soap.service.SoapLoggingHandler=DEBUG" }) @DirtiesContext -public class IseeConsultationSoapClientImplIntegrationTest extends BaseIntegrationTest { +@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) +public class IseeConsultationSoapClientImplIntegrationTestDeprecated extends BaseIntegrationTest { public static final String FISCAL_CODE_OK = "CF_OK"; public static final String FISCAL_CODE_NOTFOUND = "CF_NOT_FOUND"; diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java index 198e59c2..04d39328 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java @@ -24,7 +24,7 @@ void testKo(){ SummaryGeneratingListener listener = new SummaryGeneratingListener(); LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() - .selectors(selectMethod(IseeConsultationSoapClientImplIntegrationTest.class, "callService")) + .selectors(selectMethod(IseeConsultationSoapClientImplIntegrationTestDeprecated.class, "callService")) .build(); Launcher launcher = LauncherFactory.create(); launcher.discover(request); diff --git a/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodeServiceIntegrationTest.java b/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodeServiceIntegrationTestDeprecated.java similarity index 90% rename from src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodeServiceIntegrationTest.java rename to src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodeServiceIntegrationTestDeprecated.java index e74cdb62..4442d282 100644 --- a/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodeServiceIntegrationTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodeServiceIntegrationTestDeprecated.java @@ -13,7 +13,8 @@ @TestPropertySource(properties = { "logging.level.it.gov.pagopa.admissibility.service.CriteriaCodeServiceImpl=WARN", }) -class CriteriaCodeServiceIntegrationTest extends BaseIntegrationTest { +@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) +class CriteriaCodeServiceIntegrationTestDeprecated extends BaseIntegrationTest { @Autowired private CriteriaCodesConfiguration criteriaCodesConfiguration; diff --git a/src/test/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceIntegrationTest.java b/src/test/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceIntegrationTestDeprecated.java similarity index 96% rename from src/test/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceIntegrationTest.java rename to src/test/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceIntegrationTestDeprecated.java index b59c77a2..a8eb78d3 100644 --- a/src/test/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceIntegrationTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceIntegrationTestDeprecated.java @@ -27,7 +27,8 @@ @TestPropertySource(properties = { "logging.level.it.gov.pagopa.admissibility.service.AuthoritiesDataRetrieverServiceImpl=WARN", }) -class AuthoritiesDataRetrieverServiceIntegrationTest extends BaseIntegrationTest { +@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) +class AuthoritiesDataRetrieverServiceIntegrationTestDeprecated extends BaseIntegrationTest { private static final IseeTypologyEnum ISEE_TYPE = IseeTypologyEnum.ORDINARIO; @Autowired diff --git a/src/test/java/it/gov/pagopa/admissibility/service/onboarding/OnboardingContextHolderServiceIntegrationTest.java b/src/test/java/it/gov/pagopa/admissibility/service/onboarding/OnboardingContextHolderServiceIntegrationTestDeprecated.java similarity index 98% rename from src/test/java/it/gov/pagopa/admissibility/service/onboarding/OnboardingContextHolderServiceIntegrationTest.java rename to src/test/java/it/gov/pagopa/admissibility/service/onboarding/OnboardingContextHolderServiceIntegrationTestDeprecated.java index 99f08183..3e01adfb 100644 --- a/src/test/java/it/gov/pagopa/admissibility/service/onboarding/OnboardingContextHolderServiceIntegrationTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/service/onboarding/OnboardingContextHolderServiceIntegrationTestDeprecated.java @@ -34,7 +34,8 @@ } ) @ContextConfiguration(classes = EmbeddedRedisTestConfiguration.class) -class OnboardingContextHolderServiceIntegrationTest extends BaseIntegrationTest { +@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) +class OnboardingContextHolderServiceIntegrationTestDeprecated extends BaseIntegrationTest { @Autowired private KieContainerBuilderService kieContainerBuilderService; @Autowired From c5576df97caac0ab708a10f8aa336e2efac19bd8 Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Thu, 22 Feb 2024 16:39:44 +0100 Subject: [PATCH 02/16] IDP-2293 Added two test classes --- .../mock/FamilyMockRestClientImplTest.java | 64 +++++++++++++++++++ .../CriteriaCodesConfigurationTest.java | 37 +++++++++++ 2 files changed, 101 insertions(+) create mode 100644 src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java create mode 100644 src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodesConfigurationTest.java diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java new file mode 100644 index 00000000..e51405e0 --- /dev/null +++ b/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java @@ -0,0 +1,64 @@ +package it.gov.pagopa.admissibility.connector.rest.mock; + +import com.github.tomakehurst.wiremock.WireMockServer; +import it.gov.pagopa.admissibility.dto.onboarding.extra.Family; +import it.gov.pagopa.common.reactive.rest.config.WebClientConfig; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import reactor.core.Exceptions; + +@ExtendWith(SpringExtension.class) +@AutoConfigureWireMock(stubs ="classpath:/stub/mappings/mock" ,port =800) +@ContextConfiguration( + classes = { + FamilyMockRestClientImpl.class, + WebClientConfig.class, + WireMockServer.class + }) +@TestPropertySource( + locations = "classpath:application.yml", + properties = {"spring.application.name=idpay-admissibility-assessor", + "app.idpay-mock.base-url=http://localhost:${wiremock.server.port}/pdndMock", + //Region familyMockRestClient + "app.idpay-mock.retry.delay-millis=1", + "app.idpay-mock.retry.max-attempts=5", + //endRegion + + //Region webClientConfig + "app.web-client.connect.timeout.millis=10000", + "app.web-client.response.timeout=60000", + "app.web-client.read.handler.timeout=60000", + "app.web-client.write.handler.timeout=60000" + //endRegion + }) +@Slf4j +class FamilyMockRestClientImplTest { + @Autowired + private FamilyMockRestClientImpl familyMockRestClient; + @Autowired + private WireMockServer wireMockServer; + + @Test + void givenUserIdWhenCallFamilyMockRestClientThenFamily() { + + Family family = familyMockRestClient.retrieveFamily("userId_1").block(); + Assertions.assertEquals(3,family.getMemberIds().size()); + } + + @Test + void givenUserIdWhenCallFamilyMockRestClientThenTooManyRequestException(){ + try{ + familyMockRestClient.retrieveFamily("USERID_TOOMANYREQUEST_1").block(); + Assertions.fail(); + }catch (Throwable e){ + Assertions.assertTrue(Exceptions.isRetryExhausted(e)); + } + } +} diff --git a/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodesConfigurationTest.java b/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodesConfigurationTest.java new file mode 100644 index 00000000..2960190d --- /dev/null +++ b/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodesConfigurationTest.java @@ -0,0 +1,37 @@ +package it.gov.pagopa.admissibility.service; + +import it.gov.pagopa.admissibility.config.CriteriaCodesConfiguration; +import it.gov.pagopa.admissibility.model.CriteriaCodeConfig; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Map; +@ExtendWith(MockitoExtension.class) +class CriteriaCodesConfigurationTest { + @Mock + private CriteriaCodesConfiguration criteriaCodesConfiguration; + + @Test + void givenGetCriteriaCongigsThenReturnMapOfCriteriaCodeConfig(){ + //Given + Map expected = Map.of( + "ISEE", new CriteriaCodeConfig("ISEE", "INPS", "Istituto Nazionale Previdenza Sociale", "isee"), + "BIRTHDATE", new CriteriaCodeConfig("BIRTHDATE", "AGID", "Agenzia per l'Italia Digitale", "birthDate"), + "RESIDENCE", new CriteriaCodeConfig("RESIDENCE", "AGID","Agenzia per l'Italia Digitale", "residence"), + "FAMILY", new CriteriaCodeConfig("FAMILY", "INPS","Istituto Nazionale Previdenza Sociale", "family") + ); + + Mockito.when(criteriaCodesConfiguration.getCriteriaCodeConfigs()).thenReturn(expected); + //When + Map result = criteriaCodesConfiguration.getCriteriaCodeConfigs(); + + //then + Assertions.assertNotNull(result); + Assertions.assertEquals(expected, result); + Assertions.assertEquals(4,result.size()); + } +} From 090618b27a470f798a95fd04b2c1b296d679f991 Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Fri, 23 Feb 2024 17:48:48 +0100 Subject: [PATCH 03/16] IDP-2293 Added and updated test --- .../CriteriaCodesConfigurationTest.java | 20 ++- .../CommandMediatorServiceImplTest.java | 149 ++++++++++++++++++ 2 files changed, 162 insertions(+), 7 deletions(-) create mode 100644 src/test/java/it/gov/pagopa/admissibility/service/commands/CommandMediatorServiceImplTest.java diff --git a/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodesConfigurationTest.java b/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodesConfigurationTest.java index 2960190d..9539600f 100644 --- a/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodesConfigurationTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodesConfigurationTest.java @@ -3,6 +3,7 @@ import it.gov.pagopa.admissibility.config.CriteriaCodesConfiguration; import it.gov.pagopa.admissibility.model.CriteriaCodeConfig; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; @@ -12,8 +13,13 @@ import java.util.Map; @ExtendWith(MockitoExtension.class) class CriteriaCodesConfigurationTest { - @Mock - private CriteriaCodesConfiguration criteriaCodesConfiguration; + @Mock private CriteriaCodesConfiguration criteriaCodesConfigurationMock; + private CriteriaCodeServiceImpl criteriaCodesService; + + @BeforeEach + void setUp() { + criteriaCodesService = new CriteriaCodeServiceImpl(criteriaCodesConfigurationMock); + } @Test void givenGetCriteriaCongigsThenReturnMapOfCriteriaCodeConfig(){ @@ -25,13 +31,13 @@ void givenGetCriteriaCongigsThenReturnMapOfCriteriaCodeConfig(){ "FAMILY", new CriteriaCodeConfig("FAMILY", "INPS","Istituto Nazionale Previdenza Sociale", "family") ); - Mockito.when(criteriaCodesConfiguration.getCriteriaCodeConfigs()).thenReturn(expected); + Mockito.when(criteriaCodesConfigurationMock.getCriteriaCodeConfigs()).thenReturn(expected); + //When - Map result = criteriaCodesConfiguration.getCriteriaCodeConfigs(); + CriteriaCodeConfig criteriaCodeConfig = criteriaCodesService.getCriteriaCodeConfig("BIRTHDATE"); //then - Assertions.assertNotNull(result); - Assertions.assertEquals(expected, result); - Assertions.assertEquals(4,result.size()); + Assertions.assertNotNull(criteriaCodeConfig); + Assertions.assertEquals(expected.get("BIRTHDATE"),criteriaCodeConfig); } } diff --git a/src/test/java/it/gov/pagopa/admissibility/service/commands/CommandMediatorServiceImplTest.java b/src/test/java/it/gov/pagopa/admissibility/service/commands/CommandMediatorServiceImplTest.java new file mode 100644 index 00000000..45475ad5 --- /dev/null +++ b/src/test/java/it/gov/pagopa/admissibility/service/commands/CommandMediatorServiceImplTest.java @@ -0,0 +1,149 @@ +package it.gov.pagopa.admissibility.service.commands; + +import ch.qos.logback.classic.LoggerContext; +import com.fasterxml.jackson.databind.ObjectReader; +import it.gov.pagopa.admissibility.dto.commands.QueueCommandOperationDTO; +import it.gov.pagopa.admissibility.service.AdmissibilityErrorNotifierService; +import it.gov.pagopa.admissibility.service.commands.operations.DeleteInitiativeService; +import it.gov.pagopa.admissibility.service.onboarding.OnboardingContextHolderService; +import it.gov.pagopa.admissibility.utils.CommandConstants; +import it.gov.pagopa.common.utils.MemoryAppender; +import it.gov.pagopa.common.utils.TestUtils; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.kie.api.KieBase; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.LoggerFactory; +import org.springframework.messaging.Message; +import org.springframework.messaging.support.MessageBuilder; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; + +@ExtendWith(MockitoExtension.class) +class CommandMediatorServiceImplTest { + + @Mock + private AdmissibilityErrorNotifierService admissibilityErrorNotifierServiceMock; + @Mock + private OnboardingContextHolderService onboardingContextHolderServiceMock; + @Mock + private DeleteInitiativeService deleteInitiativeServiceMock; + private CommandMediatorServiceImpl commandMediatorService; + private MemoryAppender memoryAppender; + + @BeforeEach + void setUp() { + commandMediatorService = + new CommandMediatorServiceImpl( + "Application Name", + 100L, + "PT1S", + deleteInitiativeServiceMock, + onboardingContextHolderServiceMock, + admissibilityErrorNotifierServiceMock, + TestUtils.objectMapper); + + ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("it.gov.pagopa.admissibility.service.commands.CommandMediatorServiceImpl"); + memoryAppender = new MemoryAppender(); + memoryAppender.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); + logger.setLevel(ch.qos.logback.classic.Level.INFO); + logger.addAppender(memoryAppender); + memoryAppender.start(); + } + + @Test + void getCommitDelay() { + //given + Duration expected = Duration.ofMillis(100L); + //when + Duration commitDelay = commandMediatorService.getCommitDelay(); + //then + Assertions.assertEquals(expected,commitDelay); + } + + @Test + void givenMessagesWhenAfterCommitsThenSuccessfully() { + //given + Flux> afterCommits2Subscribe = Flux.just(List.of("INITIATIVE1","INITIATIVE2","INITIATIVE3")); + Mockito.when(onboardingContextHolderServiceMock.refreshKieContainerCacheMiss()).thenReturn(Mono.just(Mockito.mock(KieBase.class))); + + // when + commandMediatorService.subscribeAfterCommits(afterCommits2Subscribe); + + //then + Mockito.verify(onboardingContextHolderServiceMock).refreshKieContainerCacheMiss(); + Assertions.assertEquals( + ("[ADMISSIBILITY_COMMANDS] Processed offsets committed successfully"), + memoryAppender.getLoggedEvents().get(0).getFormattedMessage() + ); + } + + @Test + void getObjectReader() { + ObjectReader objectReader = commandMediatorService.getObjectReader(); + Assertions.assertNotNull(objectReader); + } + + @Test + void givenDeleteInitiatveOperationTypeWhenCallExecuteThenReturnString() { + //given + QueueCommandOperationDTO payload = QueueCommandOperationDTO.builder() + .entityId("DUMMY_INITITATIVEID") + .operationTime(LocalDateTime.now()) + .operationType(CommandConstants.OPERATION_TYPE_DELETE_INITIATIVE) + .build(); + + Message message = MessageBuilder.withPayload("INITIATIVE").setHeader("HEADER","DUMMY_HEADER").build(); + Map ctx = new HashMap<>(); + + Mockito.when(deleteInitiativeServiceMock.execute(payload.getEntityId())).thenReturn(Mono.just(anyString())); + + //when + String result = commandMediatorService.execute(payload, message, ctx).block(); + + //then + Assertions.assertNotNull(result); + Mockito.verify(deleteInitiativeServiceMock).execute(anyString()); + } + + @Test + void givenOperationTypeDifferentWhenCallExecuteThenReturnMonoEmpty(){ + //given + QueueCommandOperationDTO payload = QueueCommandOperationDTO.builder() + .entityId("DUMMY_INITITATIVEID") + .operationTime(LocalDateTime.now()) + .operationType("OTHER_OPERATION_TYPE") + .build(); + + Message message = MessageBuilder.withPayload("INITIATIVE").setHeader("HEADER","DUMMY_HEADER").build(); + Map ctx = new HashMap<>(); + //when + Mono result= commandMediatorService.execute(payload, message, ctx); + + //then + assertEquals(result,Mono.empty()); + Mockito.verify(deleteInitiativeServiceMock,Mockito.never()).execute(anyString()); + } + @Test + void getFlowName() { + //given + String expected = "ADMISSIBILITY_COMMANDS"; + //when + String result = commandMediatorService.getFlowName(); + //then + Assertions.assertEquals(expected,result); + } +} \ No newline at end of file From 982e6ef084d5282fe3217e260c25920e8e0e9f49 Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Mon, 26 Feb 2024 18:00:51 +0100 Subject: [PATCH 04/16] IDP-2293 Added new error notifier service test --- ...ssibilityErrorNotifierServiceImplTest.java | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 src/test/java/it/gov/pagopa/admissibility/service/AdmissibilityErrorNotifierServiceImplTest.java diff --git a/src/test/java/it/gov/pagopa/admissibility/service/AdmissibilityErrorNotifierServiceImplTest.java b/src/test/java/it/gov/pagopa/admissibility/service/AdmissibilityErrorNotifierServiceImplTest.java new file mode 100644 index 00000000..c2fe876c --- /dev/null +++ b/src/test/java/it/gov/pagopa/admissibility/service/AdmissibilityErrorNotifierServiceImplTest.java @@ -0,0 +1,96 @@ +package it.gov.pagopa.admissibility.service; + +import it.gov.pagopa.common.kafka.service.ErrorNotifierService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.messaging.Message; +import org.springframework.messaging.support.MessageBuilder; + +import static org.mockito.ArgumentMatchers.*; + +@ExtendWith(MockitoExtension.class) +class AdmissibilityErrorNotifierServiceImplTest { + private static final String BINDER_KAFKA_TYPE="kafka"; + private static final String BINDER_BROKER="broker"; + private static final String DUMMY_MESSAGE="DUMMY MESSAGE"; + private static final Message dummyMessage = MessageBuilder.withPayload(DUMMY_MESSAGE).build(); + @Mock + private ErrorNotifierService errorNotifierServiceMock; + + private AdmissibilityErrorNotifierServiceImpl admissibilityErrorNotifierService; + + @BeforeEach + void setUp() { + admissibilityErrorNotifierService = new AdmissibilityErrorNotifierServiceImpl( + errorNotifierServiceMock, + BINDER_KAFKA_TYPE, + BINDER_BROKER, + + "beneficiary-rule-topic", + "beneficiary-rule-group", + BINDER_KAFKA_TYPE, + BINDER_BROKER, + + "admissibility-topic", + "admissibility-group", + + BINDER_KAFKA_TYPE, + BINDER_BROKER, + "admissibility-out-topic", + + BINDER_KAFKA_TYPE, + BINDER_BROKER, + "admissibility-ranking-request-topic", + + BINDER_KAFKA_TYPE, + BINDER_BROKER, + "commands-topic", + "commands-group" + ); + } + + @Test + void notifyBeneficiaryRuleBuilder() { + errorNotifyMock("beneficiary-rule-topic","beneficiary-rule-group",true,true); + admissibilityErrorNotifierService.notifyBeneficiaryRuleBuilder(dummyMessage,DUMMY_MESSAGE,true,new Throwable(DUMMY_MESSAGE)); + + Mockito.verifyNoMoreInteractions(errorNotifierServiceMock); + } + @Test + void notifyAdmissibilityOutcome() { + errorNotifyMock("admissibility-out-topic",null,true,false); + admissibilityErrorNotifierService.notifyAdmissibilityOutcome(dummyMessage,DUMMY_MESSAGE,true,new Throwable(DUMMY_MESSAGE)); + Mockito.verifyNoMoreInteractions(errorNotifierServiceMock); + } + + @Test + void notifyRankingRequest() { + errorNotifyMock("admissibility-ranking-request-topic",null,true,false); + admissibilityErrorNotifierService.notifyRankingRequest(dummyMessage,DUMMY_MESSAGE,true,new Throwable(DUMMY_MESSAGE)); + Mockito.verifyNoMoreInteractions(errorNotifierServiceMock); + } + + @Test + void notifyAdmissibilityCommands() { + errorNotifyMock("commands-topic","commands-group",true,true); + admissibilityErrorNotifierService.notifyAdmissibilityCommands(dummyMessage,DUMMY_MESSAGE,true,new Throwable(DUMMY_MESSAGE)); + Mockito.verifyNoMoreInteractions(errorNotifierServiceMock); + } + + @Test + void testNotify() { + errorNotifyMock("commands-topic","commands-group",true,true); + admissibilityErrorNotifierService.notify(BINDER_KAFKA_TYPE,BINDER_BROKER,"commands-topic","commands-group",dummyMessage,DUMMY_MESSAGE,true,true,new Throwable(DUMMY_MESSAGE)); + Mockito.verifyNoMoreInteractions(errorNotifierServiceMock); + } + + private void errorNotifyMock(String topic, String group, boolean retryable, boolean resendApplication ) { + Mockito.when(errorNotifierServiceMock.notify(eq(BINDER_KAFKA_TYPE), eq(BINDER_BROKER), + eq(topic), eq(group), eq(dummyMessage), eq(DUMMY_MESSAGE), eq(retryable), eq(resendApplication), any())) + .thenReturn(true); + } +} \ No newline at end of file From 67239b983c1de257c43ab5bf060942e02718a146 Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Tue, 27 Feb 2024 17:48:03 +0100 Subject: [PATCH 05/16] IDP-2293 deleted deprecated tests --- ...nsumerConfigIntegrationTestDeprecated.java | 218 ----- ...nsumerConfigIntegrationTestDeprecated.java | 206 ----- ...tyProcessorConfigFamilyTestDeprecated.java | 438 --------- ...yProcessorConfigRankingTestDeprecated.java | 229 ----- ...sibilityProcessorConfigTestDeprecated.java | 833 ------------------ .../BaseAdmissibilityProcessorConfigTest.java | 164 ---- .../mock/FamilyMockRestClientImplTest.java | 64 -- ...amilyMockRestClientImplTestDeprecated.java | 34 - ...sultationSoapClientImplTestIntegrated.java | 32 - ...aCodeServiceIntegrationTestDeprecated.java | 34 - ...olderServiceIntegrationTestDeprecated.java | 188 ---- 11 files changed, 2440 deletions(-) delete mode 100644 src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.java delete mode 100644 src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/CommandConsumerConfigIntegrationTestDeprecated.java delete mode 100644 src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigFamilyTestDeprecated.java delete mode 100644 src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigRankingTestDeprecated.java delete mode 100644 src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigTestDeprecated.java delete mode 100644 src/test/java/it/gov/pagopa/admissibility/connector/event/processor/BaseAdmissibilityProcessorConfigTest.java delete mode 100644 src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java delete mode 100644 src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestDeprecated.java delete mode 100644 src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplTestIntegrated.java delete mode 100644 src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodeServiceIntegrationTestDeprecated.java delete mode 100644 src/test/java/it/gov/pagopa/admissibility/service/onboarding/OnboardingContextHolderServiceIntegrationTestDeprecated.java diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.java b/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.java deleted file mode 100644 index 9ac6afe6..00000000 --- a/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.java +++ /dev/null @@ -1,218 +0,0 @@ -package it.gov.pagopa.admissibility.connector.event.consumer; - -import it.gov.pagopa.admissibility.BaseIntegrationTest; -import it.gov.pagopa.admissibility.connector.repository.DroolsRuleRepository; -import it.gov.pagopa.admissibility.dto.rule.AutomatedCriteriaDTO; -import it.gov.pagopa.admissibility.dto.rule.InitiativeBeneficiaryRuleDTO; -import it.gov.pagopa.admissibility.service.build.KieContainerBuilderService; -import it.gov.pagopa.admissibility.service.build.KieContainerBuilderServiceImpl; -import it.gov.pagopa.admissibility.service.onboarding.OnboardingContextHolderService; -import it.gov.pagopa.admissibility.test.fakers.Initiative2BuildDTOFaker; -import it.gov.pagopa.common.kafka.utils.KafkaConstants; -import it.gov.pagopa.common.utils.TestUtils; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.OffsetAndMetadata; -import org.apache.kafka.common.TopicPartition; -import org.apache.kafka.common.header.internals.RecordHeader; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.kie.api.KieBase; -import org.kie.api.definition.KiePackage; -import org.mockito.Mockito; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.data.util.Pair; -import org.springframework.test.context.TestPropertySource; -import reactor.core.publisher.Mono; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Supplier; -import java.util.stream.IntStream; - -@TestPropertySource(properties = { - "app.beneficiary-rule.build-delay-duration=PT1S", - "logging.level.it.gov.pagopa.admissibility.service.build.BeneficiaryRule2DroolsRuleImpl=WARN", - "logging.level.it.gov.pagopa.admissibility.service.build.KieContainerBuilderServiceImpl=WARN", - "logging.level.it.gov.pagopa.common.reactive.kafka.consumer.BaseKafkaConsumer=WARN", - "logging.level.it.gov.pagopa.common.reactive.utils.PerformanceLogger=WARN", -}) -@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) -public class BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated extends BaseIntegrationTest { - - @SpyBean - private KieContainerBuilderService kieContainerBuilderServiceSpy; - @SpyBean - private OnboardingContextHolderService onboardingContextHolderServiceSpy; - @SpyBean - private DroolsRuleRepository droolsRuleRepositorySpy; - - @Test - void testBeneficiaryRuleBuilding() { - int validRules = 6; // use even number - int notValidRules = errorUseCases.size(); - long maxWaitingMs = 30000; - - int[] expectedRules = {0}; - - List initiativePayloads = new ArrayList<>(buildValidPayloads(errorUseCases.size(), validRules / 2, expectedRules)); - initiativePayloads.addAll(IntStream.range(0, notValidRules).mapToObj(i -> errorUseCases.get(i).getFirst().get()).toList()); - initiativePayloads.addAll(buildValidPayloads(errorUseCases.size() + (validRules / 2) + notValidRules, validRules / 2, expectedRules)); - - long timeStart = System.currentTimeMillis(); - initiativePayloads.forEach(i -> kafkaTestUtilitiesService.publishIntoEmbeddedKafka(topicBeneficiaryRuleConsumer, null, null, i)); - kafkaTestUtilitiesService.publishIntoEmbeddedKafka(topicBeneficiaryRuleConsumer, List.of(new RecordHeader(KafkaConstants.ERROR_MSG_HEADER_APPLICATION_NAME, "OTHERAPPNAME".getBytes(StandardCharsets.UTF_8))), null, "OTHERAPPMESSAGE"); - long timePublishingEnd = System.currentTimeMillis(); - - long[] countSaved = {0}; - //noinspection ConstantConditions - TestUtils.waitFor(() -> (countSaved[0] = droolsRuleRepository.count().block()) >= validRules, () -> "Expected %d saved rules, read %d".formatted(validRules, countSaved[0]), 15, 1000); - long timeDroolsSavingCheckPublishingEnd = System.currentTimeMillis(); - - int ruleBuiltSize = waitForKieContainerBuild(expectedRules[0]); - long timeEnd = System.currentTimeMillis(); - - Assertions.assertEquals(validRules, countSaved[0]); - Assertions.assertEquals(validRules, onboardingContextHolderServiceSpy.getBeneficiaryRulesKieInitiativeIds().size()); - Assertions.assertEquals(expectedRules[0], ruleBuiltSize); - - checkInitiativeCounters(validRules); - - checkErrorsPublished(notValidRules, maxWaitingMs, errorUseCases); - - Mockito.verify(kieContainerBuilderServiceSpy, Mockito.atLeast(1)).buildAll(); // +1 due to refresh at startup - Mockito.verify(onboardingContextHolderServiceSpy, Mockito.atLeast(1)).setBeneficiaryRulesKieBase(Mockito.any()); - - System.out.printf(""" - ************************ - Time spent to send %d (%d + %d) messages (from start): %d millis - Time spent to assert drools rule count (from previous check): %d millis - Time spent to assert kie container rules' size (from previous check): %d millis - ************************ - Test Completed in %d millis - ************************ - The kieContainer has been built %d times - ************************ - """, - validRules + notValidRules, - validRules, - notValidRules, - timePublishingEnd - timeStart, - timeDroolsSavingCheckPublishingEnd - timePublishingEnd, - timeEnd - timeDroolsSavingCheckPublishingEnd, - timeEnd - timeStart, - Mockito.mockingDetails(kieContainerBuilderServiceSpy).getInvocations().stream() - .filter(i -> i.getMethod().getName().equals("buildAll")).count() - 1 // 1 is due on startup - ); - - long timeCommitCheckStart = System.currentTimeMillis(); - final Map srcCommitOffsets = kafkaTestUtilitiesService.checkCommittedOffsets(topicBeneficiaryRuleConsumer, groupIdBeneficiaryRuleConsumer, initiativePayloads.size() + 1); // +1 due to other applicationName useCase - long timeCommitCheckEnd = System.currentTimeMillis(); - System.out.printf(""" - ************************ - Time occurred to check committed offset: %d millis - ************************ - Source Topic Committed Offsets: %s - ************************ - """, - timeCommitCheckEnd - timeCommitCheckStart, - srcCommitOffsets - ); - } - - private List buildValidPayloads(int bias, int validRules, int[] expectedRules) { - return IntStream.range(bias, bias + validRules) - .mapToObj(Initiative2BuildDTOFaker::mockInstance) - .peek(i -> expectedRules[0] += i.getBeneficiaryRule().getAutomatedCriteria().size()) - .map(TestUtils::jsonSerializer) - .toList(); - } - - private int waitForKieContainerBuild(int expectedRules) { - return waitForKieContainerBuild(expectedRules, onboardingContextHolderServiceSpy); - } - - public static int waitForKieContainerBuild(int expectedRules, OnboardingContextHolderService onboardingContextHolderServiceSpy) { - int[] ruleBuiltSize = {0}; - TestUtils.waitFor(() -> (ruleBuiltSize[0] = getRuleBuiltSize(onboardingContextHolderServiceSpy)) >= expectedRules, () -> "Expected %d rules, read %d".formatted(expectedRules, ruleBuiltSize[0]), 20, 1000); - return ruleBuiltSize[0]; - } - - public static int getRuleBuiltSize(OnboardingContextHolderService onboardingContextHolderServiceSpy) { - KieBase kieBase = onboardingContextHolderServiceSpy.getBeneficiaryRulesKieBase(); - if (kieBase == null) { - return 0; - } else { - KiePackage kiePackage = kieBase.getKiePackage(KieContainerBuilderServiceImpl.RULES_BUILT_PACKAGE); - return kiePackage != null - ? kiePackage.getRules().size() - : 0; - } - } - - private void checkInitiativeCounters(int expectedInitiativeNumber) { - Assertions.assertEquals(expectedInitiativeNumber, initiativeCountersRepository.count().block()); - Assertions.assertEquals( - Collections.emptyList(), - initiativeCountersRepository.findAll() - .filter(i -> - i.getOnboarded() == 1L - && i.getReservedInitiativeBudgetCents() > 0L - && i.getResidualInitiativeBudgetCents() < i.getInitiativeBudgetCents() - && i.getResidualInitiativeBudgetCents() > 0L) - .collectList() - .block() - ); - } - - //region not valid useCases - // all use cases configured must have a unique id recognized by the regexp errorUseCaseIdPatternMatch - private final List, Consumer>>> errorUseCases = new ArrayList<>(); - - { - String useCaseJsonNotExpected = "{\"initiativeId\":\"INITIATIVEID_0\",unexpectedStructure:0}"; - errorUseCases.add(Pair.of( - () -> useCaseJsonNotExpected, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_RULE_BUILD] Unexpected JSON", useCaseJsonNotExpected) - )); - - String jsonNotValid = "{\"initiativeId\":\"INITIATIVEID_1\",invalidJson"; - errorUseCases.add(Pair.of( - () -> jsonNotValid, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_RULE_BUILD] Unexpected JSON", jsonNotValid) - )); - - String criteriaCodeNotValid = TestUtils.jsonSerializer(Initiative2BuildDTOFaker.mockInstanceBuilder(errorUseCases.size()) - .beneficiaryRule(InitiativeBeneficiaryRuleDTO.builder() - .automatedCriteria(List.of( - AutomatedCriteriaDTO.builder() - .code("DUMMY") - .build() - )) - .build())); - errorUseCases.add(Pair.of( - () -> criteriaCodeNotValid, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_RULE_BUILD] An error occurred handling initiative", criteriaCodeNotValid) - )); - - final String errorWhenSavingUseCaseId = "INITIATIVEID_%s_ERRORWHENSAVING".formatted(errorUseCases.size()); - String droolRuleSaveInError = TestUtils.jsonSerializer(Initiative2BuildDTOFaker.mockInstanceBuilder(errorUseCases.size()) - .initiativeId(errorWhenSavingUseCaseId) - .build()); - errorUseCases.add(Pair.of( - () -> { - Mockito.doReturn(Mono.error(new RuntimeException("DUMMYEXCEPTION"))).when(droolsRuleRepositorySpy).save(Mockito.argThat(i -> errorWhenSavingUseCaseId.equals(i.getId()))); - return droolRuleSaveInError; - }, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_RULE_BUILD] An error occurred handling initiative", droolRuleSaveInError) - )); - } - - private void checkErrorMessageHeaders(ConsumerRecord errorMessage, String errorDescription, String expectedPayload) { - checkErrorMessageHeaders(kafkaBootstrapServers, topicBeneficiaryRuleConsumer, groupIdBeneficiaryRuleConsumer, errorMessage, errorDescription, expectedPayload, null, true, true); - } - //endregion -} diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/CommandConsumerConfigIntegrationTestDeprecated.java b/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/CommandConsumerConfigIntegrationTestDeprecated.java deleted file mode 100644 index 202bd5e0..00000000 --- a/src/test/java/it/gov/pagopa/admissibility/connector/event/consumer/CommandConsumerConfigIntegrationTestDeprecated.java +++ /dev/null @@ -1,206 +0,0 @@ -package it.gov.pagopa.admissibility.connector.event.consumer; - -import com.mongodb.MongoException; -import it.gov.pagopa.admissibility.BaseIntegrationTest; -import it.gov.pagopa.admissibility.connector.repository.DroolsRuleRepository; -import it.gov.pagopa.admissibility.connector.repository.InitiativeCountersRepository; -import it.gov.pagopa.admissibility.connector.repository.OnboardingFamiliesRepository; -import it.gov.pagopa.admissibility.dto.commands.QueueCommandOperationDTO; -import it.gov.pagopa.admissibility.dto.onboarding.extra.Family; -import it.gov.pagopa.admissibility.model.DroolsRule; -import it.gov.pagopa.admissibility.model.InitiativeConfig; -import it.gov.pagopa.admissibility.model.InitiativeCounters; -import it.gov.pagopa.admissibility.model.OnboardingFamilies; -import it.gov.pagopa.admissibility.utils.CommandConstants; -import it.gov.pagopa.common.utils.TestUtils; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.OffsetAndMetadata; -import org.apache.kafka.common.TopicPartition; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.data.util.Pair; -import org.springframework.test.context.TestPropertySource; - -import java.time.LocalDateTime; -import java.util.*; -import java.util.function.Consumer; -import java.util.function.Supplier; -import java.util.regex.Pattern; -import java.util.stream.IntStream; - -@TestPropertySource(properties = { - "app.beneficiary-rule.build-delay-duration=PT1S", - "logging.level.it.gov.pagopa.admissibility.service.commands.CommandMediatorServiceImpl=WARN", - "logging.level.it.gov.pagopa.admissibility.service.commands.operations.DeleteInitiativeServiceImpl=WARN", - "logging.level.it.gov.pagopa.admissibility.service.onboarding.OnboardingContextHolderServiceImpl=WARN", - "logging.level.it.gov.pagopa.common.reactive.utils.PerformanceLogger=WARN" -}) -@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) -class CommandConsumerConfigIntegrationTestDeprecated extends BaseIntegrationTest { - private final String INITIATIVEID = "INITIATIVEID_%d"; - private final Set INITIATIVES_DELETED = new HashSet<>(); - @SpyBean - private DroolsRuleRepository droolsRuleRepositorySpy; - - @Autowired - private InitiativeCountersRepository initiativeCountersRepository; - @Autowired - private OnboardingFamiliesRepository onboardingFamiliesRepository; - - @Test - void test() { - int validMessages = 10; - int notValidMessages = errorUseCases.size(); - long maxWaitingMs = 30000; - - List commandsPayloads = new ArrayList<>(notValidMessages+validMessages); - commandsPayloads.addAll(IntStream.range(0,notValidMessages).mapToObj(i -> errorUseCases.get(i).getFirst().get()).toList()); - commandsPayloads.addAll(buildValidPayloads(notValidMessages, notValidMessages+validMessages)); - - long timeStart=System.currentTimeMillis(); - commandsPayloads.forEach(cp -> kafkaTestUtilitiesService.publishIntoEmbeddedKafka(topicCommands, null, null, cp)); - long timePublishingEnd = System.currentTimeMillis(); - - waitForLastStorageChange(validMessages/2); - - long timeEnd=System.currentTimeMillis(); - - checkRepositories(); - checkErrorsPublished(notValidMessages, maxWaitingMs, errorUseCases); - - System.out.printf(""" - ************************ - Time spent to send %d (%d + %d) messages (from start): %d millis - Time spent to assert db stored count (from previous check): %d millis - ************************ - Test Completed in %d millis - ************************ - """, - commandsPayloads.size(), - validMessages, - notValidMessages, - timePublishingEnd - timeStart, - timeEnd - timePublishingEnd, - timeEnd - timeStart - ); - - long timeCommitCheckStart = System.currentTimeMillis(); - Map srcCommitOffsets = kafkaTestUtilitiesService.checkCommittedOffsets(topicCommands, groupIdCommands, commandsPayloads.size()); - long timeCommitCheckEnd = System.currentTimeMillis(); - - System.out.printf(""" - ************************ - Time occurred to check committed offset: %d millis - ************************ - Source Topic Committed Offsets: %s - ************************ - """, - timeCommitCheckEnd - timeCommitCheckStart, - srcCommitOffsets - ); - - } - - - private long waitForLastStorageChange(int n) { - long[] countSaved={0}; - //noinspection ConstantConditions - TestUtils.waitFor(()->(countSaved[0]=initiativeCountersRepository.findAll().count().block()) == n, ()->"Expected %d saved users in db, read %d".formatted(n, countSaved[0]), 60, 1000); - return countSaved[0]; - } - - private List buildValidPayloads(int startValue, int endValue) { - return IntStream.range(startValue, endValue) - .mapToObj(i -> { - initializeDB(i); - QueueCommandOperationDTO command = QueueCommandOperationDTO.builder() - .entityId(INITIATIVEID.formatted(i)) - .operationTime(LocalDateTime.now()) - .build(); - - if(i%2 == 0){ - INITIATIVES_DELETED.add(command.getEntityId()); - command.setOperationType(CommandConstants.OPERATION_TYPE_DELETE_INITIATIVE); - } else { - command.setOperationType("ANOTHER_TYPE"); - } - return command; - }) - .map(TestUtils::jsonSerializer) - .toList(); - } - - private void initializeDB(int bias) { - InitiativeConfig initiativeConfig = InitiativeConfig.builder() - .initiativeId(INITIATIVEID.formatted(bias)) - .build(); - - DroolsRule droolsRule = DroolsRule.builder() - .id(INITIATIVEID.formatted(bias)) - .initiativeConfig(initiativeConfig) - .rule("") - .build(); - droolsRuleRepositorySpy.save(droolsRule).block(); - - InitiativeCounters initiativeCounters = InitiativeCounters.builder() - .id(INITIATIVEID.formatted(bias)) - .build(); - initiativeCountersRepository.save(initiativeCounters).block(); - - String FAMILY_ID = "FAMILYID%d"; - Family family = Family.builder() - .familyId(FAMILY_ID.formatted(bias)) - .build(); - OnboardingFamilies onboardingFamilies = OnboardingFamilies.builder(family, INITIATIVEID).build(); - onboardingFamiliesRepository.save(onboardingFamilies).block(); - } - @Override - protected Pattern getErrorUseCaseIdPatternMatch() { - return Pattern.compile("\"entityId\":\"ENTITYID_ERROR([0-9]+)\""); - } - - private final List, Consumer>>> errorUseCases = new ArrayList<>(); - - { - String useCaseJsonNotExpected = "{\"entityId\":\"ENTITYID_ERROR0\",unexpectedStructure:0}"; - errorUseCases.add(Pair.of( - () -> useCaseJsonNotExpected, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_COMMANDS] Unexpected JSON", useCaseJsonNotExpected) - )); - - String jsonNotValid = "{\"entityId\":\"ENTITYID_ERROR1\",invalidJson"; - errorUseCases.add(Pair.of( - () -> jsonNotValid, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_COMMANDS] Unexpected JSON", jsonNotValid) - )); - - final String errorInitiativeId = "ENTITYID_ERROR2"; - QueueCommandOperationDTO commandOperationError = QueueCommandOperationDTO.builder() - .entityId(errorInitiativeId) - .operationType(CommandConstants.OPERATION_TYPE_DELETE_INITIATIVE) - .operationTime(LocalDateTime.now()) - .build(); - String commandOperationErrorString = TestUtils.jsonSerializer(commandOperationError); - errorUseCases.add(Pair.of( - () -> { - Mockito.doThrow(new MongoException("Command error dummy")) - .when(droolsRuleRepositorySpy).removeById(errorInitiativeId); - return commandOperationErrorString; - }, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_COMMANDS] An error occurred evaluating commands", commandOperationErrorString) - )); - } - - private void checkRepositories() { - Assertions.assertTrue(droolsRuleRepositorySpy.findAll().toStream().noneMatch(ri -> INITIATIVES_DELETED.contains(ri.getId()))); - Assertions.assertTrue(initiativeCountersRepository.findAll().toStream().noneMatch(ri -> INITIATIVES_DELETED.contains(ri.getId()))); - Assertions.assertTrue(onboardingFamiliesRepository.findAll().toStream().noneMatch(ri -> INITIATIVES_DELETED.contains(ri.getInitiativeId()))); - } - - private void checkErrorMessageHeaders(ConsumerRecord errorMessage, String errorDescription, String expectedPayload) { - checkErrorMessageHeaders(topicCommands, groupIdCommands, errorMessage, errorDescription, expectedPayload, null); - } -} \ No newline at end of file diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigFamilyTestDeprecated.java b/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigFamilyTestDeprecated.java deleted file mode 100644 index befba8a1..00000000 --- a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigFamilyTestDeprecated.java +++ /dev/null @@ -1,438 +0,0 @@ -package it.gov.pagopa.admissibility.connector.event.processor; - -import com.fasterxml.jackson.core.JsonProcessingException; -import it.gov.pagopa.admissibility.connector.event.consumer.BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated; -import it.gov.pagopa.admissibility.connector.repository.InitiativeCountersRepository; -import it.gov.pagopa.admissibility.connector.repository.OnboardingFamiliesRepository; -import it.gov.pagopa.admissibility.dto.onboarding.*; -import it.gov.pagopa.admissibility.dto.onboarding.extra.BirthDate; -import it.gov.pagopa.admissibility.dto.rule.Initiative2BuildDTO; -import it.gov.pagopa.admissibility.dto.rule.InitiativeGeneralDTO; -import it.gov.pagopa.admissibility.enums.OnboardingEvaluationStatus; -import it.gov.pagopa.admissibility.enums.OnboardingFamilyEvaluationStatus; -import it.gov.pagopa.admissibility.model.InitiativeCounters; -import it.gov.pagopa.admissibility.model.OnboardingFamilies; -import it.gov.pagopa.admissibility.service.onboarding.notifier.OnboardingRescheduleService; -import it.gov.pagopa.admissibility.service.onboarding.pdnd.FamilyDataRetrieverService; -import it.gov.pagopa.admissibility.test.fakers.CriteriaCodeConfigFaker; -import it.gov.pagopa.admissibility.test.fakers.Initiative2BuildDTOFaker; -import it.gov.pagopa.admissibility.test.fakers.OnboardingDTOFaker; -import it.gov.pagopa.admissibility.utils.OnboardingConstants; -import it.gov.pagopa.common.mongo.MongoTestUtilitiesService; -import it.gov.pagopa.common.utils.CommonUtilities; -import it.gov.pagopa.common.utils.TestUtils; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.data.domain.Sort; -import org.springframework.messaging.Message; -import org.springframework.messaging.support.MessageBuilder; -import org.springframework.test.context.ContextConfiguration; -import reactor.core.publisher.Mono; - -import java.io.IOException; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -@ContextConfiguration -@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) -class AdmissibilityProcessorConfigFamilyTestDeprecated extends BaseAdmissibilityProcessorConfigTest { - - @TestConfiguration - static class MediatorSpyConfiguration extends BaseAdmissibilityProcessorConfigTest.MediatorSpyConfiguration {} - - private List publishedInitiatives; - private final int onboardingFamilies; - private final int membersPerFamily=3; - - private int expectedOnboardingKoFamilies=0; - private int expectedFamilyRetrieveKo=0; - - private int expectedOnboardedFamilies; - - @SpyBean - private OnboardingRescheduleService rescheduleServiceSpy; - @SpyBean - private FamilyDataRetrieverService familyDataRetrieverServiceSpy; - - @Autowired - private OnboardingFamiliesRepository onboardingFamiliesRepository; - @Autowired - private InitiativeCountersRepository initiativeCountersRepository; - - @Test - void testFamilyAdmissibilityOnboarding() throws IOException { - long maxWaitingMs = 30000; - publishOnboardingRules(); - - List> onboardings = new ArrayList<>(buildValidPayloads(0, onboardingFamilies, useCases)); - - storeInitiativeCountersInitialState(); - - int expectedRequestsPerInitiative = onboardingFamilies * membersPerFamily; - int expectedPublishedMessages = expectedRequestsPerInitiative * publishedInitiatives.size(); - int expectedEvaluationCompletedMessages = - expectedRequestsPerInitiative - + (expectedOnboardingKoFamilies * membersPerFamily) + (expectedOnboardingKoFamilies*2) // rankingKO are published also here + rejected for ko family - + (onboardingFamilies - expectedOnboardingKoFamilies - expectedFamilyRetrieveKo) * (membersPerFamily - 1) // DEMANDED for each other member when ONBOARDING_OK - + (expectedFamilyRetrieveKo * membersPerFamily * (publishedInitiatives.size() - 1)); // Family not retriever - - - expectedOnboardedFamilies = onboardingFamilies - expectedFamilyRetrieveKo; - - int expectedRankingQueue = expectedOnboardedFamilies + (expectedFamilyRetrieveKo * membersPerFamily) ; - - MongoTestUtilitiesService.startMongoCommandListener("ON-BOARDINGS"); - - long timePublishOnboardingStart = System.currentTimeMillis(); - onboardings.forEach(i -> kafkaTestUtilitiesService.publishIntoEmbeddedKafka(topicAdmissibilityProcessorRequest, null, i)); - long timePublishingOnboardingRequest = System.currentTimeMillis() - timePublishOnboardingStart; - - long timeConsumerResponse = System.currentTimeMillis(); - List> rankingRequestPayloadConsumed = kafkaTestUtilitiesService.consumeMessages(topicAdmissibilityProcessorOutRankingRequest, expectedRankingQueue, maxWaitingMs); - List> evaluationOutcomePayloadConsumed = kafkaTestUtilitiesService.consumeMessages(topicAdmissibilityProcessorOutcome, expectedEvaluationCompletedMessages, maxWaitingMs); - long timeEnd = System.currentTimeMillis(); - - long timeConsumerResponseEnd = timeEnd - timeConsumerResponse; - - MongoTestUtilitiesService.stopAndPrintMongoCommands(); - - checkResponses(expectedRankingQueue, rankingRequestPayloadConsumed, RankingRequestDTO.class); - checkResponses(expectedEvaluationCompletedMessages, evaluationOutcomePayloadConsumed, EvaluationCompletedDTO.class); - - checkStoredOnboardingFamilies(); - checkInitiativeCounters(); - - long rescheduled = Mockito.mockingDetails(rescheduleServiceSpy).getInvocations().stream() - .peek(i -> { - OnboardingDTO rescheduledRequest = i.getArgument(0, OnboardingDTO.class); - Assertions.assertNotNull(rescheduledRequest.getFamily()); - }).count(); - - System.out.printf(""" - ************************ - Time spent to send %d (%d members per %d families per %d initiatives) onboarding request messages: %d millis - Rescheduled %d messages because IN_PROGRESS - Time spent to consume onboarding responses: %d millis - ************************ - Test Completed in %d millis - ************************ - """, - expectedPublishedMessages, - membersPerFamily, - publishedInitiatives.size(), - onboardingFamilies, - timePublishingOnboardingRequest, - rescheduled, - timeConsumerResponseEnd, - timeEnd - timePublishOnboardingStart - ); - - checkOffsets(onboardings.size() + rescheduled, expectedRankingQueue, topicAdmissibilityProcessorOutRankingRequest); - checkOffsets(onboardings.size() + rescheduled, expectedEvaluationCompletedMessages, topicAdmissibilityProcessorOutcome); - } - - private void publishOnboardingRules() { - MongoTestUtilitiesService.startMongoCommandListener("RULE PUBLISHING"); - - int[] expectedRules = {0}; - publishedInitiatives = IntStream.range(0, 2) - .mapToObj(i -> { - final Initiative2BuildDTO initiative = Initiative2BuildDTOFaker.mockInstanceBuilder(i) - .build(); - - initiative.getGeneral().setRankingEnabled(i % 2 == 0); - - initiative.setInitiativeId(initiative.getGeneral().isRankingEnabled()? "RANKINGINITIATIVEID":"INITIATIVEID"); - - initiative.getGeneral().setBeneficiaryType(InitiativeGeneralDTO.BeneficiaryTypeEnum.NF); - initiative.getBeneficiaryRule().getAutomatedCriteria().get(0).setOrderDirection(Sort.Direction.ASC); - initiative.getBeneficiaryRule().setAutomatedCriteria(List.of(initiative.getBeneficiaryRule().getAutomatedCriteria().get(0))); - - BigDecimal budget = initiative.getGeneral().getBeneficiaryBudget().multiply(BigDecimal.valueOf(onboardingFamilies)); - - initiative.getGeneral().setBudget(budget); - - return initiative; - }) - .peek(i -> expectedRules[0] += i.getBeneficiaryRule().getAutomatedCriteria().size()) - .peek(i -> kafkaTestUtilitiesService.publishIntoEmbeddedKafka(topicBeneficiaryRuleConsumer, null, null, i)) - .toList(); - - BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.waitForKieContainerBuild(expectedRules[0], onboardingContextHolderServiceSpy); - - MongoTestUtilitiesService.stopAndPrintMongoCommands(); - } - - @Override - protected List> buildValidPayloads(int bias, int validOnboardings, List> useCases) { - return super.buildValidPayloads(bias, validOnboardings, useCases).stream() - .flatMap(message -> publishedInitiatives.stream() - .flatMap(initiative -> - IntStream.range(0, membersPerFamily) - .mapToObj(i -> - MessageBuilder.withPayload(message.getPayload() - .replace("INITIATIVEID_0", initiative.getInitiativeId()) - .replaceAll("(userId_[^\"]+)", "$1_FAMILYMEMBER" + i) - ) - .copyHeaders(message.getHeaders()) - .build() - )) - ).toList(); - } - - private void storeInitiativeCountersInitialState() { - Assertions.assertTrue(expectedOnboardingKoFamilies + expectedFamilyRetrieveKo>0, "Call this method after payload build in order to set the residual equals to onboardingOk expected"); - - InitiativeCounters counter = new InitiativeCounters(); - counter.setId("INITIATIVEID"); - counter.setInitiativeBudgetCents(CommonUtilities.euroToCents(publishedInitiatives.get(0).getGeneral().getBudget())); - counter.setOnboarded((long)expectedOnboardingKoFamilies + (long) expectedFamilyRetrieveKo); - counter.setReservedInitiativeBudgetCents(CommonUtilities.euroToCents(publishedInitiatives.get(0).getGeneral().getBeneficiaryBudget()) * (expectedOnboardingKoFamilies + expectedFamilyRetrieveKo)); - counter.setResidualInitiativeBudgetCents(counter.getInitiativeBudgetCents() - counter.getReservedInitiativeBudgetCents()); - initiativeCountersRepository.save(counter).block(); - } - - - private void checkResponses(int expectedRequestsPerInitiative, List> payloadConsumed,Class clazz) throws JsonProcessingException { - assertInitiativePublishedMessagesCount(expectedRequestsPerInitiative, payloadConsumed, clazz); - - List evaluations = new ArrayList<>(payloadConsumed.size()); - - for (ConsumerRecord p : payloadConsumed) { - T payload = objectMapper.readValue(p.value(), clazz); - evaluations.add(payload); - - String userId = payload.getUserId(); - - payload.setUserId(userId.replaceAll("_FAMILYMEMBER\\d+","")); - checkResponse(payload, useCases); - payload.setUserId(userId); - if(payload.getUserId().startsWith("NOFAMILY")){ - Assertions.assertNull(payload.getFamilyId(), "Evaluation has familyId evenif not expected: " + payload); - } else { - Assertions.assertNotNull(payload.getFamilyId(), "Evaluation has null familyId: " + payload); - } - } - - Set familyIds = evaluations.stream().map(EvaluationDTO::getFamilyId).filter(Objects::nonNull).collect(Collectors.toSet()); - Assertions.assertEquals(expectedOnboardedFamilies, familyIds.size(), () -> "Unexpected families count: " + familyIds.stream().sorted().toList()); - - - Map> families = evaluations.stream() - .filter(ev->ev.getFamilyId()!=null) - .collect(Collectors.groupingBy(ev->ev.getFamilyId() + "_" + ev.getInitiativeId())); // not simply grouping by familyId because ranking KO publish also in outcome - - if (clazz.equals(EvaluationCompletedDTO.class)) { - families.values() - .forEach(members -> { - Map membersByStatusCount = members.stream().map(o -> (EvaluationCompletedDTO) o) - .collect(Collectors.groupingBy(EvaluationCompletedDTO::getStatus, Collectors.counting())); - - Map expected; - - if (membersByStatusCount.containsKey(OnboardingEvaluationStatus.ONBOARDING_OK)) { - expected = Map.of( - OnboardingEvaluationStatus.ONBOARDING_OK, 1L, - OnboardingEvaluationStatus.JOINED, (long) (membersPerFamily - 1), - OnboardingEvaluationStatus.DEMANDED, (long) (membersPerFamily - 1) - ); - } else if (membersByStatusCount.containsKey(OnboardingEvaluationStatus.REJECTED) - && members.stream().allMatch(o -> "INITIATIVEID".equals(o.getInitiativeId()))) { - expected = Map.of( - OnboardingEvaluationStatus.ONBOARDING_KO, 3L, - OnboardingEvaluationStatus.REJECTED, (long) (membersPerFamily - 1) - ); - } else { - expected = Map.of( - OnboardingEvaluationStatus.ONBOARDING_KO, 3L - ); - } - - Assertions.assertEquals(expected, membersByStatusCount); - }); - } - } - - private void assertInitiativePublishedMessagesCount(int expectedMessages, List> publishedRecords, Class clazz) { - Assertions.assertEquals(expectedMessages, publishedRecords.size(), ()-> { - Set> userId2MessagesCount = publishedRecords.stream() - .map(r -> { - try { - return objectMapper.readValue(r.value(), clazz); - } catch (JsonProcessingException e) { - throw new IllegalStateException(e); - } - }) - .filter(r -> !(r instanceof EvaluationCompletedDTO completedDTO) || !OnboardingEvaluationStatus.DEMANDED.equals(completedDTO.getStatus())) - .collect(Collectors.groupingBy(ev -> ev.getUserId() + "_" + ev.getInitiativeId(), Collectors.counting())) - .entrySet(); - - return "Unexpected published message count, %s: duplicates: %s".formatted( - expectedMessages == userId2MessagesCount.size() - ? "there are some duplicates" - : "distinct messages: " + userId2MessagesCount.size(), - userId2MessagesCount.stream() - .filter(e -> e.getValue() > 1) - .map(Map.Entry::getKey) - .toList()); - } - ); - } - - private void checkStoredOnboardingFamilies() { - Map> initiative2onboardingFamilies = onboardingFamiliesRepository.findAll().collect(Collectors.groupingBy(OnboardingFamilies::getInitiativeId)).block(); - Assertions.assertNotNull(initiative2onboardingFamilies); - - publishedInitiatives.forEach(i-> { - List onboardingFamilies = initiative2onboardingFamilies.get(i.getInitiativeId()); - Assertions.assertNotNull(onboardingFamilies); - - Assertions.assertEquals( - expectedOnboardedFamilies, - onboardingFamilies.size(), - "Initiative %s has an unexpected onboarding families count".formatted(i.getInitiativeId()) - ); - - Assertions.assertEquals(expectedOnboardingKoFamilies, - onboardingFamilies.stream().filter(f->OnboardingFamilyEvaluationStatus.ONBOARDING_KO.equals(f.getStatus())).count()); - - Assertions.assertTrue(onboardingFamilies.stream().allMatch(f-> - OnboardingFamilyEvaluationStatus.ONBOARDING_OK.equals(f.getStatus()) || - OnboardingFamilyEvaluationStatus.ONBOARDING_KO.equals(f.getStatus())) - ); - }); - } - - private void checkInitiativeCounters() { - { // Using anonymous block in order to be sure to not re-use variables - InitiativeCounters counter = initiativeCountersRepository.findById("INITIATIVEID").block(); - Assertions.assertNotNull(counter); - - // this counter is initialized in order to compensate KO, thus at the end the budget should be exhausted - Assertions.assertEquals(onboardingFamilies, counter.getOnboarded()); - Assertions.assertEquals(0L, counter.getResidualInitiativeBudgetCents()); - } - - { // Using anonymous block in order to be sure to not re-use variables - InitiativeCounters rankingCounter = initiativeCountersRepository.findById("RANKINGINITIATIVEID").block(); - Assertions.assertNotNull(rankingCounter); - - Assertions.assertEquals(0L, rankingCounter.getOnboarded()); - Assertions.assertEquals( - CommonUtilities.euroToCents(publishedInitiatives.get(0).getGeneral().getBudget()) - , rankingCounter.getResidualInitiativeBudgetCents()); - } - } - - //region useCases - - private OnboardingDTO.OnboardingDTOBuilder buildOnboardingRequestBuilder(Integer bias) { - return OnboardingDTOFaker.mockInstanceBuilder(bias, "INITIATIVEID_0") - .isee(BigDecimal.valueOf(20)) - .birthDate(new BirthDate("1990", LocalDate.now().getYear() - 1990)); - } - - // each useCase's userId should contain "userId_[0-9]+", this string is matched in order to set particular member id - Set expectedOnboardingOkStatuses = Set.of(OnboardingEvaluationStatus.ONBOARDING_OK, OnboardingEvaluationStatus.JOINED, OnboardingEvaluationStatus.DEMANDED); - Set expectedOnboardingKoStatuses = Set.of(OnboardingEvaluationStatus.ONBOARDING_KO, OnboardingEvaluationStatus.REJECTED); - private final List> useCases = List.of( - // useCase 0: onboardingOk - OnboardingUseCase.withJustPayload( - bias -> buildOnboardingRequestBuilder(bias).build(), - evaluation -> { - if(evaluation instanceof RankingRequestDTO rankingRequest){ - Assertions.assertFalse(rankingRequest.isOnboardingKo()); - } else if(evaluation instanceof EvaluationCompletedDTO evaluationCompleted) { - Assertions.assertEquals(Collections.emptyList(), evaluationCompleted.getOnboardingRejectionReasons()); - Assertions.assertTrue(expectedOnboardingOkStatuses.contains(evaluationCompleted.getStatus()), "Unexpected status: " + evaluationCompleted.getStatus()); - } - } - ), - - // useCase 1: onboardingKo case - OnboardingUseCase.withJustPayload( - bias -> { - expectedOnboardingKoFamilies++; - return buildOnboardingRequestBuilder(bias) - .isee(BigDecimal.ZERO) - .build(); - }, - evaluation -> { - if(evaluation instanceof RankingRequestDTO rankingRequest){ - Assertions.assertTrue(rankingRequest.isOnboardingKo()); - } else if(evaluation instanceof EvaluationCompletedDTO evaluationCompleted) { - Assertions.assertTrue(expectedOnboardingKoStatuses.contains(evaluationCompleted.getStatus())); - evaluationCompleted.getOnboardingRejectionReasons().remove(OnboardingRejectionReason.builder() - .type(OnboardingRejectionReason.OnboardingRejectionReasonType.FAMILY_CRITERIA_KO) - .code(OnboardingConstants.REJECTION_REASON_FAMILY_CRITERIA_FAIL) - .detail("Nucleo familiare non soddisfa i requisiti") - .build()); - Assertions.assertEquals( - List.of(new OnboardingRejectionReason( - OnboardingRejectionReason.OnboardingRejectionReasonType.AUTOMATED_CRITERIA_FAIL, - OnboardingConstants.REJECTION_REASON_AUTOMATED_CRITERIA_FAIL_FORMAT.formatted(CriteriaCodeConfigFaker.CRITERIA_CODE_ISEE), - CriteriaCodeConfigFaker.CRITERIA_CODE_ISEE_AUTH, - CriteriaCodeConfigFaker.CRITERIA_CODE_ISEE_AUTH_LABEL, - null - )), - evaluationCompleted.getOnboardingRejectionReasons()); - } - } - ), - - // useCase 2: onboardingKo case due to family not found - OnboardingUseCase.withJustPayload( - bias -> { - expectedFamilyRetrieveKo++; - OnboardingDTO request = buildOnboardingRequestBuilder(bias) - .userId("NOFAMILYuserId_" + bias) - .build(); - Mockito.doReturn(Mono.just(Optional.empty())) - .when(familyDataRetrieverServiceSpy) - .retrieveFamily(Mockito.argThat(r->r.getUserId().startsWith(request.getUserId())), Mockito.any()); - return request; - }, - evaluation -> { - if(evaluation instanceof RankingRequestDTO rankingRequest){ - Assertions.assertTrue(rankingRequest.isOnboardingKo()); - } else if(evaluation instanceof EvaluationCompletedDTO evaluationCompleted) { - Assertions.assertTrue(expectedOnboardingKoStatuses.contains(evaluationCompleted.getStatus())); - Assertions.assertEquals( - List.of(new OnboardingRejectionReason( - OnboardingRejectionReason.OnboardingRejectionReasonType.FAMILY_KO, - OnboardingConstants.REJECTION_REASON_FAMILY_KO, - CriteriaCodeConfigFaker.CRITERIA_CODE_FAMILY_AUTH, - CriteriaCodeConfigFaker.CRITERIA_CODE_FAMILY_AUTH_LABEL, - "Nucleo familiare non disponibile" - )), - evaluationCompleted.getOnboardingRejectionReasons()); - } - } - ) - ); - //endregion - { - onboardingFamilies= Math.max(10, TestUtils.nextOrSameEvenNumber(useCases.size())); - } - - protected void checkPayload(String errorMessage, String expectedPayload) { - try { - RankingRequestDTO actual = objectMapper.readValue(errorMessage, RankingRequestDTO.class); - RankingRequestDTO expected = objectMapper.readValue(expectedPayload, RankingRequestDTO.class); - - TestUtils.checkNotNullFields(actual, "familyId"); - Assertions.assertEquals(expected.getUserId(), actual.getUserId()); - Assertions.assertEquals(expected.getInitiativeId(), actual.getInitiativeId()); - } catch (JsonProcessingException e) { - Assertions.fail("Error check in payload"); - } - } -} \ No newline at end of file diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigRankingTestDeprecated.java b/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigRankingTestDeprecated.java deleted file mode 100644 index 8b55e3bb..00000000 --- a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigRankingTestDeprecated.java +++ /dev/null @@ -1,229 +0,0 @@ -package it.gov.pagopa.admissibility.connector.event.processor; - -import com.fasterxml.jackson.core.JsonProcessingException; -import it.gov.pagopa.admissibility.connector.event.consumer.BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated; -import it.gov.pagopa.admissibility.dto.onboarding.OnboardingDTO; -import it.gov.pagopa.admissibility.dto.onboarding.RankingRequestDTO; -import it.gov.pagopa.admissibility.dto.onboarding.extra.BirthDate; -import it.gov.pagopa.admissibility.dto.rule.Initiative2BuildDTO; -import it.gov.pagopa.admissibility.service.onboarding.notifier.RankingNotifierService; -import it.gov.pagopa.admissibility.test.fakers.Initiative2BuildDTOFaker; -import it.gov.pagopa.admissibility.test.fakers.OnboardingDTOFaker; -import it.gov.pagopa.common.mongo.MongoTestUtilitiesService; -import it.gov.pagopa.common.utils.TestUtils; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.common.KafkaException; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.data.domain.Sort; -import org.springframework.data.util.Pair; -import org.springframework.messaging.Message; -import org.springframework.messaging.support.MessageBuilder; -import org.springframework.test.context.ContextConfiguration; - -import java.io.IOException; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; -import java.util.function.Supplier; -import java.util.stream.IntStream; - -@ContextConfiguration -@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) -class AdmissibilityProcessorConfigRankingTestDeprecated extends BaseAdmissibilityProcessorConfigTest { - - private static final String INITIATIVEID = "INITIATIVEID_0"; - - @SpyBean - private RankingNotifierService rankingNotifierServiceSpy; - - @TestConfiguration - static class MediatorSpyConfiguration extends BaseAdmissibilityProcessorConfigTest.MediatorSpyConfiguration {} - - @Test - void testRankingAdmissibilityOnboarding() throws IOException { - int validOnboardings = Math.max(6, useCases.size()); // use even number - int notValidOnboarding = errorUseCases.size(); - long maxWaitingMs = 30000; - - publishOnboardingRules(validOnboardings); - - List> onboardings = new ArrayList<>(buildValidPayloads(errorUseCases.size(), validOnboardings / 2, useCases)); - onboardings.addAll(IntStream.range(0, notValidOnboarding).mapToObj(i -> errorUseCases.get(i).getFirst().get()).map(p-> MessageBuilder.withPayload(p).build()).toList()); - onboardings.addAll(buildValidPayloads(errorUseCases.size() + (validOnboardings / 2) + notValidOnboarding, validOnboardings / 2, useCases)); - - MongoTestUtilitiesService.startMongoCommandListener("ON-BOARDINGS"); - - long timePublishOnboardingStart = System.currentTimeMillis(); - onboardings.forEach(i -> kafkaTestUtilitiesService.publishIntoEmbeddedKafka(topicAdmissibilityProcessorRequest, null, i)); - long timePublishingOnboardingRequest = System.currentTimeMillis() - timePublishOnboardingStart; - - long timeConsumerResponse = System.currentTimeMillis(); - List> payloadConsumed = kafkaTestUtilitiesService.consumeMessages(topicAdmissibilityProcessorOutRankingRequest, validOnboardings, maxWaitingMs); - long timeEnd = System.currentTimeMillis(); - - long timeConsumerResponseEnd = timeEnd - timeConsumerResponse; - - MongoTestUtilitiesService.stopAndPrintMongoCommands(); - - Assertions.assertEquals(validOnboardings, payloadConsumed.size()); - - for (ConsumerRecord p : payloadConsumed) { - RankingRequestDTO rankingRequest = objectMapper.readValue(p.value(), RankingRequestDTO.class); - checkResponse(rankingRequest, useCases); - } - - checkErrorsPublished(notValidOnboarding, maxWaitingMs, errorUseCases); - - System.out.printf(""" - ************************ - Time spent to send %d (%d + %d) onboarding request messages: %d millis - Time spent to consume onboarding responses: %d millis - ************************ - Test Completed in %d millis - ************************ - """, - validOnboardings + notValidOnboarding, - validOnboardings, - notValidOnboarding, - timePublishingOnboardingRequest, - timeConsumerResponseEnd, - timeEnd - timePublishOnboardingStart - ); - - checkOffsets(onboardings.size(), validOnboardings, topicAdmissibilityProcessorOutRankingRequest); - } - - private void publishOnboardingRules(int onboardingsNumber) { - MongoTestUtilitiesService.startMongoCommandListener("RULE PUBLISHING"); - - int[] expectedRules = {0}; - IntStream.range(0, 2) - .mapToObj(i -> { - final Initiative2BuildDTO initiative = Initiative2BuildDTOFaker.mockInstanceBuilder(i) - .build(); - - initiative.getGeneral().setRankingEnabled(true); - initiative.getBeneficiaryRule().getAutomatedCriteria().get(0).setOrderDirection(Sort.Direction.ASC); - - BigDecimal budget = initiative.getGeneral().getBeneficiaryBudget().multiply(BigDecimal.valueOf(onboardingsNumber)); - - initiative.getGeneral().setBudget(budget); - - return initiative; - }) - .peek(i -> expectedRules[0] += i.getBeneficiaryRule().getAutomatedCriteria().size()) - .forEach(i -> kafkaTestUtilitiesService.publishIntoEmbeddedKafka(topicBeneficiaryRuleConsumer, null, null, i)); - - BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.waitForKieContainerBuild(expectedRules[0], onboardingContextHolderServiceSpy); - - MongoTestUtilitiesService.stopAndPrintMongoCommands(); - } - - //region useCases - private final List> useCases = List.of( - // useCase 0: successful case - coda ranking - OnboardingUseCase.withJustPayload( - bias -> buildOnboardingRequestBuilder(bias) - .build(), - rankingRequest -> { - Assertions.assertNotNull(rankingRequest.getUserId()); - Assertions.assertNotNull(rankingRequest.getInitiativeId()); - Assertions.assertNotNull(rankingRequest.getAdmissibilityCheckDate()); - Assertions.assertNotNull(rankingRequest.getRankingValue()); - Assertions.assertFalse(rankingRequest.isOnboardingKo()); - Assertions.assertNull(rankingRequest.getFamilyId()); - } - ), - - // useCase 1: onboardingKo case - OnboardingUseCase.withJustPayload( - bias -> buildOnboardingRequestBuilder(bias) - .isee(BigDecimal.ZERO) - .build(), - rankingRequest -> { - Assertions.assertNotNull(rankingRequest.getUserId()); - Assertions.assertNotNull(rankingRequest.getInitiativeId()); - Assertions.assertNotNull(rankingRequest.getAdmissibilityCheckDate()); - Assertions.assertNotNull(rankingRequest.getRankingValue()); - Assertions.assertTrue(rankingRequest.isOnboardingKo()); - } - ) - ); - //endregion - - private OnboardingDTO.OnboardingDTOBuilder buildOnboardingRequestBuilder(Integer bias) { - return OnboardingDTOFaker.mockInstanceBuilder(bias, INITIATIVEID) - .isee(BigDecimal.valueOf(20)) - .birthDate(new BirthDate("1990", LocalDate.now().getYear() - 1990)); - } - - - //region not valid useCases - // all use cases configured must have a unique id recognized by the regexp errorUseCaseIdPatternMatch - private final List, Consumer>>> errorUseCases = new ArrayList<>(); - { - // errorUseCase 0 - final String failingRankingPublishingUserId = "userId_0_FAILING_ONBOARDING_PUBLISHING"; - OnboardingDTO rankingFailinPublishing = buildOnboardingRequestBuilder(0) - .userId(failingRankingPublishingUserId) - .build(); - errorUseCases.add(Pair.of( - () -> { - Mockito.doReturn(false).when(rankingNotifierServiceSpy).notify(Mockito.argThat(i -> failingRankingPublishingUserId.equals(i.getUserId()))); - return TestUtils.jsonSerializer(rankingFailinPublishing); - }, - errorMessage-> { - RankingRequestDTO expectedEvaluationFailingPublishing = retrieveEvaluationDTOErrorUseCase(rankingFailinPublishing); - checkErrorMessageHeaders(kafkaBootstrapServers,topicAdmissibilityProcessorOutRankingRequest,null, errorMessage, "[ONBOARDING_REQUEST] An error occurred while publishing the ranking request", TestUtils.jsonSerializer(expectedEvaluationFailingPublishing),null, false, false); - } - )); - - // errorUseCase 1 - final String exceptionWhenRankingPublishingUserId = "userId_1_FAILING_ONBOARDING_PUBLISHING_DUE_EXCEPTION"; - OnboardingDTO exceptionWhenRankingPublishing = buildOnboardingRequestBuilder(errorUseCases.size()) - .userId(exceptionWhenRankingPublishingUserId) - .build(); - errorUseCases.add(Pair.of( - () -> { - Mockito.doThrow(new KafkaException()).when(rankingNotifierServiceSpy).notify(Mockito.argThat(i -> exceptionWhenRankingPublishingUserId.equals(i.getUserId()))); - return TestUtils.jsonSerializer(exceptionWhenRankingPublishing); - }, - errorMessage-> { - RankingRequestDTO expectedEvaluationFailingPublishing = retrieveEvaluationDTOErrorUseCase(exceptionWhenRankingPublishing); - checkErrorMessageHeaders(kafkaBootstrapServers,topicAdmissibilityProcessorOutRankingRequest,null, errorMessage, "[ONBOARDING_REQUEST] An error occurred while publishing the ranking request", TestUtils.jsonSerializer(expectedEvaluationFailingPublishing),null, false, false); - } - )); - } - - private RankingRequestDTO retrieveEvaluationDTOErrorUseCase(OnboardingDTO onboardingDTO) { - return RankingRequestDTO.builder() - .userId(onboardingDTO.getUserId()) - .organizationId(onboardingDTO.getInitiativeId().replace("INITIATIVEID", "ORGANIZATIONID")) - .initiativeId(onboardingDTO.getInitiativeId()) - .admissibilityCheckDate(LocalDateTime.now()) - .criteriaConsensusTimestamp(onboardingDTO.getCriteriaConsensusTimestamp()) - .rankingValue(2000L) - .build(); - } - //endregion - - protected void checkPayload(String errorMessage, String expectedPayload) { - try { - RankingRequestDTO actual = objectMapper.readValue(errorMessage, RankingRequestDTO.class); - RankingRequestDTO expected = objectMapper.readValue(expectedPayload, RankingRequestDTO.class); - - TestUtils.checkNotNullFields(actual, "familyId"); - Assertions.assertEquals(expected.getUserId(), actual.getUserId()); - Assertions.assertEquals(expected.getInitiativeId(), actual.getInitiativeId()); - } catch (JsonProcessingException e) { - Assertions.fail("Error check in payload"); - } - } -} \ No newline at end of file diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigTestDeprecated.java b/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigTestDeprecated.java deleted file mode 100644 index 95d0028b..00000000 --- a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/AdmissibilityProcessorConfigTestDeprecated.java +++ /dev/null @@ -1,833 +0,0 @@ -package it.gov.pagopa.admissibility.connector.event.processor; - -import com.fasterxml.jackson.core.JsonProcessingException; -import it.gov.pagopa.admissibility.config.PagoPaAnprPdndConfig; -import it.gov.pagopa.admissibility.connector.event.consumer.BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated; -import it.gov.pagopa.admissibility.connector.rest.anpr.service.AnprC001RestClientImplIntegrationTest; -import it.gov.pagopa.admissibility.connector.soap.inps.service.IseeConsultationSoapClientImplIntegrationTestDeprecated; -import it.gov.pagopa.admissibility.drools.model.filter.FilterOperator; -import it.gov.pagopa.admissibility.dto.onboarding.EvaluationCompletedDTO; -import it.gov.pagopa.admissibility.dto.onboarding.OnboardingDTO; -import it.gov.pagopa.admissibility.dto.onboarding.OnboardingRejectionReason; -import it.gov.pagopa.admissibility.dto.onboarding.extra.BirthDate; -import it.gov.pagopa.admissibility.dto.onboarding.extra.Residence; -import it.gov.pagopa.admissibility.dto.rule.AutomatedCriteriaDTO; -import it.gov.pagopa.admissibility.dto.rule.Initiative2BuildDTO; -import it.gov.pagopa.admissibility.dto.rule.InitiativeBeneficiaryRuleDTO; -import it.gov.pagopa.admissibility.enums.OnboardingEvaluationStatus; -import it.gov.pagopa.admissibility.model.IseeTypologyEnum; -import it.gov.pagopa.admissibility.model.PdndInitiativeConfig; -import it.gov.pagopa.admissibility.service.onboarding.notifier.OnboardingNotifierService; -import it.gov.pagopa.admissibility.test.fakers.CriteriaCodeConfigFaker; -import it.gov.pagopa.admissibility.test.fakers.Initiative2BuildDTOFaker; -import it.gov.pagopa.admissibility.test.fakers.OnboardingDTOFaker; -import it.gov.pagopa.admissibility.utils.OnboardingConstants; -import it.gov.pagopa.common.kafka.utils.KafkaConstants; -import it.gov.pagopa.common.mongo.MongoTestUtilitiesService; -import it.gov.pagopa.common.reactive.pdnd.service.PdndRestClient; -import it.gov.pagopa.common.reactive.pdv.service.UserFiscalCodeService; -import it.gov.pagopa.common.utils.TestUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.common.KafkaException; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -import org.mockito.stubbing.Answer; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.data.util.Pair; -import org.springframework.messaging.Message; -import org.springframework.messaging.support.MessageBuilder; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import reactor.core.publisher.Mono; - -import java.io.IOException; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.*; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -@ContextConfiguration(classes = {AdmissibilityProcessorConfigTestDeprecated.MediatorSpyConfiguration.class}) -@TestPropertySource(properties = { - "logging.level.it.gov.pagopa.admissibility.service.onboarding.check.OnboardingInitiativeCheck=OFF", - "logging.level.it.gov.pagopa.admissibility.service.onboarding.OnboardingContextHolderServiceImpl=OFF", - "logging.level.it.gov.pagopa.admissibility.service.onboarding.AdmissibilityEvaluatorMediatorServiceImpl=OFF", - "logging.level.it.gov.pagopa.admissibility.connector.soap.inps.service.IseeConsultationSoapClientImpl=OFF", - "logging.level.it.gov.pagopa.common.reactive.pdnd.service.BaseRestPdndServiceClient=OFF", -}) -@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) -class AdmissibilityProcessorConfigTestDeprecated extends BaseAdmissibilityProcessorConfigTest { - public static final String CF_AUTHORITIES_DATA_ALLOWED = "CF_OK_2"; - public static final String CF_INVALID_REQUEST = AnprC001RestClientImplIntegrationTest.FISCAL_CODE_INVALIDREQUEST; - public static final String CF_INPS_RETRY = IseeConsultationSoapClientImplIntegrationTestDeprecated.FISCAL_CODE_RETRY; - public static final String CF_INPS_UNEXPECTED_RESULTCODE = IseeConsultationSoapClientImplIntegrationTestDeprecated.FISCAL_CODE_UNEXPECTED_RESULT_CODE; - public static final String CF_NOT_FOUND = AnprC001RestClientImplIntegrationTest.FISCAL_CODE_NOTFOUND; - public static final String CF_ANPR_TOO_MANY_REQUESTS = AnprC001RestClientImplIntegrationTest.FISCAL_CODE_TOOMANYREQUESTS; - public static final String CF_INPS_TOO_MANY_REQUESTS = IseeConsultationSoapClientImplIntegrationTestDeprecated.FISCAL_CODE_TOOMANYREQUESTS; - - private static final String INITIATIVEID_EXHAUSTED = "EXHAUSTED_INITIATIVE_ID"; - private static final String INITIATIVEID_FAILING_BUDGET_RESERVATION = "FAILING_BUDGET_RESERVATION"; - private static final String INITIATIVEID_COMPLETE = "COMPLETE_INITIATIVE_ID"; - private static final String INITIATIVEID_PDNDIVOKEERROR = "PDNDERRORUSECASE"; - private static final String INITIATIVEID_MULTIPLE_ISEE_TYPES = "MULTIPLE_ISEE_TYPES"; - - private static final String PDND_CLIENT_ID_RESIDENCE = "CLIENTID_RESIDENCEINITIATIVE"; - private static final String PDND_CLIENT_ID_ISEE = "CLIENTID_ISEEINITIATIVE"; - private static final String PDND_CLIENT_ID_BIRTHDATE = "CLIENTID_BIRTHDATEINITIATIVE"; - private static final String PDND_CLIENT_ID_PDND_ERROR = "CLIENTID_PDNDERROR"; - -//region OnboardingRejectionReason constants - public static final OnboardingRejectionReason ONBOARDING_REJECTION_REASON_ISEE_TYPE_KO = OnboardingRejectionReason.builder() - .type(OnboardingRejectionReason.OnboardingRejectionReasonType.ISEE_TYPE_KO) - .code(OnboardingConstants.REJECTION_REASON_ISEE_TYPE_KO) - .authority("INPS") - .authorityLabel("Istituto Nazionale Previdenza Sociale") - .detail("ISEE non disponibile") - .build(); - public static final OnboardingRejectionReason ONBOARDING_REJECTION_REASON_RESIDENCE_KO = OnboardingRejectionReason.builder() - .type(OnboardingRejectionReason.OnboardingRejectionReasonType.RESIDENCE_KO) - .code(OnboardingConstants.REJECTION_REASON_RESIDENCE_KO) - .authority("AGID") - .authorityLabel("Agenzia per l'Italia Digitale") - .detail("Residenza non disponibile") - .build(); - public static final OnboardingRejectionReason ONBOARDING_REJECTION_REASON_BIRTHDATE_KO = OnboardingRejectionReason.builder() - .type(OnboardingRejectionReason.OnboardingRejectionReasonType.BIRTHDATE_KO) - .code(OnboardingConstants.REJECTION_REASON_BIRTHDATE_KO) - .authority("AGID") - .authorityLabel("Agenzia per l'Italia Digitale") - .detail("Data di nascita non disponibile") - .build(); - - public static final OnboardingRejectionReason ONBOARDING_REJECTION_REASON_ISEE = OnboardingRejectionReason.builder() - .type(OnboardingRejectionReason.OnboardingRejectionReasonType.AUTOMATED_CRITERIA_FAIL) - .code(OnboardingConstants.REJECTION_REASON_AUTOMATED_CRITERIA_FAIL_FORMAT.formatted("ISEE")) - .authority("INPS") - .authorityLabel("Istituto Nazionale Previdenza Sociale") - .build(); - public static final OnboardingRejectionReason ONBOARDING_REJECTION_REASON_RESIDENCE = OnboardingRejectionReason.builder() - .type(OnboardingRejectionReason.OnboardingRejectionReasonType.AUTOMATED_CRITERIA_FAIL) - .code(OnboardingConstants.REJECTION_REASON_AUTOMATED_CRITERIA_FAIL_FORMAT.formatted("RESIDENCE")) - .authority("AGID") - .authorityLabel("Agenzia per l'Italia Digitale") - .build(); - public static final OnboardingRejectionReason ONBOARDING_REJECTION_REASON_BIRTHDATE = OnboardingRejectionReason.builder() - .type(OnboardingRejectionReason.OnboardingRejectionReasonType.AUTOMATED_CRITERIA_FAIL) - .code(OnboardingConstants.REJECTION_REASON_AUTOMATED_CRITERIA_FAIL_FORMAT.formatted("BIRTHDATE")) - .authority("AGID") - .authorityLabel("Agenzia per l'Italia Digitale") - .build(); - - public static final OnboardingRejectionReason ONBOARDING_REJECTION_REASON_CONSENSUS_TC = buildOnboardingRejectionReasonConsensusMissed(OnboardingConstants.REJECTION_REASON_CONSENSUS_TC_FAIL); - public static final OnboardingRejectionReason ONBOARDING_REJECTION_REASON_CONSENSUS_PDND = buildOnboardingRejectionReasonConsensusMissed(OnboardingConstants.REJECTION_REASON_CONSENSUS_PDND_FAIL); - public static final OnboardingRejectionReason ONBOARDING_REJECTION_REASON_INVALID_REQUEST_INITIATIVE_NOT_EXISTS = buildOnboardingRejectionReasonInvalidRequest(OnboardingConstants.REJECTION_REASON_INVALID_INITIATIVE_ID_FAIL); - public static final OnboardingRejectionReason ONBOARDING_REJECTION_REASON_INVALID_REQUEST_TC_OUT_OF_DATE = buildOnboardingRejectionReasonInvalidRequest(OnboardingConstants.REJECTION_REASON_TC_CONSENSUS_DATETIME_FAIL); - public static final OnboardingRejectionReason ONBOARDING_REJECTION_REASON_INVALID_REQUEST_CONSENSUS_OUT_OF_DATE = buildOnboardingRejectionReasonInvalidRequest(OnboardingConstants.REJECTION_REASON_CRITERIA_CONSENSUS_DATETIME_FAIL); - public static final OnboardingRejectionReason ONBOARDING_REJECTION_REASON_BUDGET_EXHAUSTED = OnboardingRejectionReason.builder() - .type(OnboardingRejectionReason.OnboardingRejectionReasonType.BUDGET_EXHAUSTED) - .code(OnboardingConstants.REJECTION_REASON_INITIATIVE_BUDGET_EXHAUSTED) - .build(); - public static final OnboardingRejectionReason ONBOARDING_REJECTION_REASON_GENERIC_ERROR = OnboardingRejectionReason.builder() - .type(OnboardingRejectionReason.OnboardingRejectionReasonType.TECHNICAL_ERROR) - .code(OnboardingConstants.REJECTION_REASON_GENERIC_ERROR) - .build(); -//endregion - - @SpyBean - private OnboardingNotifierService onboardingNotifierServiceSpy; - @SpyBean - private UserFiscalCodeService userFiscalCodeServiceSpy; - @SpyBean - private PdndRestClient pdndRestClientSpy; - - @Autowired - private PagoPaAnprPdndConfig pagoPaAnprPdndConfig; - - @Value("${app.onboarding-request.max-retry}") - private int maxRetry; - private int expectedRescheduling = 0; - - private final Map userId2CFMocks = new HashMap<>(); - private final Map>> userId2CFAnswers = new HashMap<>(); - - @TestConfiguration - static class MediatorSpyConfiguration extends BaseAdmissibilityProcessorConfigTest.MediatorSpyConfiguration{} - - @Test - void testAdmissibilityOnboarding() throws IOException { - int validOnboardings = Math.max(10, TestUtils.nextOrSameEvenNumber(useCases.size())); // use even number - int notValidOnboarding = errorUseCases.size(); - long maxWaitingMs = 30000; - - publishOnboardingRules(validOnboardings); - - List> onboardings = new ArrayList<>(buildValidPayloads(notValidOnboarding, validOnboardings / 2, useCases)); - onboardings.addAll(IntStream.range(0, notValidOnboarding).mapToObj(i -> errorUseCases.get(i).getFirst().get()).map(p-> MessageBuilder.withPayload(p).build()).toList()); - onboardings.addAll(buildValidPayloads(notValidOnboarding + (validOnboardings / 2), validOnboardings / 2, useCases)); - - Mockito.doAnswer(i -> { - String cf = i.getArgument(0); - String mockedCF = userId2CFMocks.get(cf); - if (mockedCF != null) { - return Mono.just(mockedCF); - } else { - Answer> mockedAnswer = userId2CFAnswers.get(cf); - if (mockedAnswer != null) { - return mockedAnswer.answer(i); - } else { - return i.callRealMethod(); - } - } - }).when(userFiscalCodeServiceSpy) - .getUserFiscalCode(Mockito.any()); - - MongoTestUtilitiesService.startMongoCommandListener("ON-BOARDINGS"); - - long timePublishOnboardingStart = System.currentTimeMillis(); - onboardings.forEach(i -> kafkaTestUtilitiesService.publishIntoEmbeddedKafka(topicAdmissibilityProcessorRequest, null, i)); - long timePublishingOnboardingRequest = System.currentTimeMillis() - timePublishOnboardingStart; - - long timeConsumerResponse = System.currentTimeMillis(); - List> payloadConsumed = kafkaTestUtilitiesService.consumeMessages(topicAdmissibilityProcessorOutcome, validOnboardings, maxWaitingMs); - long timeEnd = System.currentTimeMillis(); - - MongoTestUtilitiesService.stopAndPrintMongoCommands(); - - long timeConsumerResponseEnd = timeEnd - timeConsumerResponse; - Assertions.assertEquals(validOnboardings, payloadConsumed.size()); - - for (ConsumerRecord p : payloadConsumed) { - EvaluationCompletedDTO evaluation = objectMapper.readValue(p.value(), EvaluationCompletedDTO.class); - checkResponse(evaluation, useCases); - } - - checkPdndAccessTokenInvocations(); - checkErrorsPublished(notValidOnboarding, maxWaitingMs, errorUseCases); - - System.out.printf(""" - ************************ - Time spent to send %d (%d + %d) onboarding request messages: %d millis - Time spent to consume onboarding responses: %d millis - ************************ - Test Completed in %d millis - ************************ - """, - validOnboardings + notValidOnboarding, - validOnboardings, - notValidOnboarding, - timePublishingOnboardingRequest, - timeConsumerResponseEnd, - timeEnd - timePublishOnboardingStart - ); - - checkOffsets(onboardings.size() + expectedRescheduling, validOnboardings, topicAdmissibilityProcessorOutcome); - } - - private void checkPdndAccessTokenInvocations() { - Map pdndClientIdsInvocations = Mockito.mockingDetails(pdndRestClientSpy).getInvocations().stream() - .map(i -> i.getArgument(0, String.class)) - .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); - - Assertions.assertEquals(Set.of( - pagoPaAnprPdndConfig.getClientId() // It should change based on initiative/authority, actually using once for the entire application - ), - pdndClientIdsInvocations.keySet()); - - pdndClientIdsInvocations.forEach((clientId, invocations) -> - Assertions.assertTrue( - // ideally it would be 1, but due to concurrency accesses, more than 1 requests could be performed - // if we want to strengthen this behavior, let's consider to introduce the use of it.gov.pagopa.common.reactive.service.LockService - invocations >= 1 && invocations < 50, - "Unexpected number of ClientId %s invocations: %d".formatted(clientId, invocations))); - } - - private void publishOnboardingRules(int validOnboardings) { - MongoTestUtilitiesService.startMongoCommandListener("RULE PUBLISHING"); - - int[] expectedRules = {0}; - Stream.of( - Initiative2BuildDTOFaker.mockInstanceBuilder(0, BigDecimal.ZERO) - .initiativeId(INITIATIVEID_EXHAUSTED) - .initiativeName("EXHAUSTED_INITIATIVE_NAME") - .build(), - Initiative2BuildDTOFaker.mockInstanceBuilder(1, BigDecimal.TEN) - .initiativeId(INITIATIVEID_FAILING_BUDGET_RESERVATION) - .initiativeName("FAILING_BUDGET_RESERVATION_INITIATIVE_NAME") - .build(), - Initiative2BuildDTOFaker.mockInstanceBuilder(2, Initiative2BuildDTOFaker.BENEFICIARY_BUDGET.multiply(BigDecimal.valueOf(validOnboardings))) - .initiativeId(INITIATIVEID_COMPLETE) - .initiativeName("COMPLETE_INITIATIVE_NAME") - .beneficiaryRule(InitiativeBeneficiaryRuleDTO.builder() - .automatedCriteria(List.of( - AutomatedCriteriaDTO.builder() - .authority("AUTH1") - .code(CriteriaCodeConfigFaker.CRITERIA_CODE_ISEE) - .operator(FilterOperator.GT) - .value("10000") - .iseeTypes(List.of(IseeTypologyEnum.ORDINARIO)) - .pdndConfig(new PdndInitiativeConfig(PDND_CLIENT_ID_ISEE, "KID", "PURPOSE_ID_ISEE")) - .build(), - AutomatedCriteriaDTO.builder() - .authority("AUTH1") - .code(CriteriaCodeConfigFaker.CRITERIA_CODE_RESIDENCE) - .field("city") - .operator(FilterOperator.EQ) - .value("Roma") - .pdndConfig(new PdndInitiativeConfig(PDND_CLIENT_ID_RESIDENCE, "KID", "PURPOSE_ID_RESIDENCE")) - .build(), - AutomatedCriteriaDTO.builder() - .authority("AUTH1") - .code(CriteriaCodeConfigFaker.CRITERIA_CODE_BIRTHDATE) - .field("age") - .operator(FilterOperator.GT) - .value("200") - .pdndConfig(new PdndInitiativeConfig(PDND_CLIENT_ID_BIRTHDATE, "KID", "PURPOSE_ID_BIRTHDATE")) - .build() - )) - .build()) - .build(), - - Initiative2BuildDTOFaker.mockInstanceBuilder(3) - .initiativeId("NEVERSELECTEDINITIATIVE") - .initiativeName("NEVERSELECTEDINITIATIVE_NAME") - .beneficiaryRule(InitiativeBeneficiaryRuleDTO.builder() - .automatedCriteria(List.of( - AutomatedCriteriaDTO.builder() - .authority("AUTH1") - .code(CriteriaCodeConfigFaker.CRITERIA_CODE_RESIDENCE) - .field("city") - .operator(FilterOperator.EQ) - .value("Rome") - .pdndConfig(new PdndInitiativeConfig(PDND_CLIENT_ID_RESIDENCE, "KID", "PURPOSE_ID_RESIDENCE")) - .build() - )) - .build()) - .build(), - - Initiative2BuildDTOFaker.mockInstanceBuilder(4) - .initiativeId(INITIATIVEID_PDNDIVOKEERROR) - .initiativeName("PDNDIVOKEERROR_NAME") - .beneficiaryRule(InitiativeBeneficiaryRuleDTO.builder() - .automatedCriteria(List.of( - AutomatedCriteriaDTO.builder() - .authority("AUTH1") - .code(CriteriaCodeConfigFaker.CRITERIA_CODE_RESIDENCE) - .field("city") - .operator(FilterOperator.EQ) - .value("Rome") - .pdndConfig(new PdndInitiativeConfig(PDND_CLIENT_ID_PDND_ERROR, "KID", "PURPOSEID")) - .build() - )) - .build()) - .build(), - - - Initiative2BuildDTOFaker.mockInstanceBuilder(5, Initiative2BuildDTOFaker.BENEFICIARY_BUDGET.multiply(BigDecimal.valueOf(validOnboardings))) - .initiativeId(INITIATIVEID_MULTIPLE_ISEE_TYPES) - .initiativeName("MULTIPLE_ISEE_TYPES_INITIATIVE_NAME") - .beneficiaryRule(InitiativeBeneficiaryRuleDTO.builder() - .automatedCriteria(List.of( - AutomatedCriteriaDTO.builder() - .authority("AUTH1") - .code(CriteriaCodeConfigFaker.CRITERIA_CODE_ISEE) - .operator(FilterOperator.GT) - .value("10000") - .iseeTypes(List.of(IseeTypologyEnum.CORRENTE, IseeTypologyEnum.MINORENNE, IseeTypologyEnum.RESIDENZIALE, IseeTypologyEnum.ORDINARIO)) - .pdndConfig(new PdndInitiativeConfig(PDND_CLIENT_ID_ISEE, "KID", "PURPOSE_ID_ISEE")) - .build() - )) - .build()) - .build() - ) - .peek(i -> expectedRules[0] += i.getBeneficiaryRule().getAutomatedCriteria().size()) - .forEach(i -> kafkaTestUtilitiesService.publishIntoEmbeddedKafka(topicBeneficiaryRuleConsumer, null, null, i)); - - BeneficiaryRuleBuilderConsumerConfigIntegrationTestDeprecated.waitForKieContainerBuild(expectedRules[0], onboardingContextHolderServiceSpy); - - MongoTestUtilitiesService.stopAndPrintMongoCommands(); - } - - private OnboardingDTO.OnboardingDTOBuilder buildOnboardingRequestCachedBuilder(Integer bias) { - return OnboardingDTOFaker.mockInstanceBuilder(bias, INITIATIVEID_COMPLETE) - .isee(BigDecimal.valueOf(15_000)) - .residence(new Residence("058091", "ROMA", "RM", "ROMA", "LAZIO", "ITALIA")) - .birthDate(new BirthDate("1790", LocalDate.now().getYear() - 1790)); - } - - //region useCases - private final List> useCases = List.of( - // useCase 0: successful use case where AutomatedCriteria were cached - OnboardingUseCase.withJustPayload( - bias -> buildOnboardingRequestCachedBuilder(bias) - .build(), - evaluation -> checkOk(evaluation, false) - ), - - // useCase 1: TC consensus fail - OnboardingUseCase.withJustPayload( - bias -> OnboardingDTOFaker.mockInstanceBuilder(bias, INITIATIVEID_COMPLETE) - .tc(false) - .build(), - evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_CONSENSUS_TC), true) - ), - - // useCase 2: PDND consensuns fail - OnboardingUseCase.withJustPayload( - bias -> OnboardingDTOFaker.mockInstanceBuilder(bias, INITIATIVEID_COMPLETE) - .pdndAccept(false) - .build(), - evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_CONSENSUS_PDND), true) - ), - - // self declaration fail - // Handle multi and boolean criteria - /* - OnboardingUseCase.withJustPayload( - bias -> OnboardingDTOFaker.mockInstanceBuilder(bias, INITIATIVEID_COMPLETE) - .selfDeclarationList(Map.of("DUMMY", false)) - .build(), - evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_CONSENSUS_SELF_DECLARATION), true) - ), - */ - - // useCase 3: No initiative - OnboardingUseCase.withJustPayload( - bias -> OnboardingDTOFaker.mockInstanceBuilder(bias, INITIATIVEID_COMPLETE) - .initiativeId("NOT_EXISTENT") - .tcAcceptTimestamp(LocalDateTime.now().withYear(1970)) - .build(), - evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_INVALID_REQUEST_INITIATIVE_NOT_EXISTS), false) - ), - - // useCase 4: TC acceptance timestamp fail - OnboardingUseCase.withJustPayload( - bias -> OnboardingDTOFaker.mockInstanceBuilder(bias, INITIATIVEID_COMPLETE) - .tcAcceptTimestamp(LocalDateTime.now().withYear(1970)) - .build(), - evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_INVALID_REQUEST_TC_OUT_OF_DATE), true) - ), - - // useCase 5: TC criteria acceptance timestamp fail - OnboardingUseCase.withJustPayload( - bias -> OnboardingDTOFaker.mockInstanceBuilder(bias, INITIATIVEID_COMPLETE) - .criteriaConsensusTimestamp(LocalDateTime.now().withYear(1970)) - .build(), - evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_INVALID_REQUEST_CONSENSUS_OUT_OF_DATE), true) - ), - - // useCase -: error when invoking PDND - // TODO actually not testable because the entire application will use the same PDNDInitiativeConfig not read from InitiativeConfig -// OnboardingUseCase.withJustPayload( -// bias -> { -// OnboardingDTO out = OnboardingDTOFaker.mockInstance(bias, INITIATIVEID_PDNDIVOKEERROR); -// -// Mockito.doReturn(Mono.error(new RuntimeException("DUMMYEXCEPTION"))).when(pdndRestClientSpy) -// .createToken(Mockito.eq(PDND_CLIENT_ID_PDND_ERROR), Mockito.anyString()); -// -// return out; -// }, -// evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_RESIDENCE_KO), true) -// ), - - // useCase 6: AUTOMATED_CRITERIA fails due to ISEE, RESIDENCE and BIRTHDATE: - // PDV will return CF_OK fiscalCode, for which: - // INPS stub will return a ISEE of 10.000, actual initiative allow > 10.000 - // ANPR stub will return PAVULLO NEL FRIGNANO as RESIDENCE and 1990-01-01 as BIRTHDATE - OnboardingUseCase.withJustPayload( - bias -> OnboardingDTOFaker.mockInstance(bias, INITIATIVEID_COMPLETE), - evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_ISEE, ONBOARDING_REJECTION_REASON_RESIDENCE, ONBOARDING_REJECTION_REASON_BIRTHDATE), true) - ), - - // useCase 7: ONBOARDING_OK invoking PDND services: - // PDV will return CF_OK_2 fiscalCode, for which: - // INPS stub will return a ISEE of 15.000, actual initiative allow > 10.000 - // ANPR stub will return ROMA as RESIDENCE and 1790-01-01 as BIRTHDATE - OnboardingUseCase.withJustPayload( - bias -> { - OnboardingDTO out = OnboardingDTOFaker.mockInstance(bias, INITIATIVEID_COMPLETE); - - userId2CFMocks.put(out.getUserId(), CF_AUTHORITIES_DATA_ALLOWED); - - return out; - }, - evaluation -> checkOk(evaluation, true) - ), - - // useCase 8: AUTOMATED_CRITERIA fail due to CF not found - OnboardingUseCase.withJustPayload( - bias -> { - OnboardingDTO out = OnboardingDTOFaker.mockInstance(bias, INITIATIVEID_COMPLETE); - - userId2CFMocks.put(out.getUserId(), CF_NOT_FOUND); - - return out; - }, - evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_ISEE_TYPE_KO, ONBOARDING_REJECTION_REASON_RESIDENCE_KO, ONBOARDING_REJECTION_REASON_BIRTHDATE_KO), true) - ), - - // useCase 9: retry due to ISEE Esito KO, then ONBOARDING_KO due to ANPR (just INPS is invoked again, ANPR result will be cached and its first attempt will retrieve default values, not allowed by criteria) - OnboardingUseCase.withJustPayload( - bias -> { - OnboardingDTO out = OnboardingDTOFaker.mockInstance(bias, INITIATIVEID_COMPLETE); - - AtomicBoolean isRetry = new AtomicBoolean(false); - userId2CFAnswers.put(out.getUserId(), - i -> !isRetry.getAndSet(true) - ? Mono.just(CF_INPS_RETRY) - : Mono.just(CF_AUTHORITIES_DATA_ALLOWED) - ); - - expectedRescheduling++; - - return out; - }, - evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_RESIDENCE, ONBOARDING_REJECTION_REASON_BIRTHDATE), true) - ), - - // useCase 10: multiple Isee typologies - OnboardingUseCase.withJustPayload( - bias -> { - OnboardingDTO out = OnboardingDTOFaker.mockInstance(bias, INITIATIVEID_MULTIPLE_ISEE_TYPES); - - userId2CFMocks.put(out.getUserId(), CF_AUTHORITIES_DATA_ALLOWED); - - return out; - }, - evaluation -> checkOk(evaluation, true) - ), - - // useCase 11: daily limit reached when invoking INPS, then ONBOARDING_KO due to ANPR (just INPS is invoked again, ANPR result will be cached and its first attempt will retrieve default values, not allowed by criteria) - OnboardingUseCase.withJustPayload( - bias -> { - OnboardingDTO out = OnboardingDTOFaker.mockInstance(bias, INITIATIVEID_COMPLETE); - - AtomicBoolean isRetry = new AtomicBoolean(false); - userId2CFAnswers.put(out.getUserId(), - i -> !isRetry.getAndSet(true) - ? Mono.just(CF_INPS_TOO_MANY_REQUESTS) - : Mono.just(CF_AUTHORITIES_DATA_ALLOWED) - ); - - expectedRescheduling++; - - return out; - }, - evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_RESIDENCE, ONBOARDING_REJECTION_REASON_BIRTHDATE), true) - ), - - // useCase 12: daily limit reached when invoking ANPR, then ONBOARDING_KO due to INPS (just ANPR is invoked again, INPS result will be cached and its first attempt will retrieve default values, not allowed by criteria) - OnboardingUseCase.withJustPayload( - bias -> { - OnboardingDTO out = OnboardingDTOFaker.mockInstance(bias, INITIATIVEID_COMPLETE); - - AtomicBoolean isRetry = new AtomicBoolean(false); - userId2CFAnswers.put(out.getUserId(), - i -> !isRetry.getAndSet(true) - ? Mono.just(CF_ANPR_TOO_MANY_REQUESTS) - : Mono.just(CF_AUTHORITIES_DATA_ALLOWED) - ); - - expectedRescheduling++; - - return out; - }, - evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_ISEE), true) - ), - - // useCase 13: exhausted initiative budget - OnboardingUseCase.withJustPayload( - bias -> buildOnboardingRequestCachedBuilder(bias) - .initiativeId(INITIATIVEID_EXHAUSTED) - .build(), - evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_BUDGET_EXHAUSTED), true) - ), - - // useCase 14: evaluation throws exception, but retry header expired - new OnboardingUseCase<>( - bias -> { - OnboardingDTO out = OnboardingDTOFaker.mockInstance(bias, INITIATIVEID_COMPLETE); - - Mockito.doReturn(Mono.error(new RuntimeException("DUMMYEXCEPTION"))).when(authoritiesDataRetrieverServiceSpy).retrieve( - Mockito.argThat(i->out.getUserId().equals(i.getUserId())), Mockito.any(), Mockito.any()); - - return MessageBuilder.withPayload(out).setHeader(KafkaConstants.ERROR_MSG_HEADER_RETRY, maxRetry+"").build(); - }, - evaluation -> checkKO(evaluation, List.of(ONBOARDING_REJECTION_REASON_GENERIC_ERROR), true) - ) - - ); - - private static OnboardingRejectionReason buildOnboardingRejectionReasonInvalidRequest(String code) { - return OnboardingRejectionReason.builder() - .type(OnboardingRejectionReason.OnboardingRejectionReasonType.INVALID_REQUEST) - .code(code) - .build(); - } - - private static OnboardingRejectionReason buildOnboardingRejectionReasonConsensusMissed(String code) { - return OnboardingRejectionReason.builder() - .type(OnboardingRejectionReason.OnboardingRejectionReasonType.CONSENSUS_MISSED) - .code(code) - .build(); - } - - private void assertEvaluationFields(EvaluationCompletedDTO evaluation, boolean expectedInitiativeFieldFilled){ - Assertions.assertNotNull(evaluation.getUserId()); - Assertions.assertNotNull(evaluation.getInitiativeId()); - Assertions.assertNotNull(evaluation.getStatus()); - Assertions.assertNotNull(evaluation.getAdmissibilityCheckDate()); - Assertions.assertNotNull(evaluation.getOnboardingRejectionReasons()); - - Assertions.assertNull(evaluation.getFamilyId()); - - if(expectedInitiativeFieldFilled) { - Assertions.assertNotNull(evaluation.getInitiativeName()); - Assertions.assertNotNull(evaluation.getOrganizationId()); - } else { - Assertions.assertNull(evaluation.getInitiativeName()); - Assertions.assertNull(evaluation.getOrganizationId()); - } - } - - private void checkOk(EvaluationCompletedDTO evaluation, boolean expectedPdndInvoked) { - Assertions.assertEquals(Collections.emptyList(), evaluation.getOnboardingRejectionReasons()); - Assertions.assertEquals(OnboardingEvaluationStatus.ONBOARDING_OK, evaluation.getStatus()); - assertEvaluationFields(evaluation, true); - - if(expectedPdndInvoked){ - Mockito.verify(userFiscalCodeServiceSpy).getUserFiscalCode(evaluation.getUserId()); - } else { - Mockito.verify(userFiscalCodeServiceSpy, Mockito.never()).getUserFiscalCode(evaluation.getUserId()); - } - } - - private void checkKO(EvaluationCompletedDTO evaluation, List expectedRejectionReason, boolean expectedInitiativeFieldFilled) { - Assertions.assertEquals(OnboardingEvaluationStatus.ONBOARDING_KO, evaluation.getStatus()); - Assertions.assertNotNull(evaluation.getOnboardingRejectionReasons()); - Assertions.assertEquals(expectedRejectionReason, evaluation.getOnboardingRejectionReasons()); - - - assertEvaluationFields(evaluation, expectedInitiativeFieldFilled); - } - - //endregion - - - //region not valid useCases - // all use cases configured must have a unique id recognized by the regexp errorUseCaseIdPatternMatch - private final List, Consumer>>> errorUseCases = new ArrayList<>(); - { - //errorUseCase 0 - { - String useCaseJsonNotExpected = "{\"userId\":\"userId_0\",unexpectedStructure:0}"; - errorUseCases.add(Pair.of( - () -> useCaseJsonNotExpected, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_ONBOARDING_REQUEST] Unexpected JSON", useCaseJsonNotExpected) - )); - } - - //errorUseCase 1 - { - String jsonNotValid = "{\"userId\":\"userId_1\",invalidJson"; - errorUseCases.add(Pair.of( - () -> jsonNotValid, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_ONBOARDING_REQUEST] Unexpected JSON", jsonNotValid) - )); - } - - //errorUseCase 2 - { - final String failingOnboardingChecksUserId = "userId_2_FAILING_ONBOARDING_CHECKS"; - String failingOnboardingChecks = TestUtils.jsonSerializer( - OnboardingDTOFaker.mockInstanceBuilder(errorUseCases.size(), INITIATIVEID_COMPLETE) - .userId(failingOnboardingChecksUserId) - .build() - ); - errorUseCases.add(Pair.of( - () -> { - Mockito.doThrow(new RuntimeException("DUMMYEXCEPTION")).when(onboardingCheckServiceSpy).check(Mockito.argThat(i -> failingOnboardingChecksUserId.equals(i.getUserId())), Mockito.any(), Mockito.any()); - return failingOnboardingChecks; - }, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_ONBOARDING_REQUEST] An error occurred handling onboarding request", failingOnboardingChecks) - )); - } - - //errorUseCase 3 - { - final String failingAuthorityDataUserId = "userId_3_FAILING_AUTHORITY_DATA"; - String failingAuthoritiesDataRetriever = TestUtils.jsonSerializer( - OnboardingDTOFaker.mockInstanceBuilder(errorUseCases.size(), INITIATIVEID_COMPLETE) - .userId(failingAuthorityDataUserId) - .build() - ); - errorUseCases.add(Pair.of( - () -> { - Mockito.doReturn(Mono.error(new RuntimeException("DUMMYEXCEPTION"))).when(authoritiesDataRetrieverServiceSpy).retrieve(Mockito.argThat(i -> failingAuthorityDataUserId.equals(i.getUserId())), Mockito.any(), Mockito.any()); - return failingAuthoritiesDataRetriever; - }, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_ONBOARDING_REQUEST] An error occurred handling onboarding request", failingAuthoritiesDataRetriever) - )); - } - - //errorUseCase 4 - { - final String failingRuleEngineUserId = "userId_4_FAILING_RULE_ENGINE"; - String failingRuleEngineUseCase = TestUtils.jsonSerializer( - buildOnboardingRequestCachedBuilder(errorUseCases.size()) - .userId(failingRuleEngineUserId) - .build() - ); - errorUseCases.add(Pair.of( - () -> { - Mockito.doThrow(new RuntimeException("DUMMYEXCEPTION")).when(ruleEngineServiceSpy).applyRules(Mockito.argThat(i -> failingRuleEngineUserId.equals(i.getUserId())), Mockito.any()); - return failingRuleEngineUseCase; - }, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_ONBOARDING_REQUEST] An error occurred handling onboarding request", failingRuleEngineUseCase) - )); - } - - //errorUseCase 5 - { - final String failingOnboardingPublishingUserId = "userId_5_FAILING_ONBOARDING_PUBLISHING"; - OnboardingDTO onboardingFailingPublishing = buildOnboardingRequestCachedBuilder(errorUseCases.size()) - .userId(failingOnboardingPublishingUserId) - .build(); - errorUseCases.add(Pair.of( - () -> { - Mockito.doReturn(false).when(onboardingNotifierServiceSpy).notify(Mockito.argThat(i -> failingOnboardingPublishingUserId.equals(i.getUserId()))); - return TestUtils.jsonSerializer(onboardingFailingPublishing); - }, - errorMessage -> { - EvaluationCompletedDTO expectedEvaluationFailingPublishing = retrieveEvaluationDTOErrorUseCase(onboardingFailingPublishing); - checkErrorMessageHeaders(kafkaBootstrapServers, topicAdmissibilityProcessorOutcome, null, errorMessage, "[ONBOARDING_REQUEST] An error occurred while publishing the onboarding evaluation result", TestUtils.jsonSerializer(expectedEvaluationFailingPublishing), null, false, false); - } - )); - } - - //errorUseCase 6 - { - final String exceptionWhenOnboardingPublishingUserId = "userId_6_FAILING_REWARD_PUBLISHING_DUE_EXCEPTION"; - OnboardingDTO exceptionWhenOnboardingPublishing = buildOnboardingRequestCachedBuilder(errorUseCases.size()) - .userId(exceptionWhenOnboardingPublishingUserId) - .build(); - errorUseCases.add(Pair.of( - () -> { - Mockito.doThrow(new KafkaException()).when(onboardingNotifierServiceSpy).notify(Mockito.argThat(i -> exceptionWhenOnboardingPublishingUserId.equals(i.getUserId()))); - return TestUtils.jsonSerializer(exceptionWhenOnboardingPublishing); - }, - errorMessage -> { - EvaluationCompletedDTO expectedEvaluationFailingPublishing = retrieveEvaluationDTOErrorUseCase(exceptionWhenOnboardingPublishing); - checkErrorMessageHeaders(kafkaBootstrapServers, topicAdmissibilityProcessorOutcome, null, errorMessage, "[ONBOARDING_REQUEST] An error occurred while publishing the onboarding evaluation result", TestUtils.jsonSerializer(expectedEvaluationFailingPublishing), null, false, false); - } - )); - } - - //errorUseCase 7 - { - String failingBudgetReservation = TestUtils.jsonSerializer( - buildOnboardingRequestCachedBuilder(errorUseCases.size()) - .initiativeId(INITIATIVEID_FAILING_BUDGET_RESERVATION) - .userId("userId_7_FAILING_BUDGET_RESERVATION") - .build() - ); - errorUseCases.add(Pair.of( - () -> { - Mockito.doReturn(Mono.error(new RuntimeException("DUMMYEXCEPTION"))).when(initiativeCountersRepositorySpy).reserveBudget(Mockito.eq(INITIATIVEID_FAILING_BUDGET_RESERVATION), Mockito.any()); - return failingBudgetReservation; - }, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_ONBOARDING_REQUEST] An error occurred handling onboarding request", failingBudgetReservation) - )); - } - - //errorUseCase 8 AUTOMATED_CRITERIA fail due to invalid request - { - String failingAnprInvalidRequestUserId = "userId_8_FAILING_ANPR_INVALID_REQUEST"; - String failingAnprInvalidRequest = TestUtils.jsonSerializer( - OnboardingDTOFaker.mockInstanceBuilder(errorUseCases.size(), INITIATIVEID_COMPLETE) - .userId(failingAnprInvalidRequestUserId) - .build() - ); - errorUseCases.add(Pair.of( - () -> { - userId2CFMocks.put(failingAnprInvalidRequestUserId, CF_INVALID_REQUEST); - - return failingAnprInvalidRequest; - }, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_ONBOARDING_REQUEST] An error occurred handling onboarding request", failingAnprInvalidRequest) - )); - } - - //errorUseCase 9: INPS unexpected result code - { - String failingInpsUnexpectedResultUserId = "userId_9_FAILING_INPS_UNEXPECTED_RESULT"; - String failingInpsUnexpectedResult = TestUtils.jsonSerializer( - OnboardingDTOFaker.mockInstanceBuilder(errorUseCases.size(), INITIATIVEID_COMPLETE) - .userId(failingInpsUnexpectedResultUserId) - .build() - ); - errorUseCases.add(Pair.of( - () -> { - userId2CFMocks.put(failingInpsUnexpectedResultUserId, CF_INPS_UNEXPECTED_RESULTCODE); - - return failingInpsUnexpectedResult; - }, - errorMessage -> checkErrorMessageHeaders(errorMessage, "[ADMISSIBILITY_ONBOARDING_REQUEST] An error occurred handling onboarding request", failingInpsUnexpectedResult) - )); - } - - } - - private EvaluationCompletedDTO retrieveEvaluationDTOErrorUseCase(OnboardingDTO onboardingDTO) { - Initiative2BuildDTO initiativeExceptionWhenOnboardingPublishing = Initiative2BuildDTOFaker.mockInstance(2); // COMPLETE_INITIATIVEID bias - return EvaluationCompletedDTO.builder() - .userId(onboardingDTO.getUserId()) - .initiativeId(onboardingDTO.getInitiativeId()) - .initiativeName("COMPLETE_INITIATIVE_NAME") - .initiativeEndDate(initiativeExceptionWhenOnboardingPublishing.getGeneral().getEndDate()) - .initiativeRewardType(initiativeExceptionWhenOnboardingPublishing.getInitiativeRewardType()) - .isLogoPresent(initiativeExceptionWhenOnboardingPublishing.getAdditionalInfo() != null && !StringUtils.isEmpty(initiativeExceptionWhenOnboardingPublishing.getAdditionalInfo().getLogoFileName())) - .organizationId(initiativeExceptionWhenOnboardingPublishing.getOrganizationId()) - .organizationName(initiativeExceptionWhenOnboardingPublishing.getOrganizationName()) - .status(OnboardingEvaluationStatus.ONBOARDING_OK) - .onboardingRejectionReasons(Collections.emptyList()) - .beneficiaryBudget(initiativeExceptionWhenOnboardingPublishing.getGeneral().getBeneficiaryBudget()) - .admissibilityCheckDate(LocalDateTime.now()) - .criteriaConsensusTimestamp(onboardingDTO.getCriteriaConsensusTimestamp()) - .build(); - } - - private void checkErrorMessageHeaders(ConsumerRecord errorMessage, String errorDescription, String expectedPayload) { - checkErrorMessageHeaders(serviceBusServers, topicAdmissibilityProcessorRequest, "", errorMessage, errorDescription, expectedPayload,null,true,true); - } - //endregion - - protected void checkPayload(String errorMessage, String expectedPayload) { - try { - EvaluationCompletedDTO actual = objectMapper.readValue(errorMessage, EvaluationCompletedDTO.class); - EvaluationCompletedDTO expected = objectMapper.readValue(expectedPayload, EvaluationCompletedDTO.class); - - TestUtils.checkNotNullFields(actual, "rankingValue", "familyId"); - Assertions.assertEquals(expected.getUserId(), actual.getUserId()); - Assertions.assertEquals(expected.getInitiativeId(), actual.getInitiativeId()); - Assertions.assertEquals(expected.getInitiativeName(), actual.getInitiativeName()); - Assertions.assertEquals(expected.getOrganizationId(),actual.getOrganizationId()); - Assertions.assertEquals(expected.getStatus(), actual.getStatus()); - Assertions.assertEquals(expected.getOnboardingRejectionReasons(), actual.getOnboardingRejectionReasons()); - Assertions.assertEquals(expected.getBeneficiaryBudget(), actual.getBeneficiaryBudget()); - Assertions.assertEquals(expected.getRankingValue(), actual.getRankingValue()); - } catch (JsonProcessingException e) { - Assertions.fail("Error check in payload"); - } - } -} \ No newline at end of file diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/BaseAdmissibilityProcessorConfigTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/BaseAdmissibilityProcessorConfigTest.java deleted file mode 100644 index 337dca8a..00000000 --- a/src/test/java/it/gov/pagopa/admissibility/connector/event/processor/BaseAdmissibilityProcessorConfigTest.java +++ /dev/null @@ -1,164 +0,0 @@ -package it.gov.pagopa.admissibility.connector.event.processor; - -import com.azure.spring.messaging.AzureHeaders; -import com.azure.spring.messaging.checkpoint.Checkpointer; -import it.gov.pagopa.admissibility.BaseIntegrationTest; -import it.gov.pagopa.admissibility.connector.repository.InitiativeCountersRepository; -import it.gov.pagopa.admissibility.dto.onboarding.EvaluationDTO; -import it.gov.pagopa.admissibility.dto.onboarding.OnboardingDTO; -import it.gov.pagopa.admissibility.service.onboarding.AdmissibilityEvaluatorMediatorService; -import it.gov.pagopa.admissibility.service.onboarding.AuthoritiesDataRetrieverService; -import it.gov.pagopa.admissibility.service.onboarding.OnboardingCheckService; -import it.gov.pagopa.admissibility.service.onboarding.OnboardingContextHolderService; -import it.gov.pagopa.admissibility.service.onboarding.evaluate.RuleEngineService; -import it.gov.pagopa.common.utils.TestUtils; -import jakarta.annotation.PostConstruct; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.regex.Pattern; -import java.util.stream.IntStream; -import lombok.extern.slf4j.Slf4j; -import org.apache.kafka.common.TopicPartition; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.mockito.Mockito; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.messaging.Message; -import org.springframework.messaging.support.MessageBuilder; -import org.springframework.test.context.TestPropertySource; -import reactor.core.Scannable; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -@Slf4j -@TestPropertySource(properties = { - "app.beneficiary-rule.build-delay-duration=PT1S", - "logging.level.it.gov.pagopa.admissibility.service.build=WARN", - "logging.level.it.gov.pagopa.admissibility.service.onboarding=WARN", - "logging.level.it.gov.pagopa.admissibility.service.onboarding.AdmissibilityEvaluatorMediatorServiceImpl=WARN", - "logging.level.it.gov.pagopa.common.reactive.kafka.consumer.BaseKafkaConsumer=WARN", - "logging.level.it.gov.pagopa.common.reactive.utils.PerformanceLogger=WARN", - "logging.level.it.gov.pagopa.common.reactive.pdv.service.UserFiscalCodeRestClientImpl=WARN", -}) -abstract class BaseAdmissibilityProcessorConfigTest extends BaseIntegrationTest { - - @BeforeAll - static void configureWireMock() { - //Disabling Client SSL auth: ANPR and INPS are configured to use HTTPS protocol - BaseIntegrationTest.configureServerWiremockBeforeAll(false, true); - } - - @SpyBean - protected OnboardingContextHolderService onboardingContextHolderServiceSpy; - @SpyBean - protected OnboardingCheckService onboardingCheckServiceSpy; - @SpyBean - protected AuthoritiesDataRetrieverService authoritiesDataRetrieverServiceSpy; - @SpyBean - protected RuleEngineService ruleEngineServiceSpy; - @SpyBean - protected InitiativeCountersRepository initiativeCountersRepositorySpy; - - protected static List checkpointers; - - static class MediatorSpyConfiguration { - @SpyBean - private AdmissibilityEvaluatorMediatorService admissibilityEvaluatorMediatorServiceSpy; - - @PostConstruct - void init() { - checkpointers = configureSpies(); - } - - private List configureSpies(){ - List checkpoints = Collections.synchronizedList(new ArrayList<>(1100)); - - Mockito.doAnswer(args-> { - Flux> messageFlux = args.getArgument(0); - messageFlux = messageFlux.map(m -> { - Checkpointer mock = Mockito.mock(Checkpointer.class); - Mockito.when(mock.success()).thenReturn(Mono.empty()); - checkpoints.add(mock); - return MessageBuilder.withPayload(m.getPayload()) - .copyHeaders(m.getHeaders()) - .setHeader(AzureHeaders.CHECKPOINTER, mock) - .build(); - } - ) - .name("spy"); - admissibilityEvaluatorMediatorServiceSpy.execute(messageFlux); - return null; - }) - .when(admissibilityEvaluatorMediatorServiceSpy).execute(Mockito.argThat(a -> !Scannable.from(a).name().equals("spy"))); - - return checkpoints; - } - } - - public record OnboardingUseCase ( - Function> useCaseMessageBuilder, - Consumer useCaseVerifier) { - - public static OnboardingUseCase withJustPayload(Function useCaseBuilder, Consumer useCaseVerifier){ - return new OnboardingUseCase<>( - bias -> MessageBuilder.withPayload(useCaseBuilder.apply(bias)).build(), - useCaseVerifier); - } - } - - protected List> buildValidPayloads(int bias, int validOnboardings,List> useCases) { - return IntStream.range(bias, bias + validOnboardings) - .mapToObj(i -> this.mockInstance(i,useCases)) - .map(m->MessageBuilder.withPayload(TestUtils.jsonSerializer(m.getPayload())).copyHeaders(m.getHeaders()).build()) - .toList(); - } - - protected Message mockInstance(int bias, List> useCases) { - return useCases.get(bias % useCases.size()).useCaseMessageBuilder().apply(bias); - } - - protected void checkResponse(T evaluation, List> useCases) { - String userId = evaluation.getUserId(); - int biasRetrieve = Integer.parseInt(userId.substring(userId.indexOf("userId_") + 7)); - int useCaseIndex = biasRetrieve % useCases.size(); - try { - useCases.get(useCaseIndex).useCaseVerifier().accept(evaluation); - } catch (Throwable e) { - System.err.printf("Failed use case %d on user %s initiativeId %s%n", - useCaseIndex, - userId, - evaluation.getInitiativeId()); - throw e; - } - } - - @Override - protected Pattern getErrorUseCaseIdPatternMatch() { - return Pattern.compile("\"userId\":\"userId_([0-9]+)_?[^\"]*\""); - } - - protected void checkOffsets(long expectedReadMessages, long exptectedPublishedResults, String outputTopic) { - Assertions.assertEquals(expectedReadMessages, checkpointers.size()); - checkpointers.forEach(checkpointer -> Mockito.verify(checkpointer).success()); - - long timeCommitChecked = System.currentTimeMillis(); - final Map destPublishedOffsets = kafkaTestUtilitiesService.checkPublishedOffsets(outputTopic, exptectedPublishedResults); - long timePublishChecked = System.currentTimeMillis(); - System.out.printf(""" - ************************ - Time occurred to check published offset: %d millis - ************************ - Source Topic Committed Offsets: %s - Dest Topic Published Offsets: %s - ************************ - """, - timePublishChecked - timeCommitChecked, - expectedReadMessages, - destPublishedOffsets - ); - } -} \ No newline at end of file diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java deleted file mode 100644 index e51405e0..00000000 --- a/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package it.gov.pagopa.admissibility.connector.rest.mock; - -import com.github.tomakehurst.wiremock.WireMockServer; -import it.gov.pagopa.admissibility.dto.onboarding.extra.Family; -import it.gov.pagopa.common.reactive.rest.config.WebClientConfig; -import lombok.extern.slf4j.Slf4j; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import reactor.core.Exceptions; - -@ExtendWith(SpringExtension.class) -@AutoConfigureWireMock(stubs ="classpath:/stub/mappings/mock" ,port =800) -@ContextConfiguration( - classes = { - FamilyMockRestClientImpl.class, - WebClientConfig.class, - WireMockServer.class - }) -@TestPropertySource( - locations = "classpath:application.yml", - properties = {"spring.application.name=idpay-admissibility-assessor", - "app.idpay-mock.base-url=http://localhost:${wiremock.server.port}/pdndMock", - //Region familyMockRestClient - "app.idpay-mock.retry.delay-millis=1", - "app.idpay-mock.retry.max-attempts=5", - //endRegion - - //Region webClientConfig - "app.web-client.connect.timeout.millis=10000", - "app.web-client.response.timeout=60000", - "app.web-client.read.handler.timeout=60000", - "app.web-client.write.handler.timeout=60000" - //endRegion - }) -@Slf4j -class FamilyMockRestClientImplTest { - @Autowired - private FamilyMockRestClientImpl familyMockRestClient; - @Autowired - private WireMockServer wireMockServer; - - @Test - void givenUserIdWhenCallFamilyMockRestClientThenFamily() { - - Family family = familyMockRestClient.retrieveFamily("userId_1").block(); - Assertions.assertEquals(3,family.getMemberIds().size()); - } - - @Test - void givenUserIdWhenCallFamilyMockRestClientThenTooManyRequestException(){ - try{ - familyMockRestClient.retrieveFamily("USERID_TOOMANYREQUEST_1").block(); - Assertions.fail(); - }catch (Throwable e){ - Assertions.assertTrue(Exceptions.isRetryExhausted(e)); - } - } -} diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestDeprecated.java b/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestDeprecated.java deleted file mode 100644 index 7acb5035..00000000 --- a/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestDeprecated.java +++ /dev/null @@ -1,34 +0,0 @@ -package it.gov.pagopa.admissibility.connector.rest.mock; - -import it.gov.pagopa.admissibility.BaseIntegrationTest; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.TestPropertySource; -import reactor.core.Exceptions; - -@TestPropertySource(properties = { - "logging.level.it.gov.pagopa.admissibility.rest.mock.FamilyMockRestClientImpl=WARN", - "app.idpay-mock.retry.max-attempts=1", - "app.idpay-mock.retry.delay-millis=100" -}) -@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) -class FamilyMockRestClientImplTestDeprecated extends BaseIntegrationTest { - - - @Autowired - private FamilyMockRestClient familyMockRestClient; - - - @Test - void retrieveFamilyTooManyRequest() { - String userId = "USERID_TOOMANYREQUEST_1"; - - try{ - familyMockRestClient.retrieveFamily(userId).block(); - Assertions.fail(); - }catch (Throwable e){ - Assertions.assertTrue(Exceptions.isRetryExhausted(e)); - } - } -} \ No newline at end of file diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplTestIntegrated.java b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplTestIntegrated.java deleted file mode 100644 index 1dcde10e..00000000 --- a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplTestIntegrated.java +++ /dev/null @@ -1,32 +0,0 @@ -package it.gov.pagopa.admissibility.connector.soap.inps.service; - -import it.gov.pagopa.admissibility.BaseIntegrationTest; -import it.gov.pagopa.admissibility.generated.soap.ws.client.ConsultazioneIndicatoreResponseType; -import it.gov.pagopa.admissibility.model.IseeTypologyEnum; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; - -/** - * See confluence page: Secrets for UnitTests - */ -@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) // suppressing class name not match alert: we are not using the Test suffix in order to let not execute this test by default maven configuration because it depends on properties not pushable. See -@TestPropertySource(properties = { - "logging.level.it.gov.pagopa.common.soap.service.SoapLoggingHandler=DEBUG", - "app.inps.iseeConsultation.base-url=https://dev01.idpay.internal.dev.cstar.pagopa.it/idpaymock/idpay/mock/inps/soap/ConsultazioneISEE" //Temporary calling Mocked APIM -}) -@ContextConfiguration(inheritInitializers = false) -class IseeConsultationSoapClientImplTestIntegrated extends BaseIntegrationTest { - - @SpyBean - private IseeConsultationSoapClient iseeConsultationSoapClient; - - @Test - void callService() { - ConsultazioneIndicatoreResponseType result = iseeConsultationSoapClient.getIsee("CF_OK", IseeTypologyEnum.ORDINARIO).block(); - Assertions.assertNotNull(result); - System.out.println(result.getEsito()); - } -} diff --git a/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodeServiceIntegrationTestDeprecated.java b/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodeServiceIntegrationTestDeprecated.java deleted file mode 100644 index 4442d282..00000000 --- a/src/test/java/it/gov/pagopa/admissibility/service/CriteriaCodeServiceIntegrationTestDeprecated.java +++ /dev/null @@ -1,34 +0,0 @@ -package it.gov.pagopa.admissibility.service; - -import it.gov.pagopa.admissibility.BaseIntegrationTest; -import it.gov.pagopa.admissibility.config.CriteriaCodesConfiguration; -import it.gov.pagopa.admissibility.model.CriteriaCodeConfig; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.TestPropertySource; - -import java.util.Map; - -@TestPropertySource(properties = { - "logging.level.it.gov.pagopa.admissibility.service.CriteriaCodeServiceImpl=WARN", -}) -@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) -class CriteriaCodeServiceIntegrationTestDeprecated extends BaseIntegrationTest { - @Autowired - private CriteriaCodesConfiguration criteriaCodesConfiguration; - - @Test - void test(){ - Map result = criteriaCodesConfiguration.getCriteriaCodeConfigs(); - - Map expected = Map.of( - "ISEE", new CriteriaCodeConfig("ISEE", "INPS", "Istituto Nazionale Previdenza Sociale", "isee"), - "BIRTHDATE", new CriteriaCodeConfig("BIRTHDATE", "AGID", "Agenzia per l'Italia Digitale", "birthDate"), - "RESIDENCE", new CriteriaCodeConfig("RESIDENCE", "AGID","Agenzia per l'Italia Digitale", "residence"), - "FAMILY", new CriteriaCodeConfig("FAMILY", "INPS","Istituto Nazionale Previdenza Sociale", "family") - ); - - Assertions.assertEquals(expected, result); - } -} diff --git a/src/test/java/it/gov/pagopa/admissibility/service/onboarding/OnboardingContextHolderServiceIntegrationTestDeprecated.java b/src/test/java/it/gov/pagopa/admissibility/service/onboarding/OnboardingContextHolderServiceIntegrationTestDeprecated.java deleted file mode 100644 index 3e01adfb..00000000 --- a/src/test/java/it/gov/pagopa/admissibility/service/onboarding/OnboardingContextHolderServiceIntegrationTestDeprecated.java +++ /dev/null @@ -1,188 +0,0 @@ -package it.gov.pagopa.admissibility.service.onboarding; - -import it.gov.pagopa.admissibility.BaseIntegrationTest; -import it.gov.pagopa.admissibility.dto.onboarding.*; -import it.gov.pagopa.admissibility.dto.rule.AutomatedCriteriaDTO; -import it.gov.pagopa.admissibility.model.DroolsRule; -import it.gov.pagopa.admissibility.model.InitiativeConfig; -import it.gov.pagopa.admissibility.service.build.KieContainerBuilderService; -import it.gov.pagopa.admissibility.service.build.KieContainerBuilderServiceImpl; -import it.gov.pagopa.admissibility.service.onboarding.evaluate.RuleEngineService; -import it.gov.pagopa.admissibility.test.fakers.OnboardingDTOFaker; -import it.gov.pagopa.common.redis.config.EmbeddedRedisTestConfiguration; -import it.gov.pagopa.common.utils.TestUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.kie.api.KieBase; -import org.kie.api.definition.KiePackage; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.ReactiveRedisTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.util.ReflectionUtils; -import reactor.core.publisher.Flux; - -import java.lang.reflect.Field; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.util.Collections; -import java.util.List; - -@TestPropertySource( - properties = { - "spring.redis.enabled=true", - } -) -@ContextConfiguration(classes = EmbeddedRedisTestConfiguration.class) -@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) -class OnboardingContextHolderServiceIntegrationTestDeprecated extends BaseIntegrationTest { - @Autowired - private KieContainerBuilderService kieContainerBuilderService; - @Autowired - private ReactiveRedisTemplate reactiveRedisTemplate; - @Autowired - private OnboardingContextHolderServiceImpl onboardingContextHolderService; - @Autowired - private RuleEngineService ruleEngineService; - - @Test - void testKieBuildWithRedisCache() { - - // Assert the starting built rule size is 0 - int startingRuleBuiltSize = getRuleBuiltSize(onboardingContextHolderService); - - Assertions.assertEquals(0, startingRuleBuiltSize); - - // Caching invalid rules - reactiveRedisTemplate.opsForValue().set(OnboardingContextHolderServiceImpl.ONBOARDING_CONTEXT_HOLDER_CACHE_NAME, "INVALIDOBJECT".getBytes()).block(); - refreshAndAssertKieContainerRuleSize(0); - - // Build a valid KieBase that produces a rule of size 1, assert KieBase is null after Reflection - List expectedRejectionReason = - Collections.singletonList( - OnboardingRejectionReason.builder() - .type(OnboardingRejectionReason.OnboardingRejectionReasonType.valueOf("INVALID_REQUEST")) - .code("OK") - .build() - ); - - DroolsRule dr = new DroolsRule(); - dr.setId("NAME"); - dr.setName("INITIATIVEID"); - dr.setRule(""" - package %s; - - rule "%s" - agenda-group "%s" - when $onb: %s() - then $onb.getOnboardingRejectionReasons().add(it.gov.pagopa.admissibility.dto.onboarding.OnboardingRejectionReason.builder().type(it.gov.pagopa.admissibility.dto.onboarding.OnboardingRejectionReason.OnboardingRejectionReasonType.valueOf("INVALID_REQUEST")).code("OK").build()); - end - """.formatted( - KieContainerBuilderServiceImpl.RULES_BUILT_PACKAGE, - dr.getRule(), - dr.getName(), - OnboardingDroolsDTO.class.getName() - ) - ); - - KieBase kieBase = kieContainerBuilderService.build(Flux.just(dr)).block(); - onboardingContextHolderService.setBeneficiaryRulesKieBase(kieBase); - TestUtils.waitFor( - ()->(reactiveRedisTemplate.opsForValue().get(OnboardingContextHolderServiceImpl.ONBOARDING_CONTEXT_HOLDER_CACHE_NAME).block()) != null, - ()->"KieBase not saved in cache", - 10, - 500 - ); - - setContextHolderFieldToNull("kieBase"); - setContextHolderFieldToNull("kieBaseSerialized"); - - Assertions.assertNull(onboardingContextHolderService.getBeneficiaryRulesKieBase()); - - // Refresh KieBase and assert the built rules have expected size - refreshAndAssertKieContainerRuleSize(1); - - // Execute rule and assert onboarding has the expected rejection reason - OnboardingDTO onboardingMock = OnboardingDTOFaker.mockInstance(1, "INITIATIVEID"); - EvaluationDTO result = executeRules(onboardingMock); - - Assertions.assertNotNull(result); - Assertions.assertInstanceOf(EvaluationCompletedDTO.class, result); - - EvaluationCompletedDTO resultCompleted = (EvaluationCompletedDTO) result; - Assertions.assertEquals(expectedRejectionReason, resultCompleted.getOnboardingRejectionReasons()); - - // Set a null kieBase - onboardingContextHolderService.setBeneficiaryRulesKieBase(null); - TestUtils.waitFor( - ()->(reactiveRedisTemplate.opsForValue().get(OnboardingContextHolderServiceImpl.ONBOARDING_CONTEXT_HOLDER_CACHE_NAME).block()) == null, - ()->"KieBase not saved in cache", - 10, - 500 - ); - - onboardingContextHolderService.refreshKieContainer(); - TestUtils.waitFor( - ()-> (reactiveRedisTemplate.opsForValue().get(OnboardingContextHolderServiceImpl.ONBOARDING_CONTEXT_HOLDER_CACHE_NAME).block()) != null, - ()-> "KieBase is null", - 10, - 500 - ); - - KieBase resultKieBase = onboardingContextHolderService.getBeneficiaryRulesKieBase(); - Assertions.assertNotNull(resultKieBase); - - int resultRuleBuiltSize = getRuleBuiltSize(onboardingContextHolderService); - Assertions.assertEquals(0, resultRuleBuiltSize); - } - - private void refreshAndAssertKieContainerRuleSize(int expectedRuleSize) { - onboardingContextHolderService.refreshKieContainer(); - TestUtils.waitFor( - ()-> onboardingContextHolderService.getBeneficiaryRulesKieBase() != null, - ()->"KieBase is null", - 10, - 500 - ); - - int ruleBuiltSize = getRuleBuiltSize(onboardingContextHolderService); - Assertions.assertEquals(expectedRuleSize, ruleBuiltSize); - } - - private void setContextHolderFieldToNull(String fieldName) { - Field field = ReflectionUtils.findField(OnboardingContextHolderServiceImpl.class, fieldName); - Assertions.assertNotNull(field); - ReflectionUtils.makeAccessible(field); - ReflectionUtils.setField(field, onboardingContextHolderService, null); - } - - private EvaluationDTO executeRules(OnboardingDTO onb) { - - InitiativeConfig config = InitiativeConfig.builder() - .initiativeId(onb.getInitiativeId()) - .beneficiaryInitiativeBudget(BigDecimal.valueOf(100)) - .endDate(LocalDate.MAX) - .initiativeName("NAME") - .initiativeBudget(BigDecimal.valueOf(100)) - .status("STATUS") - .automatedCriteriaCodes(List.of("CODE1")) - .organizationId("ORGANIZATION-ID") - .startDate(LocalDate.MIN) - .automatedCriteria(List.of(new AutomatedCriteriaDTO())) - .build(); - - return ruleEngineService.applyRules(onb, config); - } - - public static int getRuleBuiltSize(OnboardingContextHolderService onboardingContextHolderServiceSpy) { - KieBase kieBase = onboardingContextHolderServiceSpy.getBeneficiaryRulesKieBase(); - if (kieBase == null) { - return 0; - } else { - KiePackage kiePackage = kieBase.getKiePackage(KieContainerBuilderServiceImpl.RULES_BUILT_PACKAGE); - return kiePackage != null - ? kiePackage.getRules().size() - : 0; - } - } -} From 19d839867cadf6766a8e1d2d2ae42627bc1f53d1 Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Tue, 27 Feb 2024 18:12:00 +0100 Subject: [PATCH 06/16] IDP-2293 added common wiremock and embeddedMongo configuration and updated tests --- ...equenceGeneratorOpsRepositoryImplTest.java | 16 +- ...ntersReservationOpsRepositoryImplTest.java | 14 +- .../OnboardingFamiliesRepositoryTest.java | 13 +- .../FamilyMockRestClientImplTestBase.java | 39 +++++ ...ltationSoapClientImplIntegrationTest.java} | 28 ++-- .../reactive/mongo/BaseMongoEmbeddedTest.java | 23 +++ .../reactive/wireMock/BaseWireMockTest.java | 143 ++++++++++++++++++ 7 files changed, 258 insertions(+), 18 deletions(-) create mode 100644 src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestBase.java rename src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/{IseeConsultationSoapClientImplIntegrationTestDeprecated.java => IseeConsultationSoapClientImplIntegrationTest.java} (83%) create mode 100644 src/test/java/it/gov/pagopa/common/reactive/mongo/BaseMongoEmbeddedTest.java create mode 100644 src/test/java/it/gov/pagopa/common/reactive/wireMock/BaseWireMockTest.java diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/repository/CustomSequenceGeneratorOpsRepositoryImplTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/repository/CustomSequenceGeneratorOpsRepositoryImplTest.java index 8072c559..5d5d8bf7 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/repository/CustomSequenceGeneratorOpsRepositoryImplTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/repository/CustomSequenceGeneratorOpsRepositoryImplTest.java @@ -1,13 +1,25 @@ package it.gov.pagopa.admissibility.connector.repository; -import it.gov.pagopa.admissibility.BaseIntegrationTest; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import it.gov.pagopa.admissibility.model.CustomSequenceGenerator; +import it.gov.pagopa.common.mongo.MongoTestUtilitiesService; +import it.gov.pagopa.common.reactive.mongo.BaseMongoEmbeddedTest; +import it.gov.pagopa.common.reactive.mongo.config.ReactiveMongoConfig; +import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; -class CustomSequenceGeneratorOpsRepositoryImplTest extends BaseIntegrationTest { + +@ContextConfiguration(classes = { + CustomSequenceGeneratorRepository.class, + ReactiveMongoConfig.class, + MongoTestUtilitiesService.TestMongoConfiguration.class, + SimpleMeterRegistry.class}) +@Slf4j +class CustomSequenceGeneratorOpsRepositoryImplTest extends BaseMongoEmbeddedTest { @Autowired protected CustomSequenceGeneratorRepository customSequenceGeneratorRepository; diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/repository/InitiativeCountersReservationOpsRepositoryImplTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/repository/InitiativeCountersReservationOpsRepositoryImplTest.java index ec96a8b8..7f343dbd 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/repository/InitiativeCountersReservationOpsRepositoryImplTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/repository/InitiativeCountersReservationOpsRepositoryImplTest.java @@ -1,10 +1,14 @@ package it.gov.pagopa.admissibility.connector.repository; -import it.gov.pagopa.admissibility.BaseIntegrationTest; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import it.gov.pagopa.admissibility.model.InitiativeCounters; +import it.gov.pagopa.common.mongo.MongoTestUtilitiesService; +import it.gov.pagopa.common.reactive.mongo.BaseMongoEmbeddedTest; +import it.gov.pagopa.common.reactive.mongo.config.ReactiveMongoConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; import java.math.BigDecimal; import java.util.List; @@ -14,7 +18,13 @@ import java.util.concurrent.Future; import java.util.stream.IntStream; -class InitiativeCountersReservationOpsRepositoryImplTest extends BaseIntegrationTest { +@ContextConfiguration(classes = { + InitiativeCountersReservationOpsRepositoryImpl.class, + InitiativeCountersRepository.class, + ReactiveMongoConfig.class, + MongoTestUtilitiesService.TestMongoConfiguration.class, + SimpleMeterRegistry.class}) +class InitiativeCountersReservationOpsRepositoryImplTest extends BaseMongoEmbeddedTest { @Autowired protected InitiativeCountersRepository initiativeCountersRepository; diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/repository/OnboardingFamiliesRepositoryTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/repository/OnboardingFamiliesRepositoryTest.java index 5137f471..a43ec8c9 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/repository/OnboardingFamiliesRepositoryTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/repository/OnboardingFamiliesRepositoryTest.java @@ -1,15 +1,19 @@ package it.gov.pagopa.admissibility.connector.repository; import com.mongodb.client.result.UpdateResult; -import it.gov.pagopa.admissibility.BaseIntegrationTest; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import it.gov.pagopa.admissibility.dto.onboarding.OnboardingRejectionReason; import it.gov.pagopa.admissibility.dto.onboarding.extra.Family; import it.gov.pagopa.admissibility.enums.OnboardingFamilyEvaluationStatus; import it.gov.pagopa.admissibility.model.OnboardingFamilies; +import it.gov.pagopa.common.mongo.MongoTestUtilitiesService; +import it.gov.pagopa.common.reactive.mongo.BaseMongoEmbeddedTest; +import it.gov.pagopa.common.reactive.mongo.config.ReactiveMongoConfig; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; @@ -18,7 +22,12 @@ import java.util.List; import java.util.Set; -class OnboardingFamiliesRepositoryTest extends BaseIntegrationTest { +@ContextConfiguration(classes = { + OnboardingFamiliesRepositoryTest.class, + ReactiveMongoConfig.class, + MongoTestUtilitiesService.TestMongoConfiguration.class, + SimpleMeterRegistry.class}) +class OnboardingFamiliesRepositoryTest extends BaseMongoEmbeddedTest { @Autowired private OnboardingFamiliesRepository repository; diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestBase.java b/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestBase.java new file mode 100644 index 00000000..1854786c --- /dev/null +++ b/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestBase.java @@ -0,0 +1,39 @@ +package it.gov.pagopa.admissibility.connector.rest.mock; + +import it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest; +import it.gov.pagopa.admissibility.dto.onboarding.extra.Family; +import it.gov.pagopa.common.reactive.rest.config.WebClientConfig; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import reactor.core.Exceptions; + + +@ContextConfiguration( + classes = { + FamilyMockRestClientImpl.class, + WebClientConfig.class + }) +class FamilyMockRestClientImplTest extends BaseWireMockTest { + + @Autowired + private FamilyMockRestClientImpl familyMockRestClient; + + @Test + void givenUserIdWhenCallFamilyMockRestClientThenFamily() { + + Family family = familyMockRestClient.retrieveFamily("userId_1").block(); + Assertions.assertEquals(3,family.getMemberIds().size()); + } + + @Test + void givenUserIdWhenCallFamilyMockRestClientThenTooManyRequestException(){ + try{ + familyMockRestClient.retrieveFamily("USERID_TOOMANYREQUEST_1").block(); + Assertions.fail(); + }catch (Throwable e){ + Assertions.assertTrue(Exceptions.isRetryExhausted(e)); + } + } +} diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTestDeprecated.java b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTest.java similarity index 83% rename from src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTestDeprecated.java rename to src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTest.java index 3fe2dc20..3f2db642 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTestDeprecated.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTest.java @@ -1,27 +1,31 @@ package it.gov.pagopa.admissibility.connector.soap.inps.service; -import it.gov.pagopa.admissibility.BaseIntegrationTest; +import it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest; +import it.gov.pagopa.admissibility.connector.soap.inps.config.InpsClientConfig; import it.gov.pagopa.admissibility.connector.soap.inps.exception.InpsDailyRequestLimitException; import it.gov.pagopa.admissibility.generated.soap.ws.client.ConsultazioneIndicatoreResponseType; import it.gov.pagopa.admissibility.generated.soap.ws.client.EsitoEnum; import it.gov.pagopa.admissibility.generated.soap.ws.client.TypeEsitoConsultazioneIndicatore; import it.gov.pagopa.admissibility.model.IseeTypologyEnum; +import it.gov.pagopa.common.reactive.rest.config.WebClientConfig; +import it.gov.pagopa.common.soap.service.SoapLoggingHandler; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.TestPropertySource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; import reactor.core.publisher.Mono; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; -@TestPropertySource(properties = { - "logging.level.it.gov.pagopa.common.soap.service.SoapLoggingHandler=DEBUG" -}) -@DirtiesContext -@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) -public class IseeConsultationSoapClientImplIntegrationTestDeprecated extends BaseIntegrationTest { +@ContextConfiguration( + classes = { + IseeConsultationSoapClientImpl.class, + InpsClientConfig.class, + SoapLoggingHandler.class, + WebClientConfig.class + }) +public class IseeConsultationSoapClientImplIntegrationTest extends BaseWireMockTest { public static final String FISCAL_CODE_OK = "CF_OK"; public static final String FISCAL_CODE_NOTFOUND = "CF_NOT_FOUND"; @@ -31,8 +35,8 @@ public class IseeConsultationSoapClientImplIntegrationTestDeprecated extends Bas public static final String FISCAL_CODE_FAULT_MESSAGE = "CF_INPS_FAULT_MESSAGE"; public static final String FISCAL_CODE_TOOMANYREQUESTS = "CF_INPS_TOO_MANY_REQUESTS"; - @SpyBean - private IseeConsultationSoapClient iseeConsultationSoapClient; + @Autowired + private IseeConsultationSoapClientImpl iseeConsultationSoapClient; @Test void callService() { diff --git a/src/test/java/it/gov/pagopa/common/reactive/mongo/BaseMongoEmbeddedTest.java b/src/test/java/it/gov/pagopa/common/reactive/mongo/BaseMongoEmbeddedTest.java new file mode 100644 index 00000000..0fb84bc8 --- /dev/null +++ b/src/test/java/it/gov/pagopa/common/reactive/mongo/BaseMongoEmbeddedTest.java @@ -0,0 +1,23 @@ +package it.gov.pagopa.common.reactive.mongo; + +import it.gov.pagopa.common.mongo.singleinstance.AutoConfigureSingleInstanceMongodb; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@TestPropertySource(properties = { + "de.flapdoodle.mongodb.embedded.version=4.2.24", + + "spring.data.mongodb.database=idpay", + "spring.data.mongodb.config.connectionPool.maxSize: 100", + "spring.data.mongodb.config.connectionPool.minSize: 0", + "spring.data.mongodb.config.connectionPool.maxWaitTimeMS: 120000", + "spring.data.mongodb.config.connectionPool.maxConnectionLifeTimeMS: 0", + "spring.data.mongodb.config.connectionPool.maxConnectionIdleTimeMS: 120000", + "spring.data.mongodb.config.connectionPool.maxConnecting: 2", +}) +@ExtendWith(SpringExtension.class) +@AutoConfigureSingleInstanceMongodb +@SuppressWarnings("squid:S2187") +public class BaseMongoEmbeddedTest { +} diff --git a/src/test/java/it/gov/pagopa/common/reactive/wireMock/BaseWireMockTest.java b/src/test/java/it/gov/pagopa/common/reactive/wireMock/BaseWireMockTest.java new file mode 100644 index 00000000..eab61436 --- /dev/null +++ b/src/test/java/it/gov/pagopa/common/reactive/wireMock/BaseWireMockTest.java @@ -0,0 +1,143 @@ +package it.gov.pagopa.common.reactive.wireMock; + +import it.gov.pagopa.common.rest.utils.WireMockUtils; +import it.gov.pagopa.common.utils.JUnitExtensionContextHolder; +import it.gov.pagopa.common.utils.TestUtils; +import jakarta.annotation.PostConstruct; +import lombok.NonNull; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.data.util.Pair; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.support.TestPropertySourceUtils; + +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +@ExtendWith(JUnitExtensionContextHolder.class) +@SpringBootTest +@ContextConfiguration(initializers = {BaseWireMockTest.WireMockInitializer.class}) +@SuppressWarnings("squid:S2187") +public class BaseWireMockTest { + + @PostConstruct + public void logEmbeddedServerConfig() { + String wiremockHttpBaseUrl = "UNKNOWN"; + String wiremockHttpsBaseUrl = "UNKNOWN"; + try { + wiremockHttpBaseUrl = serverWireMockExtension.getRuntimeInfo().getHttpBaseUrl(); + wiremockHttpsBaseUrl = serverWireMockExtension.getRuntimeInfo().getHttpsBaseUrl(); + } catch (Exception e) { + System.out.println("Cannot read wiremock urls"); + } + System.out.printf(""" + ************************ + WireMock http: %s + WireMock https: %s + ************************ + """, + wiremockHttpBaseUrl, + wiremockHttpsBaseUrl); + } + + //region desc=Setting WireMock + private static boolean WIREMOCK_REQUEST_CLIENT_AUTH = true; + private static boolean USE_TRUSTORE_OK = true; + public static final String TRUSTSTORE_PATH = "src/test/resources/wiremockKeyStore.p12"; + private static final String TRUSTSTORE_KO_PATH = "src/test/resources/wiremockTrustStoreKO.p12"; + @RegisterExtension + static com.github.tomakehurst.wiremock.junit5.WireMockExtension serverWireMockExtension = initServerWiremock(); + + public static void configureServerWiremockBeforeAll(boolean needClientAuth, boolean useTrustoreOk) { + WIREMOCK_REQUEST_CLIENT_AUTH = needClientAuth; + USE_TRUSTORE_OK = useTrustoreOk; + initServerWiremock(); + } + + private static com.github.tomakehurst.wiremock.junit5.WireMockExtension initServerWiremock() { + int httpPort=0; + int httpsPort=0; + boolean start=false; + + // re-using shutdown server port in order to let Spring loaded configuration still valid + if (serverWireMockExtension != null && JUnitExtensionContextHolder.extensionContext != null) { + try { + httpPort = serverWireMockExtension.getRuntimeInfo().getHttpPort(); + httpsPort = serverWireMockExtension.getRuntimeInfo().getHttpsPort(); + + serverWireMockExtension.shutdownServer(); + // waiting server stop, releasing ports + TestUtils.wait(200, TimeUnit.MILLISECONDS); + start=true; + } catch (IllegalStateException e){ + // Do Nothing: the wiremock server was not started + } + } + + com.github.tomakehurst.wiremock.junit5.WireMockExtension newWireMockConfig = WireMockUtils.initServerWiremock( + httpPort, + httpsPort, + "src/test/resources/stub", + WIREMOCK_REQUEST_CLIENT_AUTH, + USE_TRUSTORE_OK ? TRUSTSTORE_PATH : TRUSTSTORE_KO_PATH, + "idpay"); + + if(start){ + try { + newWireMockConfig.beforeAll(JUnitExtensionContextHolder.extensionContext); + } catch (Exception e) { + throw new IllegalStateException("Cannot start WireMock JUnit Extension", e); + } + } + + return serverWireMockExtension = newWireMockConfig; + } + + @AfterAll + static void restoreWireMockConfig() { + if(!USE_TRUSTORE_OK || !WIREMOCK_REQUEST_CLIENT_AUTH) { + USE_TRUSTORE_OK = true; + WIREMOCK_REQUEST_CLIENT_AUTH = true; + initServerWiremock(); + } + } + + public static class WireMockInitializer implements ApplicationContextInitializer { + @Override + public void initialize(@NonNull ConfigurableApplicationContext applicationContext) { + // setting wiremock HTTP baseUrl + Stream.of( + Pair.of("app.pdv.base-url", "pdv"), + Pair.of("app.pdnd.base-url", "pdnd"), + Pair.of("app.idpay-mock.base-url", "pdndMock") + ).forEach(setWireMockBaseMockedServicePath(applicationContext, serverWireMockExtension.getRuntimeInfo().getHttpBaseUrl())); + + // setting wiremock HTTPS baseUrl + Stream.of( + Pair.of("app.anpr.config.base-url", "anpr/"), + Pair.of("app.inps.iseeConsultation.base-url", "inps/isee") + ).forEach(setWireMockBaseMockedServicePath(applicationContext, serverWireMockExtension.getRuntimeInfo().getHttpsBaseUrl())); + + System.out.printf(""" + ************************ + Server wiremock: + http base url: %s + https base url: %s + ************************ + """, + serverWireMockExtension.getRuntimeInfo().getHttpBaseUrl(), + serverWireMockExtension.getRuntimeInfo().getHttpsBaseUrl()); + } + + private static java.util.function.Consumer> setWireMockBaseMockedServicePath(ConfigurableApplicationContext applicationContext, String serverWireMock) { + return key2basePath -> TestPropertySourceUtils.addInlinedPropertiesToEnvironment(applicationContext, + String.format("%s=%s/%s", key2basePath.getFirst(), serverWireMock, key2basePath.getSecond()) + ); + + } + } +//endregion +} From 967f9899907995a41f20395646226e7016d11d1d Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Wed, 28 Feb 2024 17:59:50 +0100 Subject: [PATCH 07/16] IDP-2293 updated common classes repository and wiremock tests --- ...equenceGeneratorOpsRepositoryImplTest.java | 14 ++--- ...ntersReservationOpsRepositoryImplTest.java | 15 ++---- .../OnboardingFamiliesRepositoryTest.java | 14 ++--- ...java => FamilyMockRestClientImplTest.java} | 8 +++ ...eeConsultationSoapClientImplSSLKOTest.java | 8 +-- ...> IseeConsultationSoapClientImplTest.java} | 12 ++++- .../it/gov/pagopa/common/mongo/MongoTest.java | 54 +++++++++++++++++++ .../reactive/mongo/BaseMongoEmbeddedTest.java | 23 -------- .../reactive/wireMock/BaseWireMockTest.java | 53 +++++++++++------- 9 files changed, 118 insertions(+), 83 deletions(-) rename src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/{FamilyMockRestClientImplTestBase.java => FamilyMockRestClientImplTest.java} (80%) rename src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/{IseeConsultationSoapClientImplIntegrationTest.java => IseeConsultationSoapClientImplTest.java} (91%) create mode 100644 src/test/java/it/gov/pagopa/common/mongo/MongoTest.java delete mode 100644 src/test/java/it/gov/pagopa/common/reactive/mongo/BaseMongoEmbeddedTest.java diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/repository/CustomSequenceGeneratorOpsRepositoryImplTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/repository/CustomSequenceGeneratorOpsRepositoryImplTest.java index 5d5d8bf7..1a1d23c4 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/repository/CustomSequenceGeneratorOpsRepositoryImplTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/repository/CustomSequenceGeneratorOpsRepositoryImplTest.java @@ -1,25 +1,17 @@ package it.gov.pagopa.admissibility.connector.repository; -import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import it.gov.pagopa.admissibility.model.CustomSequenceGenerator; -import it.gov.pagopa.common.mongo.MongoTestUtilitiesService; -import it.gov.pagopa.common.reactive.mongo.BaseMongoEmbeddedTest; -import it.gov.pagopa.common.reactive.mongo.config.ReactiveMongoConfig; +import it.gov.pagopa.common.mongo.MongoTest; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -@ContextConfiguration(classes = { - CustomSequenceGeneratorRepository.class, - ReactiveMongoConfig.class, - MongoTestUtilitiesService.TestMongoConfiguration.class, - SimpleMeterRegistry.class}) @Slf4j -class CustomSequenceGeneratorOpsRepositoryImplTest extends BaseMongoEmbeddedTest { +@MongoTest +class CustomSequenceGeneratorOpsRepositoryImplTest { @Autowired protected CustomSequenceGeneratorRepository customSequenceGeneratorRepository; diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/repository/InitiativeCountersReservationOpsRepositoryImplTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/repository/InitiativeCountersReservationOpsRepositoryImplTest.java index 7f343dbd..7716b7dd 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/repository/InitiativeCountersReservationOpsRepositoryImplTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/repository/InitiativeCountersReservationOpsRepositoryImplTest.java @@ -1,14 +1,10 @@ package it.gov.pagopa.admissibility.connector.repository; -import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import it.gov.pagopa.admissibility.model.InitiativeCounters; -import it.gov.pagopa.common.mongo.MongoTestUtilitiesService; -import it.gov.pagopa.common.reactive.mongo.BaseMongoEmbeddedTest; -import it.gov.pagopa.common.reactive.mongo.config.ReactiveMongoConfig; +import it.gov.pagopa.common.mongo.MongoTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; import java.math.BigDecimal; import java.util.List; @@ -18,13 +14,8 @@ import java.util.concurrent.Future; import java.util.stream.IntStream; -@ContextConfiguration(classes = { - InitiativeCountersReservationOpsRepositoryImpl.class, - InitiativeCountersRepository.class, - ReactiveMongoConfig.class, - MongoTestUtilitiesService.TestMongoConfiguration.class, - SimpleMeterRegistry.class}) -class InitiativeCountersReservationOpsRepositoryImplTest extends BaseMongoEmbeddedTest { +@MongoTest +class InitiativeCountersReservationOpsRepositoryImplTest { @Autowired protected InitiativeCountersRepository initiativeCountersRepository; diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/repository/OnboardingFamiliesRepositoryTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/repository/OnboardingFamiliesRepositoryTest.java index a43ec8c9..69354cde 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/repository/OnboardingFamiliesRepositoryTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/repository/OnboardingFamiliesRepositoryTest.java @@ -1,19 +1,15 @@ package it.gov.pagopa.admissibility.connector.repository; import com.mongodb.client.result.UpdateResult; -import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import it.gov.pagopa.admissibility.dto.onboarding.OnboardingRejectionReason; import it.gov.pagopa.admissibility.dto.onboarding.extra.Family; import it.gov.pagopa.admissibility.enums.OnboardingFamilyEvaluationStatus; import it.gov.pagopa.admissibility.model.OnboardingFamilies; -import it.gov.pagopa.common.mongo.MongoTestUtilitiesService; -import it.gov.pagopa.common.reactive.mongo.BaseMongoEmbeddedTest; -import it.gov.pagopa.common.reactive.mongo.config.ReactiveMongoConfig; +import it.gov.pagopa.common.mongo.MongoTest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; @@ -22,12 +18,8 @@ import java.util.List; import java.util.Set; -@ContextConfiguration(classes = { - OnboardingFamiliesRepositoryTest.class, - ReactiveMongoConfig.class, - MongoTestUtilitiesService.TestMongoConfiguration.class, - SimpleMeterRegistry.class}) -class OnboardingFamiliesRepositoryTest extends BaseMongoEmbeddedTest { +@MongoTest +class OnboardingFamiliesRepositoryTest{ @Autowired private OnboardingFamiliesRepository repository; diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestBase.java b/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java similarity index 80% rename from src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestBase.java rename to src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java index 1854786c..e4ffec30 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTestBase.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/rest/mock/FamilyMockRestClientImplTest.java @@ -7,14 +7,22 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; import reactor.core.Exceptions; +import static it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest.WIREMOCK_TEST_PROP2BASEPATH_MAP_PREFIX; + @ContextConfiguration( classes = { FamilyMockRestClientImpl.class, WebClientConfig.class }) +@TestPropertySource( + properties = { + WIREMOCK_TEST_PROP2BASEPATH_MAP_PREFIX + "app.idpay-mock.base-url=pdndMock" + } +) class FamilyMockRestClientImplTest extends BaseWireMockTest { @Autowired diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java index 04d39328..249d8607 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java @@ -1,6 +1,6 @@ package it.gov.pagopa.admissibility.connector.soap.inps.service; -import it.gov.pagopa.admissibility.BaseIntegrationTest; +import it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -12,11 +12,11 @@ import static org.junit.platform.engine.discovery.DiscoverySelectors.selectMethod; -class IseeConsultationSoapClientImplSSLKOTest{ +class IseeConsultationSoapClientImplSSLKOTest { @BeforeAll static void setUp() { - BaseIntegrationTest.configureServerWiremockBeforeAll(true, false); + BaseWireMockTest.configureServerWiremockBeforeAll(true, false); } @Test @@ -24,7 +24,7 @@ void testKo(){ SummaryGeneratingListener listener = new SummaryGeneratingListener(); LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() - .selectors(selectMethod(IseeConsultationSoapClientImplIntegrationTestDeprecated.class, "callService")) + .selectors(selectMethod(IseeConsultationSoapClientImplTest.class, "callService")) .build(); Launcher launcher = LauncherFactory.create(); launcher.discover(request); diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplTest.java similarity index 91% rename from src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTest.java rename to src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplTest.java index 3f2db642..18e1b8f1 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplIntegrationTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplTest.java @@ -1,6 +1,5 @@ package it.gov.pagopa.admissibility.connector.soap.inps.service; -import it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest; import it.gov.pagopa.admissibility.connector.soap.inps.config.InpsClientConfig; import it.gov.pagopa.admissibility.connector.soap.inps.exception.InpsDailyRequestLimitException; import it.gov.pagopa.admissibility.generated.soap.ws.client.ConsultazioneIndicatoreResponseType; @@ -8,16 +7,20 @@ import it.gov.pagopa.admissibility.generated.soap.ws.client.TypeEsitoConsultazioneIndicatore; import it.gov.pagopa.admissibility.model.IseeTypologyEnum; import it.gov.pagopa.common.reactive.rest.config.WebClientConfig; +import it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest; import it.gov.pagopa.common.soap.service.SoapLoggingHandler; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; import reactor.core.publisher.Mono; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; +import static it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest.WIREMOCK_TEST_PROP2BASEPATH_SECURE_MAP_PREFIX; + @ContextConfiguration( classes = { IseeConsultationSoapClientImpl.class, @@ -25,7 +28,12 @@ SoapLoggingHandler.class, WebClientConfig.class }) -public class IseeConsultationSoapClientImplIntegrationTest extends BaseWireMockTest { +@TestPropertySource( + properties = { + WIREMOCK_TEST_PROP2BASEPATH_SECURE_MAP_PREFIX + "app.inps.iseeConsultation.base-url=inps/isee" + } +) +public class IseeConsultationSoapClientImplTest extends BaseWireMockTest { public static final String FISCAL_CODE_OK = "CF_OK"; public static final String FISCAL_CODE_NOTFOUND = "CF_NOT_FOUND"; diff --git a/src/test/java/it/gov/pagopa/common/mongo/MongoTest.java b/src/test/java/it/gov/pagopa/common/mongo/MongoTest.java new file mode 100644 index 00000000..2b9d9f0b --- /dev/null +++ b/src/test/java/it/gov/pagopa/common/mongo/MongoTest.java @@ -0,0 +1,54 @@ +package it.gov.pagopa.common.mongo; + +import io.micrometer.core.instrument.binder.mongodb.MongoMetricsCommandListener; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import it.gov.pagopa.common.mongo.config.MongoConfig; +import it.gov.pagopa.common.mongo.singleinstance.AutoConfigureSingleInstanceMongodb; +import it.gov.pagopa.common.reactive.mongo.config.ReactiveMongoConfig; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.mongo.MongoClientSettingsBuilderCustomizer; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.lang.annotation.*; + +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@ExtendWith(SpringExtension.class) +@TestPropertySource( + properties = { + "de.flapdoodle.mongodb.embedded.version=4.2.24", + + "spring.data.mongodb.database=idpay", + "spring.data.mongodb.config.connectionPool.maxSize: 100", + "spring.data.mongodb.config.connectionPool.minSize: 0", + "spring.data.mongodb.config.connectionPool.maxWaitTimeMS: 120000", + "spring.data.mongodb.config.connectionPool.maxConnectionLifeTimeMS: 0", + "spring.data.mongodb.config.connectionPool.maxConnectionIdleTimeMS: 120000", + "spring.data.mongodb.config.connectionPool.maxConnecting: 2", + }) +@AutoConfigureSingleInstanceMongodb +@Import({MongoTestUtilitiesService.TestMongoConfiguration.class, + ReactiveMongoConfig.class, + SimpleMeterRegistry.class, + MongoTest.MongoTestConfiguration.class}) +public @interface MongoTest { + @TestConfiguration + class MongoTestConfiguration extends MongoConfig { + @Autowired + private MongoMetricsCommandListener mongoMetricsCommandListener; + + @Override + public MongoClientSettingsBuilderCustomizer customizer(MongoDbCustomProperties mongoDbCustomProperties) { + return builder -> { + super.customizer(mongoDbCustomProperties).customize(builder); + builder.addCommandListener(mongoMetricsCommandListener); + }; + } + + } +} \ No newline at end of file diff --git a/src/test/java/it/gov/pagopa/common/reactive/mongo/BaseMongoEmbeddedTest.java b/src/test/java/it/gov/pagopa/common/reactive/mongo/BaseMongoEmbeddedTest.java deleted file mode 100644 index 0fb84bc8..00000000 --- a/src/test/java/it/gov/pagopa/common/reactive/mongo/BaseMongoEmbeddedTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package it.gov.pagopa.common.reactive.mongo; - -import it.gov.pagopa.common.mongo.singleinstance.AutoConfigureSingleInstanceMongodb; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -@TestPropertySource(properties = { - "de.flapdoodle.mongodb.embedded.version=4.2.24", - - "spring.data.mongodb.database=idpay", - "spring.data.mongodb.config.connectionPool.maxSize: 100", - "spring.data.mongodb.config.connectionPool.minSize: 0", - "spring.data.mongodb.config.connectionPool.maxWaitTimeMS: 120000", - "spring.data.mongodb.config.connectionPool.maxConnectionLifeTimeMS: 0", - "spring.data.mongodb.config.connectionPool.maxConnectionIdleTimeMS: 120000", - "spring.data.mongodb.config.connectionPool.maxConnecting: 2", -}) -@ExtendWith(SpringExtension.class) -@AutoConfigureSingleInstanceMongodb -@SuppressWarnings("squid:S2187") -public class BaseMongoEmbeddedTest { -} diff --git a/src/test/java/it/gov/pagopa/common/reactive/wireMock/BaseWireMockTest.java b/src/test/java/it/gov/pagopa/common/reactive/wireMock/BaseWireMockTest.java index eab61436..076cc7ba 100644 --- a/src/test/java/it/gov/pagopa/common/reactive/wireMock/BaseWireMockTest.java +++ b/src/test/java/it/gov/pagopa/common/reactive/wireMock/BaseWireMockTest.java @@ -11,17 +11,25 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.data.util.Pair; +import org.springframework.core.env.EnumerablePropertySource; +import org.springframework.core.env.PropertySource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.support.TestPropertySourceUtils; +import java.util.HashMap; +import java.util.Map; import java.util.concurrent.TimeUnit; -import java.util.stream.Stream; @ExtendWith(JUnitExtensionContextHolder.class) @SpringBootTest -@ContextConfiguration(initializers = {BaseWireMockTest.WireMockInitializer.class}) +@ContextConfiguration( + initializers = {BaseWireMockTest.WireMockInitializer.class}) @SuppressWarnings("squid:S2187") public class BaseWireMockTest { + public static final String WIREMOCK_TEST_PROP2BASEPATH_MAP_PREFIX = "wireMock-test.prop2basePath."; + public static final String WIREMOCK_TEST_PROP2BASEPATH_SECURE_MAP_PREFIX = "wireMock-test.prop2basePath.secure."; + + private static final Map propertiesMap = new HashMap<>(); + private static final Map propertiesSecureMap = new HashMap<>(); @PostConstruct public void logEmbeddedServerConfig() { @@ -108,18 +116,26 @@ static void restoreWireMockConfig() { public static class WireMockInitializer implements ApplicationContextInitializer { @Override public void initialize(@NonNull ConfigurableApplicationContext applicationContext) { - // setting wiremock HTTP baseUrl - Stream.of( - Pair.of("app.pdv.base-url", "pdv"), - Pair.of("app.pdnd.base-url", "pdnd"), - Pair.of("app.idpay-mock.base-url", "pdndMock") - ).forEach(setWireMockBaseMockedServicePath(applicationContext, serverWireMockExtension.getRuntimeInfo().getHttpBaseUrl())); - - // setting wiremock HTTPS baseUrl - Stream.of( - Pair.of("app.anpr.config.base-url", "anpr/"), - Pair.of("app.inps.iseeConsultation.base-url", "inps/isee") - ).forEach(setWireMockBaseMockedServicePath(applicationContext, serverWireMockExtension.getRuntimeInfo().getHttpsBaseUrl())); + + for (PropertySource propertySource : applicationContext.getEnvironment().getPropertySources()) { + if (propertySource instanceof EnumerablePropertySource) { + for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) { + if (key.startsWith(WIREMOCK_TEST_PROP2BASEPATH_MAP_PREFIX)) { + propertiesMap.put(key.substring(WIREMOCK_TEST_PROP2BASEPATH_MAP_PREFIX.length()), (String) propertySource.getProperty(key)); + } + if (key.startsWith(WIREMOCK_TEST_PROP2BASEPATH_SECURE_MAP_PREFIX)) { + propertiesSecureMap.put(key.substring(WIREMOCK_TEST_PROP2BASEPATH_SECURE_MAP_PREFIX.length()), (String) propertySource.getProperty(key)); + } + } + } + } + + for (Map.Entry entry : propertiesMap.entrySet()) { + setWireMockBaseMockedServicePath(applicationContext,serverWireMockExtension.getRuntimeInfo().getHttpBaseUrl(),entry); + } + for (Map.Entry entry : propertiesSecureMap.entrySet()) { + setWireMockBaseMockedServicePath(applicationContext,serverWireMockExtension.getRuntimeInfo().getHttpBaseUrl(),entry); + } System.out.printf(""" ************************ @@ -132,11 +148,8 @@ public void initialize(@NonNull ConfigurableApplicationContext applicationContex serverWireMockExtension.getRuntimeInfo().getHttpsBaseUrl()); } - private static java.util.function.Consumer> setWireMockBaseMockedServicePath(ConfigurableApplicationContext applicationContext, String serverWireMock) { - return key2basePath -> TestPropertySourceUtils.addInlinedPropertiesToEnvironment(applicationContext, - String.format("%s=%s/%s", key2basePath.getFirst(), serverWireMock, key2basePath.getSecond()) - ); - + private static void setWireMockBaseMockedServicePath(ConfigurableApplicationContext applicationContext, String serverWireMock,Map.Entry entry){ + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(applicationContext,String.format("%s=%s/%s",entry.getKey(),serverWireMock,entry.getValue())); } } //endregion From d0ccbf3cf556eea21f72324683a98ba3414beb3b Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Thu, 29 Feb 2024 12:53:23 +0100 Subject: [PATCH 08/16] IDP-2293 updated tests --- .../AuthoritiesDataRetrieverServiceImpl.java | 2 +- .../admissibility/BaseIntegrationTest.java | 2 +- ...AnprC001RestClientImplIntegrationTest.java | 468 ++++++++++-------- .../service/AnprC001RestClientSSLKOTest.java | 72 +-- .../CommandMediatorServiceImplTest.java | 25 +- ...ieverServiceIntegrationTestDeprecated.java | 98 ---- 6 files changed, 326 insertions(+), 341 deletions(-) delete mode 100644 src/test/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceIntegrationTestDeprecated.java diff --git a/src/main/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceImpl.java b/src/main/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceImpl.java index 7d7a8de9..0022a168 100644 --- a/src/main/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceImpl.java +++ b/src/main/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceImpl.java @@ -64,7 +64,7 @@ public AuthoritiesDataRetrieverServiceImpl( } @Override - public Mono retrieve(OnboardingDTO onboardingRequest, InitiativeConfig initiativeConfig, Message message) { +public Mono retrieve(OnboardingDTO onboardingRequest, InitiativeConfig initiativeConfig, Message message) { log.trace("[ONBOARDING_REQUEST] [AUTOMATED_CRITERIA_FIELD_FILL] retrieving automated criteria of user {} into initiative {}", onboardingRequest.getUserId(), onboardingRequest.getInitiativeId()); List iseeTypes; diff --git a/src/test/java/it/gov/pagopa/admissibility/BaseIntegrationTest.java b/src/test/java/it/gov/pagopa/admissibility/BaseIntegrationTest.java index 79ddb95d..49e333ad 100644 --- a/src/test/java/it/gov/pagopa/admissibility/BaseIntegrationTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/BaseIntegrationTest.java @@ -207,7 +207,7 @@ protected String normalizePayload(String expectedPayload) { //region desc=Setting WireMock private static boolean WIREMOCK_REQUEST_CLIENT_AUTH = true; private static boolean USE_TRUSTORE_OK = true; - private static final String TRUSTSTORE_PATH = "src/test/resources/wiremockKeyStore.p12"; + public static final String TRUSTSTORE_PATH = "src/test/resources/wiremockKeyStore.p12"; private static final String TRUSTSTORE_KO_PATH = "src/test/resources/wiremockTrustStoreKO.p12"; @RegisterExtension static WireMockExtension serverWireMockExtension = initServerWiremock(); diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientImplIntegrationTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientImplIntegrationTest.java index 6b56ad87..2b348944 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientImplIntegrationTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientImplIntegrationTest.java @@ -1,204 +1,264 @@ -package it.gov.pagopa.admissibility.connector.rest.anpr.service; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.cache.Cache; -import it.gov.pagopa.admissibility.BaseIntegrationTest; -import it.gov.pagopa.admissibility.generated.openapi.pdnd.residence.assessment.client.dto.RispostaE002OKDTO; -import it.gov.pagopa.admissibility.model.PdndInitiativeConfig; -import it.gov.pagopa.common.reactive.pdnd.exception.PdndServiceTooManyRequestException; -import it.gov.pagopa.common.reactive.pdnd.service.PdndRestClient; -import it.gov.pagopa.common.utils.TestUtils; -import lombok.SneakyThrows; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.test.context.TestPropertySource; -import org.springframework.util.ReflectionUtils; -import reactor.core.publisher.Mono; - -import java.lang.reflect.Field; - -@TestPropertySource(properties = { - "logging.level.it.gov.pagopa.admissibility.connector.rest.anpr.service.AnprC001RestClientImpl=WARN", - - "app.anpr.config.https-config.enabled=true", - // cert and key configured inside wiremockKeyStore.p12 - "app.anpr.config.https-config.cert=-----BEGIN CERTIFICATE-----\\nMIIDnzCCAoegAwIBAgIUJ8/0z+sR6Llr9FcIGoc5nvZQydgwDQYJKoZIhvcNAQEL\\nBQAwXzELMAkGA1UEBhMCSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUx\\nDjAMBgNVBAoMBUlEUEFZMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxo\\nb3N0MB4XDTIyMTEwOTE1MTI0NFoXDTMyMDkxNzE1MTI0NFowXzELMAkGA1UEBhMC\\nSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUxDjAMBgNVBAoMBUlEUEFZ\\nMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG\\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEArDOJKswwCaKdYJbaHZz3bgEIl7z1ArZpNI54\\nZGaXcRitiwjr/W9fenW69mG7IAlITuPtaIu4iggXTcSRuaulres2EvuP7KjL0tfo\\nx/PstqaMZzLF8wOYfJE4iJ8ffcQL67LJ3/Wwn2FhYVV+4D2AYW8QPdRm406HJG7b\\nNKLmdM9AFUQp6zoTvNegyWQyAfH40i72UopltDubcAykD6YgkRctCtKd8h/BRpIR\\ntMn0AGLM/o5qwYu+eCAy8/7Ppj3HzCwHkDOJad/g2pRj4soJdvn5rP6TM4OVtZ7V\\nehxionkaccBPcyDGSrIo5837XYaGv3r7Rn0rCplfxnU4Gtmd5wIDAQABo1MwUTAd\\nBgNVHQ4EFgQUPYfJeHRHwSLmcueB8jUQSHUReVIwHwYDVR0jBBgwFoAUPYfJeHRH\\nwSLmcueB8jUQSHUReVIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\\nAQEAK34LEHSVM44Wwbs9nKDKeQTRGosdd+gQSrqGf3nI0vkhckuaoYPnuFKi+eo2\\nr+J6xXgqhQfrvhXnYxNEJr9U+9ELBc3IjG6bTUS6HyWhu2PJCeckxQJqonVntl99\\njmEr4G7QJeDc9oJmC0NJqBmQS/D0tMxChNWpYe1AoGXwqc4S6NTd3x2Z8THzv8du\\nMMn7+1f/VOWe7/Iuuvx5DHN2JFi0lvhMqwglIweGn/qLGB0+r9GM+QlfGuZvUey2\\nx3C0DLQnNIkNKktGjaNjCmpZcd9SIVi6TOPpR+AxlIddYvUXu4GYVXyfDPgzPeha\\nJDiI4WMkIMmYSzhMc/lfuDMGow==\\n-----END CERTIFICATE-----", - "app.anpr.config.https-config.key=-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCsM4kqzDAJop1g\\nltodnPduAQiXvPUCtmk0jnhkZpdxGK2LCOv9b196dbr2YbsgCUhO4+1oi7iKCBdN\\nxJG5q6Wt6zYS+4/sqMvS1+jH8+y2poxnMsXzA5h8kTiInx99xAvrssnf9bCfYWFh\\nVX7gPYBhbxA91GbjTockbts0ouZ0z0AVRCnrOhO816DJZDIB8fjSLvZSimW0O5tw\\nDKQPpiCRFy0K0p3yH8FGkhG0yfQAYsz+jmrBi754IDLz/s+mPcfMLAeQM4lp3+Da\\nlGPiygl2+fms/pMzg5W1ntV6HGKieRpxwE9zIMZKsijnzftdhoa/evtGfSsKmV/G\\ndTga2Z3nAgMBAAECggEAEC6FmMJ4Tyd7T3zNgVPjQnCRbKTihz858qjislibqZKO\\nmE6d0oJ5P+o5R/bWHUQSCevMPvNGQ55QBkxO/1ocZxP/0FfYZf5UrPsCEmwfFejf\\nr8DrLhNr7GS/IcOGM4zNK/hwlP2i+88sVfexRQQygLVtmsnPY1PZSjiqm68lJdu+\\naP8TYM10y1aeiYnfuUYvnvXJFXeTEockhaUJTmeIQNbbUy+pyJ0mAPASPtXRLr8h\\nUflutICnWcx4v/qkCn1jmHw+NMA4q7hOH7UuOAqj53FqGMN+IWfjMmmYoQ7MVURx\\n8CrnEtlCOua+C8EEIFL2ylvV7X0cv/DqCJLVQoegsQKBgQDLzMaAjNgD8xSXp+Gj\\nbeeUsSGptEaGMuA89AzyTnCyvU9a1HGwDAghoQPae+pVk7R5uokojWkBVzP/kKxv\\nZldGwPOegUUdBLS4yJML+OkqtoCgf3Mbcozm5dVYtx7bYdhh3PswzRmn/h/YjEAz\\n+/mxi6dJir0k0Nd4YNtQbzBctwKBgQDYTtSmJvVQdOHnzqA/LRmMF1l+HaqLuDfu\\nB4rDlxCdDfOAvHqz+3YapP3B4MQuz29TSDqwAnzoN2XZX5B6g/jKauWpAwZkFXuO\\nfqcfNG/+MewTcHIYNm+EtgXtIsnCXDfAeXdQapzNsOX+XSF/aWcgGHg18xOBPt0R\\n7Aoa/h34UQKBgQCsCzGjwcJ2CxXeNPYxfg1ao/HUDoDet0I/kpL/VqKi8Vd1SRS0\\nVmPi58eWALfBCJD5ljRFjKMRY6lc3KgE3vNconTG4UAUEC30NDaWi8liqnCJjS4C\\nBMDYBzwEyYn+D2qYqvFOsEYxYEFIEJX+jH+sl0VguwOTec38LF/YVhUQnwKBgG5u\\n2Kw3SZkZA1ioqjF24gsexKbZmH+avps8qICw+F9mhwIbt/15jVOPFqrMCPzpFKoN\\nP0ErFAAugEYZPxb9l6AoMTY3gCTKvvkB+mq5B9BcRm2qQ+XOrOKxV5c44o7jK+eN\\nW/fnZkSxYsqZW4fEFU1SkNTiU/vxT0ZeHs6nHD/xAoGAOIqaqQnJfGj/wLo3Z9o5\\n/Oxu1zTPGZC6SqpdygCjlQ0kQ8Bp0LV7nL06/VCHAHI2lF12xApRnFk7GY3xyqK8\\nnYxeRASCj3GGmLupGshtfCtDBeysE2h7kj3Bo0d6g1Ye+j8BUZuZaZm6WNlo7cgE\\nNLHn1k0IpmXFOiFa1Y1D6Bc=\\n-----END PRIVATE KEY-----", - - "app.anpr.config.https-config.mutualAuthEnabled=true", - // Wiremock configured to use same keystore: wiremockKeyStore.p12 - "app.anpr.config.https-config.trustCertificatesCollection=-----BEGIN CERTIFICATE-----\\nMIIDnzCCAoegAwIBAgIUJ8/0z+sR6Llr9FcIGoc5nvZQydgwDQYJKoZIhvcNAQEL\\nBQAwXzELMAkGA1UEBhMCSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUx\\nDjAMBgNVBAoMBUlEUEFZMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxo\\nb3N0MB4XDTIyMTEwOTE1MTI0NFoXDTMyMDkxNzE1MTI0NFowXzELMAkGA1UEBhMC\\nSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUxDjAMBgNVBAoMBUlEUEFZ\\nMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG\\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEArDOJKswwCaKdYJbaHZz3bgEIl7z1ArZpNI54\\nZGaXcRitiwjr/W9fenW69mG7IAlITuPtaIu4iggXTcSRuaulres2EvuP7KjL0tfo\\nx/PstqaMZzLF8wOYfJE4iJ8ffcQL67LJ3/Wwn2FhYVV+4D2AYW8QPdRm406HJG7b\\nNKLmdM9AFUQp6zoTvNegyWQyAfH40i72UopltDubcAykD6YgkRctCtKd8h/BRpIR\\ntMn0AGLM/o5qwYu+eCAy8/7Ppj3HzCwHkDOJad/g2pRj4soJdvn5rP6TM4OVtZ7V\\nehxionkaccBPcyDGSrIo5837XYaGv3r7Rn0rCplfxnU4Gtmd5wIDAQABo1MwUTAd\\nBgNVHQ4EFgQUPYfJeHRHwSLmcueB8jUQSHUReVIwHwYDVR0jBBgwFoAUPYfJeHRH\\nwSLmcueB8jUQSHUReVIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\\nAQEAK34LEHSVM44Wwbs9nKDKeQTRGosdd+gQSrqGf3nI0vkhckuaoYPnuFKi+eo2\\nr+J6xXgqhQfrvhXnYxNEJr9U+9ELBc3IjG6bTUS6HyWhu2PJCeckxQJqonVntl99\\njmEr4G7QJeDc9oJmC0NJqBmQS/D0tMxChNWpYe1AoGXwqc4S6NTd3x2Z8THzv8du\\nMMn7+1f/VOWe7/Iuuvx5DHN2JFi0lvhMqwglIweGn/qLGB0+r9GM+QlfGuZvUey2\\nx3C0DLQnNIkNKktGjaNjCmpZcd9SIVi6TOPpR+AxlIddYvUXu4GYVXyfDPgzPeha\\nJDiI4WMkIMmYSzhMc/lfuDMGow==\\n-----END CERTIFICATE-----", -}) -public class AnprC001RestClientImplIntegrationTest extends BaseIntegrationTest { - - public static final String FISCAL_CODE_OK = "CF_OK"; - public static final String FISCAL_CODE_NOTFOUND = "CF_NOT_FOUND"; - public static final String FISCAL_CODE_INVALIDREQUEST = "CF_INVALID_REQUEST"; - public static final String FISCAL_CODE_TOOMANYREQUESTS = "CF_ANPR_TOO_MANY_REQUESTS"; - - public static final PdndInitiativeConfig PDND_INITIATIVE_CONFIG = new PdndInitiativeConfig( - "CLIENTID", - "KID", - "PURPOSEID" - ); - - @SpyBean - private ObjectMapper objectMapper; - @SpyBean - private PdndRestClient pdndRestClient; - - @Autowired - private AnprC001RestClient anprC001RestClient; - - @BeforeEach - void clearCache() throws IllegalAccessException { - Field cacheField = ReflectionUtils.findField(anprC001RestClient.getClass(), "pdndAuthDataCache"); - Assertions.assertNotNull(cacheField); - cacheField.setAccessible(true); - Cache cache = (Cache) cacheField.get(anprC001RestClient); - cache.invalidateAll(); - } - - @Test - void getResidenceAssessment(){ - // When - RispostaE002OKDTO result = anprC001RestClient.invoke(FISCAL_CODE_OK, PDND_INITIATIVE_CONFIG).block(); - - // Then - RispostaE002OKDTO expectedResponse = buildExpectedResponse(); - expectedResponse.getListaSoggetti().getDatiSoggetto().get(0).getGeneralita().getCodiceFiscale().setCodFiscale(FISCAL_CODE_OK); - Assertions.assertEquals(expectedResponse, result); - - // accessToken cached for each pdndInitiativeConfig - RispostaE002OKDTO result2ndInvoke = anprC001RestClient.invoke(FISCAL_CODE_OK, PDND_INITIATIVE_CONFIG).block(); - Assertions.assertEquals(expectedResponse, result2ndInvoke); - - Mockito.verify(pdndRestClient).createToken(Mockito.eq(PDND_INITIATIVE_CONFIG.getClientId()), Mockito.anyString()); - - // new clientId - PdndInitiativeConfig pdndInitiativeConfig2 = new PdndInitiativeConfig( - "CLIENTID2", - "KID", - "PURPOSEID" - ); - RispostaE002OKDTO resultNewClientId = anprC001RestClient.invoke(FISCAL_CODE_OK, pdndInitiativeConfig2).block(); - Assertions.assertEquals(expectedResponse, resultNewClientId); - - Mockito.verify(pdndRestClient, Mockito.times(2)).createToken(Mockito.anyString(), Mockito.anyString()); - } - - @Test - void testNotFound(){ - //When - RispostaE002OKDTO result = anprC001RestClient.invoke(FISCAL_CODE_NOTFOUND, PDND_INITIATIVE_CONFIG).block(); - - // Then - Assertions.assertNotNull(result); - Assertions.assertNull(result.getListaSoggetti()); - } - - @Test - void testInvalidRequest(){ - Mono mono = anprC001RestClient.invoke(FISCAL_CODE_INVALIDREQUEST, PDND_INITIATIVE_CONFIG); - IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class, mono::block); - Assertions.assertTrue(exception.getMessage().startsWith("[PDND_SERVICE_INVOKE] Something went wrong when invoking PDND service https://modipa-val.anpr.interno.it/govway/rest/in/MinInternoPortaANPR/C001-servizioNotifica/v1: 400 Bad Request")); - } - - @Test - void testTooManyRequests(){ - Mono mono = anprC001RestClient.invoke(FISCAL_CODE_TOOMANYREQUESTS, PDND_INITIATIVE_CONFIG); - Assertions.assertThrows(PdndServiceTooManyRequestException.class, mono::block); - } - - @Test - @SneakyThrows - void objectMapperException(){ - // Given - Mockito.when(objectMapper.writeValueAsString(Mockito.any())).thenThrow(JsonProcessingException.class); - - // When - try { - anprC001RestClient.invoke(FISCAL_CODE_OK, PDND_INITIATIVE_CONFIG).block(); - }catch (Exception e){ - // Then - Assertions.assertTrue(e instanceof IllegalStateException); - } - } - - public static RispostaE002OKDTO buildExpectedResponse() { - try { - return TestUtils.objectMapper.readValue(""" - { - "listaSoggetti": { - "datiSoggetto": [ - { - "generalita": { - "codiceFiscale": { - "codFiscale": "STTSGT90A01H501J", - "validitaCF": "9" - }, - "cognome": "SETTIMO", - "dataNascita": "1990-01-01", - "idSchedaSoggettoANPR": "2775118", - "luogoNascita": { - "comune": { - "codiceIstat": "058091", - "nomeComune": "ROMA", - "siglaProvinciaIstat": "RM" - } - }, - "nome": "SOGGETTO", - "sesso": "M" - }, - "identificativi": { - "idANPR": "AF41450AS" - }, - "infoSoggettoEnte": [ - { - "chiave": "Verifica esistenza in vita", - "id": "1003", - "valore": "S" - } - ], - "residenza": [ - { - "indirizzo": { - "cap": "41026", - "comune": { - "codiceIstat": "036030", - "nomeComune": "PAVULLO NEL FRIGNANO", - "siglaProvinciaIstat": "MO" - }, - "numeroCivico": { - "civicoInterno": { - "interno1": "3", - "scala": "B4" - }, - "numero": "55" - }, - "toponimo": { - "denominazioneToponimo": "AMERIGO VESPUCCI", - "specie": "VIA", - "specieFonte": "1" - } - }, - "tipoIndirizzo": "1" - } - ] - } - ] - }, - "idOperazioneANPR": "58370927" - } - """, RispostaE002OKDTO.class); - } catch (JsonProcessingException e) { - throw new IllegalStateException("Cannot read expected response", e); - } - } - -} \ No newline at end of file +//package it.gov.pagopa.admissibility.connector.rest.anpr.service; +// +//import com.fasterxml.jackson.core.JsonProcessingException; +//import com.fasterxml.jackson.databind.ObjectMapper; +//import com.google.common.cache.Cache; +//import it.gov.pagopa.admissibility.config.PagoPaAnprPdndConfig; +//import it.gov.pagopa.admissibility.connector.repository.CustomSequenceGeneratorRepository; +//import it.gov.pagopa.admissibility.connector.rest.anpr.config.AnprC001ServiceConfig; +//import it.gov.pagopa.admissibility.connector.rest.anpr.config.AnprConfig; +//import it.gov.pagopa.admissibility.generated.openapi.pdnd.residence.assessment.client.dto.RispostaE002OKDTO; +//import it.gov.pagopa.admissibility.model.PdndInitiativeConfig; +//import it.gov.pagopa.common.reactive.pdnd.config.PdndConfig; +//import it.gov.pagopa.common.reactive.pdnd.exception.PdndServiceTooManyRequestException; +//import it.gov.pagopa.common.reactive.pdnd.service.PdndRestClient; +//import it.gov.pagopa.common.reactive.rest.config.WebClientConfig; +//import it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest; +//import it.gov.pagopa.common.utils.TestUtils; +//import lombok.SneakyThrows; +//import org.junit.jupiter.api.Assertions; +//import org.junit.jupiter.api.BeforeEach; +//import org.junit.jupiter.api.Test; +//import org.junit.jupiter.api.extension.ExtendWith; +//import org.mockito.Mock; +//import org.mockito.Mockito; +//import org.mockito.junit.jupiter.MockitoExtension; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.boot.test.mock.mockito.MockBean; +//import org.springframework.test.context.ContextConfiguration; +//import org.springframework.test.context.TestPropertySource; +//import org.springframework.util.ReflectionUtils; +//import org.springframework.web.reactive.function.client.WebClient; +//import reactor.core.publisher.Mono; +// +//import java.lang.reflect.Field; +// +//import static it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest.WIREMOCK_TEST_PROP2BASEPATH_SECURE_MAP_PREFIX; +// +////@TestPropertySource(properties = { +//// "logging.level.it.gov.pagopa.admissibility.connector.rest.anpr.service.AnprC001RestClientImpl=WARN", +//// +//// "app.anpr.config.https-config.enabled=true", +//// // cert and key configured inside wiremockKeyStore.p12 +//// "app.anpr.config.https-config.cert=-----BEGIN CERTIFICATE-----\\nMIIDnzCCAoegAwIBAgIUJ8/0z+sR6Llr9FcIGoc5nvZQydgwDQYJKoZIhvcNAQEL\\nBQAwXzELMAkGA1UEBhMCSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUx\\nDjAMBgNVBAoMBUlEUEFZMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxo\\nb3N0MB4XDTIyMTEwOTE1MTI0NFoXDTMyMDkxNzE1MTI0NFowXzELMAkGA1UEBhMC\\nSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUxDjAMBgNVBAoMBUlEUEFZ\\nMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG\\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEArDOJKswwCaKdYJbaHZz3bgEIl7z1ArZpNI54\\nZGaXcRitiwjr/W9fenW69mG7IAlITuPtaIu4iggXTcSRuaulres2EvuP7KjL0tfo\\nx/PstqaMZzLF8wOYfJE4iJ8ffcQL67LJ3/Wwn2FhYVV+4D2AYW8QPdRm406HJG7b\\nNKLmdM9AFUQp6zoTvNegyWQyAfH40i72UopltDubcAykD6YgkRctCtKd8h/BRpIR\\ntMn0AGLM/o5qwYu+eCAy8/7Ppj3HzCwHkDOJad/g2pRj4soJdvn5rP6TM4OVtZ7V\\nehxionkaccBPcyDGSrIo5837XYaGv3r7Rn0rCplfxnU4Gtmd5wIDAQABo1MwUTAd\\nBgNVHQ4EFgQUPYfJeHRHwSLmcueB8jUQSHUReVIwHwYDVR0jBBgwFoAUPYfJeHRH\\nwSLmcueB8jUQSHUReVIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\\nAQEAK34LEHSVM44Wwbs9nKDKeQTRGosdd+gQSrqGf3nI0vkhckuaoYPnuFKi+eo2\\nr+J6xXgqhQfrvhXnYxNEJr9U+9ELBc3IjG6bTUS6HyWhu2PJCeckxQJqonVntl99\\njmEr4G7QJeDc9oJmC0NJqBmQS/D0tMxChNWpYe1AoGXwqc4S6NTd3x2Z8THzv8du\\nMMn7+1f/VOWe7/Iuuvx5DHN2JFi0lvhMqwglIweGn/qLGB0+r9GM+QlfGuZvUey2\\nx3C0DLQnNIkNKktGjaNjCmpZcd9SIVi6TOPpR+AxlIddYvUXu4GYVXyfDPgzPeha\\nJDiI4WMkIMmYSzhMc/lfuDMGow==\\n-----END CERTIFICATE-----", +//// "app.anpr.config.https-config.key=-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCsM4kqzDAJop1g\\nltodnPduAQiXvPUCtmk0jnhkZpdxGK2LCOv9b196dbr2YbsgCUhO4+1oi7iKCBdN\\nxJG5q6Wt6zYS+4/sqMvS1+jH8+y2poxnMsXzA5h8kTiInx99xAvrssnf9bCfYWFh\\nVX7gPYBhbxA91GbjTockbts0ouZ0z0AVRCnrOhO816DJZDIB8fjSLvZSimW0O5tw\\nDKQPpiCRFy0K0p3yH8FGkhG0yfQAYsz+jmrBi754IDLz/s+mPcfMLAeQM4lp3+Da\\nlGPiygl2+fms/pMzg5W1ntV6HGKieRpxwE9zIMZKsijnzftdhoa/evtGfSsKmV/G\\ndTga2Z3nAgMBAAECggEAEC6FmMJ4Tyd7T3zNgVPjQnCRbKTihz858qjislibqZKO\\nmE6d0oJ5P+o5R/bWHUQSCevMPvNGQ55QBkxO/1ocZxP/0FfYZf5UrPsCEmwfFejf\\nr8DrLhNr7GS/IcOGM4zNK/hwlP2i+88sVfexRQQygLVtmsnPY1PZSjiqm68lJdu+\\naP8TYM10y1aeiYnfuUYvnvXJFXeTEockhaUJTmeIQNbbUy+pyJ0mAPASPtXRLr8h\\nUflutICnWcx4v/qkCn1jmHw+NMA4q7hOH7UuOAqj53FqGMN+IWfjMmmYoQ7MVURx\\n8CrnEtlCOua+C8EEIFL2ylvV7X0cv/DqCJLVQoegsQKBgQDLzMaAjNgD8xSXp+Gj\\nbeeUsSGptEaGMuA89AzyTnCyvU9a1HGwDAghoQPae+pVk7R5uokojWkBVzP/kKxv\\nZldGwPOegUUdBLS4yJML+OkqtoCgf3Mbcozm5dVYtx7bYdhh3PswzRmn/h/YjEAz\\n+/mxi6dJir0k0Nd4YNtQbzBctwKBgQDYTtSmJvVQdOHnzqA/LRmMF1l+HaqLuDfu\\nB4rDlxCdDfOAvHqz+3YapP3B4MQuz29TSDqwAnzoN2XZX5B6g/jKauWpAwZkFXuO\\nfqcfNG/+MewTcHIYNm+EtgXtIsnCXDfAeXdQapzNsOX+XSF/aWcgGHg18xOBPt0R\\n7Aoa/h34UQKBgQCsCzGjwcJ2CxXeNPYxfg1ao/HUDoDet0I/kpL/VqKi8Vd1SRS0\\nVmPi58eWALfBCJD5ljRFjKMRY6lc3KgE3vNconTG4UAUEC30NDaWi8liqnCJjS4C\\nBMDYBzwEyYn+D2qYqvFOsEYxYEFIEJX+jH+sl0VguwOTec38LF/YVhUQnwKBgG5u\\n2Kw3SZkZA1ioqjF24gsexKbZmH+avps8qICw+F9mhwIbt/15jVOPFqrMCPzpFKoN\\nP0ErFAAugEYZPxb9l6AoMTY3gCTKvvkB+mq5B9BcRm2qQ+XOrOKxV5c44o7jK+eN\\nW/fnZkSxYsqZW4fEFU1SkNTiU/vxT0ZeHs6nHD/xAoGAOIqaqQnJfGj/wLo3Z9o5\\n/Oxu1zTPGZC6SqpdygCjlQ0kQ8Bp0LV7nL06/VCHAHI2lF12xApRnFk7GY3xyqK8\\nnYxeRASCj3GGmLupGshtfCtDBeysE2h7kj3Bo0d6g1Ye+j8BUZuZaZm6WNlo7cgE\\nNLHn1k0IpmXFOiFa1Y1D6Bc=\\n-----END PRIVATE KEY-----", +//// +//// "app.anpr.config.https-config.mutualAuthEnabled=true", +//// // Wiremock configured to use same keystore: wiremockKeyStore.p12 +//// "app.anpr.config.https-config.trustCertificatesCollection=-----BEGIN CERTIFICATE-----\\nMIIDnzCCAoegAwIBAgIUJ8/0z+sR6Llr9FcIGoc5nvZQydgwDQYJKoZIhvcNAQEL\\nBQAwXzELMAkGA1UEBhMCSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUx\\nDjAMBgNVBAoMBUlEUEFZMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxo\\nb3N0MB4XDTIyMTEwOTE1MTI0NFoXDTMyMDkxNzE1MTI0NFowXzELMAkGA1UEBhMC\\nSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUxDjAMBgNVBAoMBUlEUEFZ\\nMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG\\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEArDOJKswwCaKdYJbaHZz3bgEIl7z1ArZpNI54\\nZGaXcRitiwjr/W9fenW69mG7IAlITuPtaIu4iggXTcSRuaulres2EvuP7KjL0tfo\\nx/PstqaMZzLF8wOYfJE4iJ8ffcQL67LJ3/Wwn2FhYVV+4D2AYW8QPdRm406HJG7b\\nNKLmdM9AFUQp6zoTvNegyWQyAfH40i72UopltDubcAykD6YgkRctCtKd8h/BRpIR\\ntMn0AGLM/o5qwYu+eCAy8/7Ppj3HzCwHkDOJad/g2pRj4soJdvn5rP6TM4OVtZ7V\\nehxionkaccBPcyDGSrIo5837XYaGv3r7Rn0rCplfxnU4Gtmd5wIDAQABo1MwUTAd\\nBgNVHQ4EFgQUPYfJeHRHwSLmcueB8jUQSHUReVIwHwYDVR0jBBgwFoAUPYfJeHRH\\nwSLmcueB8jUQSHUReVIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\\nAQEAK34LEHSVM44Wwbs9nKDKeQTRGosdd+gQSrqGf3nI0vkhckuaoYPnuFKi+eo2\\nr+J6xXgqhQfrvhXnYxNEJr9U+9ELBc3IjG6bTUS6HyWhu2PJCeckxQJqonVntl99\\njmEr4G7QJeDc9oJmC0NJqBmQS/D0tMxChNWpYe1AoGXwqc4S6NTd3x2Z8THzv8du\\nMMn7+1f/VOWe7/Iuuvx5DHN2JFi0lvhMqwglIweGn/qLGB0+r9GM+QlfGuZvUey2\\nx3C0DLQnNIkNKktGjaNjCmpZcd9SIVi6TOPpR+AxlIddYvUXu4GYVXyfDPgzPeha\\nJDiI4WMkIMmYSzhMc/lfuDMGow==\\n-----END CERTIFICATE-----", +//////}) +//@ContextConfiguration(classes = { +//// AnprC001RestClientImpl.class, +//// AnprC001ServiceConfig.class, +//// AnprConfig.class, +// WebClientConfig.class +//}) +////@ContextConfiguration(classes = { +//// AnprC001RestClientImpl.class, +////// AnprC001ServiceConfig.class, +////// AnprConfig.class, +//// WebClientConfig.class}) +//@TestPropertySource( +// properties = { +// WIREMOCK_TEST_PROP2BASEPATH_SECURE_MAP_PREFIX + "app.anpr.config.base-url=anpr/", +// +// "logging.level.it.gov.pagopa.admissibility.connector.rest.anpr.service.AnprC001RestClientImpl=WARN", +// +// "app.anpr.config.https-config.enabled=true", +// // cert and key configured inside wiremockKeyStore.p12 +// "app.anpr.config.https-config.cert=-----BEGIN CERTIFICATE-----\\nMIIDnzCCAoegAwIBAgIUJ8/0z+sR6Llr9FcIGoc5nvZQydgwDQYJKoZIhvcNAQEL\\nBQAwXzELMAkGA1UEBhMCSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUx\\nDjAMBgNVBAoMBUlEUEFZMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxo\\nb3N0MB4XDTIyMTEwOTE1MTI0NFoXDTMyMDkxNzE1MTI0NFowXzELMAkGA1UEBhMC\\nSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUxDjAMBgNVBAoMBUlEUEFZ\\nMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG\\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEArDOJKswwCaKdYJbaHZz3bgEIl7z1ArZpNI54\\nZGaXcRitiwjr/W9fenW69mG7IAlITuPtaIu4iggXTcSRuaulres2EvuP7KjL0tfo\\nx/PstqaMZzLF8wOYfJE4iJ8ffcQL67LJ3/Wwn2FhYVV+4D2AYW8QPdRm406HJG7b\\nNKLmdM9AFUQp6zoTvNegyWQyAfH40i72UopltDubcAykD6YgkRctCtKd8h/BRpIR\\ntMn0AGLM/o5qwYu+eCAy8/7Ppj3HzCwHkDOJad/g2pRj4soJdvn5rP6TM4OVtZ7V\\nehxionkaccBPcyDGSrIo5837XYaGv3r7Rn0rCplfxnU4Gtmd5wIDAQABo1MwUTAd\\nBgNVHQ4EFgQUPYfJeHRHwSLmcueB8jUQSHUReVIwHwYDVR0jBBgwFoAUPYfJeHRH\\nwSLmcueB8jUQSHUReVIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\\nAQEAK34LEHSVM44Wwbs9nKDKeQTRGosdd+gQSrqGf3nI0vkhckuaoYPnuFKi+eo2\\nr+J6xXgqhQfrvhXnYxNEJr9U+9ELBc3IjG6bTUS6HyWhu2PJCeckxQJqonVntl99\\njmEr4G7QJeDc9oJmC0NJqBmQS/D0tMxChNWpYe1AoGXwqc4S6NTd3x2Z8THzv8du\\nMMn7+1f/VOWe7/Iuuvx5DHN2JFi0lvhMqwglIweGn/qLGB0+r9GM+QlfGuZvUey2\\nx3C0DLQnNIkNKktGjaNjCmpZcd9SIVi6TOPpR+AxlIddYvUXu4GYVXyfDPgzPeha\\nJDiI4WMkIMmYSzhMc/lfuDMGow==\\n-----END CERTIFICATE-----", +// "app.anpr.config.https-config.key=-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCsM4kqzDAJop1g\\nltodnPduAQiXvPUCtmk0jnhkZpdxGK2LCOv9b196dbr2YbsgCUhO4+1oi7iKCBdN\\nxJG5q6Wt6zYS+4/sqMvS1+jH8+y2poxnMsXzA5h8kTiInx99xAvrssnf9bCfYWFh\\nVX7gPYBhbxA91GbjTockbts0ouZ0z0AVRCnrOhO816DJZDIB8fjSLvZSimW0O5tw\\nDKQPpiCRFy0K0p3yH8FGkhG0yfQAYsz+jmrBi754IDLz/s+mPcfMLAeQM4lp3+Da\\nlGPiygl2+fms/pMzg5W1ntV6HGKieRpxwE9zIMZKsijnzftdhoa/evtGfSsKmV/G\\ndTga2Z3nAgMBAAECggEAEC6FmMJ4Tyd7T3zNgVPjQnCRbKTihz858qjislibqZKO\\nmE6d0oJ5P+o5R/bWHUQSCevMPvNGQ55QBkxO/1ocZxP/0FfYZf5UrPsCEmwfFejf\\nr8DrLhNr7GS/IcOGM4zNK/hwlP2i+88sVfexRQQygLVtmsnPY1PZSjiqm68lJdu+\\naP8TYM10y1aeiYnfuUYvnvXJFXeTEockhaUJTmeIQNbbUy+pyJ0mAPASPtXRLr8h\\nUflutICnWcx4v/qkCn1jmHw+NMA4q7hOH7UuOAqj53FqGMN+IWfjMmmYoQ7MVURx\\n8CrnEtlCOua+C8EEIFL2ylvV7X0cv/DqCJLVQoegsQKBgQDLzMaAjNgD8xSXp+Gj\\nbeeUsSGptEaGMuA89AzyTnCyvU9a1HGwDAghoQPae+pVk7R5uokojWkBVzP/kKxv\\nZldGwPOegUUdBLS4yJML+OkqtoCgf3Mbcozm5dVYtx7bYdhh3PswzRmn/h/YjEAz\\n+/mxi6dJir0k0Nd4YNtQbzBctwKBgQDYTtSmJvVQdOHnzqA/LRmMF1l+HaqLuDfu\\nB4rDlxCdDfOAvHqz+3YapP3B4MQuz29TSDqwAnzoN2XZX5B6g/jKauWpAwZkFXuO\\nfqcfNG/+MewTcHIYNm+EtgXtIsnCXDfAeXdQapzNsOX+XSF/aWcgGHg18xOBPt0R\\n7Aoa/h34UQKBgQCsCzGjwcJ2CxXeNPYxfg1ao/HUDoDet0I/kpL/VqKi8Vd1SRS0\\nVmPi58eWALfBCJD5ljRFjKMRY6lc3KgE3vNconTG4UAUEC30NDaWi8liqnCJjS4C\\nBMDYBzwEyYn+D2qYqvFOsEYxYEFIEJX+jH+sl0VguwOTec38LF/YVhUQnwKBgG5u\\n2Kw3SZkZA1ioqjF24gsexKbZmH+avps8qICw+F9mhwIbt/15jVOPFqrMCPzpFKoN\\nP0ErFAAugEYZPxb9l6AoMTY3gCTKvvkB+mq5B9BcRm2qQ+XOrOKxV5c44o7jK+eN\\nW/fnZkSxYsqZW4fEFU1SkNTiU/vxT0ZeHs6nHD/xAoGAOIqaqQnJfGj/wLo3Z9o5\\n/Oxu1zTPGZC6SqpdygCjlQ0kQ8Bp0LV7nL06/VCHAHI2lF12xApRnFk7GY3xyqK8\\nnYxeRASCj3GGmLupGshtfCtDBeysE2h7kj3Bo0d6g1Ye+j8BUZuZaZm6WNlo7cgE\\nNLHn1k0IpmXFOiFa1Y1D6Bc=\\n-----END PRIVATE KEY-----", +// +// "app.anpr.config.https-config.mutualAuthEnabled=true", +// // Wiremock configured to use same keystore: wiremockKeyStore.p12 +// +// } +//) +//@ExtendWith(MockitoExtension.class) +//public class AnprC001RestClientImplIntegrationTest extends BaseWireMockTest { +// +// public static final String FISCAL_CODE_OK = "CF_OK"; +// public static final String FISCAL_CODE_NOTFOUND = "CF_NOT_FOUND"; +// public static final String FISCAL_CODE_INVALIDREQUEST = "CF_INVALID_REQUEST"; +// public static final String FISCAL_CODE_TOOMANYREQUESTS = "CF_ANPR_TOO_MANY_REQUESTS"; +// +// public static final PdndInitiativeConfig PDND_INITIATIVE_CONFIG = new PdndInitiativeConfig( +// "CLIENTID", +// "KID", +// "PURPOSEID" +// ); +// +// @MockBean +// private ObjectMapper objectMapper; +// @MockBean +// private PdndRestClient pdndRestClient; +// @Mock +// private PdndConfig pdndConfig; +// @Mock +// private AnprConfig anprConfig; +// @Mock +// private AnprC001ServiceConfig anprC001ServiceConfig; +// @Mock +// private AnprSignAlgorithmRetriever anprSignAlgorithmRetriever; +// @Autowired +// private WebClientConfig webClientConfig; +// @Mock +// private CustomSequenceGeneratorRepository customSequenceGeneratorRepository; +//// @MockBean +//// private BasePdndServiceProviderConfig basePdndServiceProviderConfig; +// +// private AnprC001RestClientImpl anprC001RestClient; +//// @Autowired +//// private PagoPaAnprPdndConfig pagoPaAnprPdndConfig; +//// @Autowired +//// private CustomSequenceGeneratorRepository sequenceGeneratorRepository; +// @BeforeEach +// void clearCache() throws IllegalAccessException { +// anprC001RestClient = new AnprC001RestClientImpl(TestUtils.objectMapper,pdndConfig,anprConfig,anprC001ServiceConfig,anprSignAlgorithmRetriever,pdndRestClient, webClientConfig.webClientConfigure(),webClientConfig.httpClientConfig(),customSequenceGeneratorRepository ); +// +// Field cacheField = ReflectionUtils.findField(anprC001RestClient.getClass(), "pdndAuthDataCache"); +// Assertions.assertNotNull(cacheField); +// cacheField.setAccessible(true); +// Cache cache = (Cache) cacheField.get(anprC001RestClient); +// cache.invalidateAll(); +// +// } +// +// @Test +// void getResidenceAssessment(){ +// // When +// RispostaE002OKDTO result = anprC001RestClient.invoke(FISCAL_CODE_OK, PDND_INITIATIVE_CONFIG).block(); +// +// // Then +// RispostaE002OKDTO expectedResponse = buildExpectedResponse(); +// expectedResponse.getListaSoggetti().getDatiSoggetto().get(0).getGeneralita().getCodiceFiscale().setCodFiscale(FISCAL_CODE_OK); +// Assertions.assertEquals(expectedResponse, result); +// +// // accessToken cached for each pdndInitiativeConfig +// RispostaE002OKDTO result2ndInvoke = anprC001RestClient.invoke(FISCAL_CODE_OK, PDND_INITIATIVE_CONFIG).block(); +// Assertions.assertEquals(expectedResponse, result2ndInvoke); +// +// Mockito.verify(pdndRestClient).createToken(Mockito.eq(PDND_INITIATIVE_CONFIG.getClientId()), Mockito.anyString()); +// +// // new clientId +// PdndInitiativeConfig pdndInitiativeConfig2 = new PdndInitiativeConfig( +// "CLIENTID2", +// "KID", +// "PURPOSEID" +// ); +// RispostaE002OKDTO resultNewClientId = anprC001RestClient.invoke(FISCAL_CODE_OK, pdndInitiativeConfig2).block(); +// Assertions.assertEquals(expectedResponse, resultNewClientId); +// +// Mockito.verify(pdndRestClient, Mockito.times(2)).createToken(Mockito.anyString(), Mockito.anyString()); +// } +// +// @Test +// void testNotFound(){ +// //When +// RispostaE002OKDTO result = anprC001RestClient.invoke(FISCAL_CODE_NOTFOUND, PDND_INITIATIVE_CONFIG).block(); +// +// // Then +// Assertions.assertNotNull(result); +// Assertions.assertNull(result.getListaSoggetti()); +// } +// +// @Test +// void testInvalidRequest(){ +// Mono mono = anprC001RestClient.invoke(FISCAL_CODE_INVALIDREQUEST, PDND_INITIATIVE_CONFIG); +// IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class, mono::block); +// Assertions.assertTrue(exception.getMessage().startsWith("[PDND_SERVICE_INVOKE] Something went wrong when invoking PDND service https://modipa-val.anpr.interno.it/govway/rest/in/MinInternoPortaANPR/C001-servizioNotifica/v1: 400 Bad Request")); +// } +// +// @Test +// void testTooManyRequests(){ +// Mono mono = anprC001RestClient.invoke(FISCAL_CODE_TOOMANYREQUESTS, PDND_INITIATIVE_CONFIG); +// Assertions.assertThrows(PdndServiceTooManyRequestException.class, mono::block); +// } +// +// @Test +// @SneakyThrows +// void objectMapperException(){ +// // Given +// Mockito.when(objectMapper.writeValueAsString(Mockito.any())).thenThrow(JsonProcessingException.class); +// +// // When +// try { +// anprC001RestClient.invoke(FISCAL_CODE_OK, PDND_INITIATIVE_CONFIG).block(); +// }catch (Exception e){ +// // Then +// Assertions.assertTrue(e instanceof IllegalStateException); +// } +// } +// +// public static RispostaE002OKDTO buildExpectedResponse() { +// try { +// return TestUtils.objectMapper.readValue(""" +// { +// "listaSoggetti": { +// "datiSoggetto": [ +// { +// "generalita": { +// "codiceFiscale": { +// "codFiscale": "STTSGT90A01H501J", +// "validitaCF": "9" +// }, +// "cognome": "SETTIMO", +// "dataNascita": "1990-01-01", +// "idSchedaSoggettoANPR": "2775118", +// "luogoNascita": { +// "comune": { +// "codiceIstat": "058091", +// "nomeComune": "ROMA", +// "siglaProvinciaIstat": "RM" +// } +// }, +// "nome": "SOGGETTO", +// "sesso": "M" +// }, +// "identificativi": { +// "idANPR": "AF41450AS" +// }, +// "infoSoggettoEnte": [ +// { +// "chiave": "Verifica esistenza in vita", +// "id": "1003", +// "valore": "S" +// } +// ], +// "residenza": [ +// { +// "indirizzo": { +// "cap": "41026", +// "comune": { +// "codiceIstat": "036030", +// "nomeComune": "PAVULLO NEL FRIGNANO", +// "siglaProvinciaIstat": "MO" +// }, +// "numeroCivico": { +// "civicoInterno": { +// "interno1": "3", +// "scala": "B4" +// }, +// "numero": "55" +// }, +// "toponimo": { +// "denominazioneToponimo": "AMERIGO VESPUCCI", +// "specie": "VIA", +// "specieFonte": "1" +// } +// }, +// "tipoIndirizzo": "1" +// } +// ] +// } +// ] +// }, +// "idOperazioneANPR": "58370927" +// } +// """, RispostaE002OKDTO.class); +// } catch (JsonProcessingException e) { +// throw new IllegalStateException("Cannot read expected response", e); +// } +// } +// +//} \ No newline at end of file diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientSSLKOTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientSSLKOTest.java index 95a0d1ae..5b33b9d0 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientSSLKOTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientSSLKOTest.java @@ -1,36 +1,36 @@ -package it.gov.pagopa.admissibility.connector.rest.anpr.service; - -import it.gov.pagopa.admissibility.BaseIntegrationTest; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.platform.launcher.Launcher; -import org.junit.platform.launcher.LauncherDiscoveryRequest; -import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; -import org.junit.platform.launcher.core.LauncherFactory; -import org.junit.platform.launcher.listeners.SummaryGeneratingListener; - -import static org.junit.platform.engine.discovery.DiscoverySelectors.selectMethod; - -class AnprC001RestClientSSLKOTest { - - @BeforeAll - static void setUp() { - BaseIntegrationTest.configureServerWiremockBeforeAll(true, false); - } - - @Test - void testKo(){ - SummaryGeneratingListener listener = new SummaryGeneratingListener(); - - LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() - .selectors(selectMethod(AnprC001RestClientImplIntegrationTest.class, "getResidenceAssessment")) - .build(); - Launcher launcher = LauncherFactory.create(); - launcher.discover(request); - launcher.registerTestExecutionListeners(listener); - launcher.execute(request); - - Assertions.assertEquals(1,listener.getSummary().getTestsFailedCount()); - } -} \ No newline at end of file +//package it.gov.pagopa.admissibility.connector.rest.anpr.service; +// +//import it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest; +//import org.junit.jupiter.api.Assertions; +//import org.junit.jupiter.api.BeforeAll; +//import org.junit.jupiter.api.Test; +//import org.junit.platform.launcher.Launcher; +//import org.junit.platform.launcher.LauncherDiscoveryRequest; +//import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +//import org.junit.platform.launcher.core.LauncherFactory; +//import org.junit.platform.launcher.listeners.SummaryGeneratingListener; +// +//import static org.junit.platform.engine.discovery.DiscoverySelectors.selectMethod; +// +//class AnprC001RestClientSSLKOTest { +// +// @BeforeAll +// static void setUp() { +// BaseWireMockTest.configureServerWiremockBeforeAll(true, false); +// } +// +// @Test +// void testKo(){ +// SummaryGeneratingListener listener = new SummaryGeneratingListener(); +// +// LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() +// .selectors(selectMethod(AnprC001RestClientImplIntegrationTest.class, "getResidenceAssessment")) +// .build(); +// Launcher launcher = LauncherFactory.create(); +// launcher.discover(request); +// launcher.registerTestExecutionListeners(listener); +// launcher.execute(request); +// +// Assertions.assertEquals(1,listener.getSummary().getTestsFailedCount()); +// } +//} \ No newline at end of file diff --git a/src/test/java/it/gov/pagopa/admissibility/service/commands/CommandMediatorServiceImplTest.java b/src/test/java/it/gov/pagopa/admissibility/service/commands/CommandMediatorServiceImplTest.java index 45475ad5..71b7c2d0 100644 --- a/src/test/java/it/gov/pagopa/admissibility/service/commands/CommandMediatorServiceImplTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/service/commands/CommandMediatorServiceImplTest.java @@ -41,6 +41,8 @@ class CommandMediatorServiceImplTest { private OnboardingContextHolderService onboardingContextHolderServiceMock; @Mock private DeleteInitiativeService deleteInitiativeServiceMock; + @Mock + private Message messageMock; private CommandMediatorServiceImpl commandMediatorService; private MemoryAppender memoryAppender; @@ -90,7 +92,28 @@ void givenMessagesWhenAfterCommitsThenSuccessfully() { memoryAppender.getLoggedEvents().get(0).getFormattedMessage() ); } - + @Test + void givenErrorWhenNotifyErrorThenCallNotifierService() { + Throwable error = new RuntimeException("Test error"); + commandMediatorService.notifyError(messageMock, error); + Mockito.verify(admissibilityErrorNotifierServiceMock).notifyAdmissibilityCommands( + messageMock, + "[ADMISSIBILITY_COMMANDS] An error occurred evaluating commands", + true, + error + ); + } + @Test + void givenDeserializationErrorWhenOnDeserializationErrorThenCallNotifierService() { + Throwable error = new RuntimeException("Test error"); + commandMediatorService.onDeserializationError(messageMock).accept(error); + Mockito.verify(admissibilityErrorNotifierServiceMock).notifyAdmissibilityCommands( + messageMock, + "[ADMISSIBILITY_COMMANDS] Unexpected JSON", + false, + error + ); + } @Test void getObjectReader() { ObjectReader objectReader = commandMediatorService.getObjectReader(); diff --git a/src/test/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceIntegrationTestDeprecated.java b/src/test/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceIntegrationTestDeprecated.java deleted file mode 100644 index a8eb78d3..00000000 --- a/src/test/java/it/gov/pagopa/admissibility/service/onboarding/AuthoritiesDataRetrieverServiceIntegrationTestDeprecated.java +++ /dev/null @@ -1,98 +0,0 @@ -package it.gov.pagopa.admissibility.service.onboarding; - -import it.gov.pagopa.admissibility.BaseIntegrationTest; -import it.gov.pagopa.admissibility.dto.onboarding.OnboardingDTO; -import it.gov.pagopa.admissibility.dto.onboarding.extra.BirthDate; -import it.gov.pagopa.admissibility.dto.onboarding.extra.Residence; -import it.gov.pagopa.admissibility.dto.rule.AutomatedCriteriaDTO; -import it.gov.pagopa.admissibility.model.InitiativeConfig; -import it.gov.pagopa.admissibility.model.IseeTypologyEnum; -import it.gov.pagopa.admissibility.test.fakers.CriteriaCodeConfigFaker; -import it.gov.pagopa.common.utils.TestUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.messaging.Message; -import org.springframework.messaging.support.MessageBuilder; -import org.springframework.test.context.TestPropertySource; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.Period; -import java.util.List; - -@TestPropertySource(properties = { - "logging.level.it.gov.pagopa.admissibility.service.AuthoritiesDataRetrieverServiceImpl=WARN", -}) -@SuppressWarnings({"squid:S3577", "NewClassNamingConvention"}) -class AuthoritiesDataRetrieverServiceIntegrationTestDeprecated extends BaseIntegrationTest { - private static final IseeTypologyEnum ISEE_TYPE = IseeTypologyEnum.ORDINARIO; - - @Autowired - private AuthoritiesDataRetrieverService authoritiesDataRetrieverService; - - private OnboardingDTO onboardingDTO; - private InitiativeConfig initiativeConfig; - private Message message; - - @BeforeAll - static void configureWiremock() { - BaseIntegrationTest.configureServerWiremockBeforeAll(false, false); - } - - @BeforeEach - void setUp() { - onboardingDTO = OnboardingDTO.builder() - .userId("userId_1") - .initiativeId("INITIATIVEID") - .tc(true) - .status("STATUS") - .pdndAccept(true) - .tcAcceptTimestamp(LocalDateTime.of(2022, 10, 2, 10, 0, 0)) - .criteriaConsensusTimestamp(LocalDateTime.of(2022, 10, 2, 10, 0, 0)) - .build(); - - LocalDate now = LocalDate.now(); - initiativeConfig = InitiativeConfig.builder() - .initiativeId("INITIATIVEID") - .initiativeName("INITITIATIVE_NAME") - .organizationId("ORGANIZATIONID") - .status("STATUS") - .startDate(now) - .endDate(now) - .initiativeBudget(new BigDecimal("100")) - .beneficiaryInitiativeBudget(BigDecimal.TEN) - .rankingInitiative(Boolean.TRUE) - .automatedCriteria(List.of( - AutomatedCriteriaDTO.builder().code(CriteriaCodeConfigFaker.CRITERIA_CODE_ISEE).iseeTypes(List.of(ISEE_TYPE)).build() - )) - .automatedCriteriaCodes(List.of("ISEE", "RESIDENCE", "BIRTHDATE")) - .build(); - - message = MessageBuilder.withPayload(TestUtils.jsonSerializer(onboardingDTO)).build(); - } - - @Test - void test() { - OnboardingDTO result = authoritiesDataRetrieverService.retrieve(onboardingDTO, initiativeConfig, message).block(); - - Residence expectedResidence = Residence.builder() - .postalCode("41026") - .province("MO") - .city("PAVULLO NEL FRIGNANO") - .cityCouncil("PAVULLO NEL FRIGNANO") - .build(); - BirthDate expectedBirthDate = BirthDate.builder() - .year("1990") - .age(Period.between(LocalDate.of(1990, 1, 1), LocalDate.now()).getYears()) // 2023-1970=53 - .build(); - - Assertions.assertNotNull(result); - Assertions.assertEquals(BigDecimal.valueOf(10000), result.getIsee()); - Assertions.assertEquals(expectedResidence, result.getResidence()); - Assertions.assertEquals(expectedBirthDate, result.getBirthDate()); - } -} From 556ec24573ea43571448491832f21e1780f00b66 Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Thu, 29 Feb 2024 15:23:10 +0100 Subject: [PATCH 09/16] IDP-2293 updated tests --- ...AnprC001RestClientImplIntegrationTest.java | 468 ++++++++---------- .../service/AnprC001RestClientSSLKOTest.java | 72 +-- 2 files changed, 240 insertions(+), 300 deletions(-) diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientImplIntegrationTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientImplIntegrationTest.java index 2b348944..ad486abf 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientImplIntegrationTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientImplIntegrationTest.java @@ -1,264 +1,204 @@ -//package it.gov.pagopa.admissibility.connector.rest.anpr.service; -// -//import com.fasterxml.jackson.core.JsonProcessingException; -//import com.fasterxml.jackson.databind.ObjectMapper; -//import com.google.common.cache.Cache; -//import it.gov.pagopa.admissibility.config.PagoPaAnprPdndConfig; -//import it.gov.pagopa.admissibility.connector.repository.CustomSequenceGeneratorRepository; -//import it.gov.pagopa.admissibility.connector.rest.anpr.config.AnprC001ServiceConfig; -//import it.gov.pagopa.admissibility.connector.rest.anpr.config.AnprConfig; -//import it.gov.pagopa.admissibility.generated.openapi.pdnd.residence.assessment.client.dto.RispostaE002OKDTO; -//import it.gov.pagopa.admissibility.model.PdndInitiativeConfig; -//import it.gov.pagopa.common.reactive.pdnd.config.PdndConfig; -//import it.gov.pagopa.common.reactive.pdnd.exception.PdndServiceTooManyRequestException; -//import it.gov.pagopa.common.reactive.pdnd.service.PdndRestClient; -//import it.gov.pagopa.common.reactive.rest.config.WebClientConfig; -//import it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest; -//import it.gov.pagopa.common.utils.TestUtils; -//import lombok.SneakyThrows; -//import org.junit.jupiter.api.Assertions; -//import org.junit.jupiter.api.BeforeEach; -//import org.junit.jupiter.api.Test; -//import org.junit.jupiter.api.extension.ExtendWith; -//import org.mockito.Mock; -//import org.mockito.Mockito; -//import org.mockito.junit.jupiter.MockitoExtension; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.boot.test.mock.mockito.MockBean; -//import org.springframework.test.context.ContextConfiguration; -//import org.springframework.test.context.TestPropertySource; -//import org.springframework.util.ReflectionUtils; -//import org.springframework.web.reactive.function.client.WebClient; -//import reactor.core.publisher.Mono; -// -//import java.lang.reflect.Field; -// -//import static it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest.WIREMOCK_TEST_PROP2BASEPATH_SECURE_MAP_PREFIX; -// -////@TestPropertySource(properties = { -//// "logging.level.it.gov.pagopa.admissibility.connector.rest.anpr.service.AnprC001RestClientImpl=WARN", -//// -//// "app.anpr.config.https-config.enabled=true", -//// // cert and key configured inside wiremockKeyStore.p12 -//// "app.anpr.config.https-config.cert=-----BEGIN CERTIFICATE-----\\nMIIDnzCCAoegAwIBAgIUJ8/0z+sR6Llr9FcIGoc5nvZQydgwDQYJKoZIhvcNAQEL\\nBQAwXzELMAkGA1UEBhMCSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUx\\nDjAMBgNVBAoMBUlEUEFZMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxo\\nb3N0MB4XDTIyMTEwOTE1MTI0NFoXDTMyMDkxNzE1MTI0NFowXzELMAkGA1UEBhMC\\nSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUxDjAMBgNVBAoMBUlEUEFZ\\nMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG\\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEArDOJKswwCaKdYJbaHZz3bgEIl7z1ArZpNI54\\nZGaXcRitiwjr/W9fenW69mG7IAlITuPtaIu4iggXTcSRuaulres2EvuP7KjL0tfo\\nx/PstqaMZzLF8wOYfJE4iJ8ffcQL67LJ3/Wwn2FhYVV+4D2AYW8QPdRm406HJG7b\\nNKLmdM9AFUQp6zoTvNegyWQyAfH40i72UopltDubcAykD6YgkRctCtKd8h/BRpIR\\ntMn0AGLM/o5qwYu+eCAy8/7Ppj3HzCwHkDOJad/g2pRj4soJdvn5rP6TM4OVtZ7V\\nehxionkaccBPcyDGSrIo5837XYaGv3r7Rn0rCplfxnU4Gtmd5wIDAQABo1MwUTAd\\nBgNVHQ4EFgQUPYfJeHRHwSLmcueB8jUQSHUReVIwHwYDVR0jBBgwFoAUPYfJeHRH\\nwSLmcueB8jUQSHUReVIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\\nAQEAK34LEHSVM44Wwbs9nKDKeQTRGosdd+gQSrqGf3nI0vkhckuaoYPnuFKi+eo2\\nr+J6xXgqhQfrvhXnYxNEJr9U+9ELBc3IjG6bTUS6HyWhu2PJCeckxQJqonVntl99\\njmEr4G7QJeDc9oJmC0NJqBmQS/D0tMxChNWpYe1AoGXwqc4S6NTd3x2Z8THzv8du\\nMMn7+1f/VOWe7/Iuuvx5DHN2JFi0lvhMqwglIweGn/qLGB0+r9GM+QlfGuZvUey2\\nx3C0DLQnNIkNKktGjaNjCmpZcd9SIVi6TOPpR+AxlIddYvUXu4GYVXyfDPgzPeha\\nJDiI4WMkIMmYSzhMc/lfuDMGow==\\n-----END CERTIFICATE-----", -//// "app.anpr.config.https-config.key=-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCsM4kqzDAJop1g\\nltodnPduAQiXvPUCtmk0jnhkZpdxGK2LCOv9b196dbr2YbsgCUhO4+1oi7iKCBdN\\nxJG5q6Wt6zYS+4/sqMvS1+jH8+y2poxnMsXzA5h8kTiInx99xAvrssnf9bCfYWFh\\nVX7gPYBhbxA91GbjTockbts0ouZ0z0AVRCnrOhO816DJZDIB8fjSLvZSimW0O5tw\\nDKQPpiCRFy0K0p3yH8FGkhG0yfQAYsz+jmrBi754IDLz/s+mPcfMLAeQM4lp3+Da\\nlGPiygl2+fms/pMzg5W1ntV6HGKieRpxwE9zIMZKsijnzftdhoa/evtGfSsKmV/G\\ndTga2Z3nAgMBAAECggEAEC6FmMJ4Tyd7T3zNgVPjQnCRbKTihz858qjislibqZKO\\nmE6d0oJ5P+o5R/bWHUQSCevMPvNGQ55QBkxO/1ocZxP/0FfYZf5UrPsCEmwfFejf\\nr8DrLhNr7GS/IcOGM4zNK/hwlP2i+88sVfexRQQygLVtmsnPY1PZSjiqm68lJdu+\\naP8TYM10y1aeiYnfuUYvnvXJFXeTEockhaUJTmeIQNbbUy+pyJ0mAPASPtXRLr8h\\nUflutICnWcx4v/qkCn1jmHw+NMA4q7hOH7UuOAqj53FqGMN+IWfjMmmYoQ7MVURx\\n8CrnEtlCOua+C8EEIFL2ylvV7X0cv/DqCJLVQoegsQKBgQDLzMaAjNgD8xSXp+Gj\\nbeeUsSGptEaGMuA89AzyTnCyvU9a1HGwDAghoQPae+pVk7R5uokojWkBVzP/kKxv\\nZldGwPOegUUdBLS4yJML+OkqtoCgf3Mbcozm5dVYtx7bYdhh3PswzRmn/h/YjEAz\\n+/mxi6dJir0k0Nd4YNtQbzBctwKBgQDYTtSmJvVQdOHnzqA/LRmMF1l+HaqLuDfu\\nB4rDlxCdDfOAvHqz+3YapP3B4MQuz29TSDqwAnzoN2XZX5B6g/jKauWpAwZkFXuO\\nfqcfNG/+MewTcHIYNm+EtgXtIsnCXDfAeXdQapzNsOX+XSF/aWcgGHg18xOBPt0R\\n7Aoa/h34UQKBgQCsCzGjwcJ2CxXeNPYxfg1ao/HUDoDet0I/kpL/VqKi8Vd1SRS0\\nVmPi58eWALfBCJD5ljRFjKMRY6lc3KgE3vNconTG4UAUEC30NDaWi8liqnCJjS4C\\nBMDYBzwEyYn+D2qYqvFOsEYxYEFIEJX+jH+sl0VguwOTec38LF/YVhUQnwKBgG5u\\n2Kw3SZkZA1ioqjF24gsexKbZmH+avps8qICw+F9mhwIbt/15jVOPFqrMCPzpFKoN\\nP0ErFAAugEYZPxb9l6AoMTY3gCTKvvkB+mq5B9BcRm2qQ+XOrOKxV5c44o7jK+eN\\nW/fnZkSxYsqZW4fEFU1SkNTiU/vxT0ZeHs6nHD/xAoGAOIqaqQnJfGj/wLo3Z9o5\\n/Oxu1zTPGZC6SqpdygCjlQ0kQ8Bp0LV7nL06/VCHAHI2lF12xApRnFk7GY3xyqK8\\nnYxeRASCj3GGmLupGshtfCtDBeysE2h7kj3Bo0d6g1Ye+j8BUZuZaZm6WNlo7cgE\\nNLHn1k0IpmXFOiFa1Y1D6Bc=\\n-----END PRIVATE KEY-----", -//// -//// "app.anpr.config.https-config.mutualAuthEnabled=true", -//// // Wiremock configured to use same keystore: wiremockKeyStore.p12 -//// "app.anpr.config.https-config.trustCertificatesCollection=-----BEGIN CERTIFICATE-----\\nMIIDnzCCAoegAwIBAgIUJ8/0z+sR6Llr9FcIGoc5nvZQydgwDQYJKoZIhvcNAQEL\\nBQAwXzELMAkGA1UEBhMCSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUx\\nDjAMBgNVBAoMBUlEUEFZMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxo\\nb3N0MB4XDTIyMTEwOTE1MTI0NFoXDTMyMDkxNzE1MTI0NFowXzELMAkGA1UEBhMC\\nSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUxDjAMBgNVBAoMBUlEUEFZ\\nMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG\\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEArDOJKswwCaKdYJbaHZz3bgEIl7z1ArZpNI54\\nZGaXcRitiwjr/W9fenW69mG7IAlITuPtaIu4iggXTcSRuaulres2EvuP7KjL0tfo\\nx/PstqaMZzLF8wOYfJE4iJ8ffcQL67LJ3/Wwn2FhYVV+4D2AYW8QPdRm406HJG7b\\nNKLmdM9AFUQp6zoTvNegyWQyAfH40i72UopltDubcAykD6YgkRctCtKd8h/BRpIR\\ntMn0AGLM/o5qwYu+eCAy8/7Ppj3HzCwHkDOJad/g2pRj4soJdvn5rP6TM4OVtZ7V\\nehxionkaccBPcyDGSrIo5837XYaGv3r7Rn0rCplfxnU4Gtmd5wIDAQABo1MwUTAd\\nBgNVHQ4EFgQUPYfJeHRHwSLmcueB8jUQSHUReVIwHwYDVR0jBBgwFoAUPYfJeHRH\\nwSLmcueB8jUQSHUReVIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\\nAQEAK34LEHSVM44Wwbs9nKDKeQTRGosdd+gQSrqGf3nI0vkhckuaoYPnuFKi+eo2\\nr+J6xXgqhQfrvhXnYxNEJr9U+9ELBc3IjG6bTUS6HyWhu2PJCeckxQJqonVntl99\\njmEr4G7QJeDc9oJmC0NJqBmQS/D0tMxChNWpYe1AoGXwqc4S6NTd3x2Z8THzv8du\\nMMn7+1f/VOWe7/Iuuvx5DHN2JFi0lvhMqwglIweGn/qLGB0+r9GM+QlfGuZvUey2\\nx3C0DLQnNIkNKktGjaNjCmpZcd9SIVi6TOPpR+AxlIddYvUXu4GYVXyfDPgzPeha\\nJDiI4WMkIMmYSzhMc/lfuDMGow==\\n-----END CERTIFICATE-----", -//////}) -//@ContextConfiguration(classes = { -//// AnprC001RestClientImpl.class, -//// AnprC001ServiceConfig.class, -//// AnprConfig.class, -// WebClientConfig.class -//}) -////@ContextConfiguration(classes = { -//// AnprC001RestClientImpl.class, -////// AnprC001ServiceConfig.class, -////// AnprConfig.class, -//// WebClientConfig.class}) -//@TestPropertySource( -// properties = { -// WIREMOCK_TEST_PROP2BASEPATH_SECURE_MAP_PREFIX + "app.anpr.config.base-url=anpr/", -// -// "logging.level.it.gov.pagopa.admissibility.connector.rest.anpr.service.AnprC001RestClientImpl=WARN", -// -// "app.anpr.config.https-config.enabled=true", -// // cert and key configured inside wiremockKeyStore.p12 -// "app.anpr.config.https-config.cert=-----BEGIN CERTIFICATE-----\\nMIIDnzCCAoegAwIBAgIUJ8/0z+sR6Llr9FcIGoc5nvZQydgwDQYJKoZIhvcNAQEL\\nBQAwXzELMAkGA1UEBhMCSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUx\\nDjAMBgNVBAoMBUlEUEFZMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxo\\nb3N0MB4XDTIyMTEwOTE1MTI0NFoXDTMyMDkxNzE1MTI0NFowXzELMAkGA1UEBhMC\\nSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUxDjAMBgNVBAoMBUlEUEFZ\\nMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG\\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEArDOJKswwCaKdYJbaHZz3bgEIl7z1ArZpNI54\\nZGaXcRitiwjr/W9fenW69mG7IAlITuPtaIu4iggXTcSRuaulres2EvuP7KjL0tfo\\nx/PstqaMZzLF8wOYfJE4iJ8ffcQL67LJ3/Wwn2FhYVV+4D2AYW8QPdRm406HJG7b\\nNKLmdM9AFUQp6zoTvNegyWQyAfH40i72UopltDubcAykD6YgkRctCtKd8h/BRpIR\\ntMn0AGLM/o5qwYu+eCAy8/7Ppj3HzCwHkDOJad/g2pRj4soJdvn5rP6TM4OVtZ7V\\nehxionkaccBPcyDGSrIo5837XYaGv3r7Rn0rCplfxnU4Gtmd5wIDAQABo1MwUTAd\\nBgNVHQ4EFgQUPYfJeHRHwSLmcueB8jUQSHUReVIwHwYDVR0jBBgwFoAUPYfJeHRH\\nwSLmcueB8jUQSHUReVIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\\nAQEAK34LEHSVM44Wwbs9nKDKeQTRGosdd+gQSrqGf3nI0vkhckuaoYPnuFKi+eo2\\nr+J6xXgqhQfrvhXnYxNEJr9U+9ELBc3IjG6bTUS6HyWhu2PJCeckxQJqonVntl99\\njmEr4G7QJeDc9oJmC0NJqBmQS/D0tMxChNWpYe1AoGXwqc4S6NTd3x2Z8THzv8du\\nMMn7+1f/VOWe7/Iuuvx5DHN2JFi0lvhMqwglIweGn/qLGB0+r9GM+QlfGuZvUey2\\nx3C0DLQnNIkNKktGjaNjCmpZcd9SIVi6TOPpR+AxlIddYvUXu4GYVXyfDPgzPeha\\nJDiI4WMkIMmYSzhMc/lfuDMGow==\\n-----END CERTIFICATE-----", -// "app.anpr.config.https-config.key=-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCsM4kqzDAJop1g\\nltodnPduAQiXvPUCtmk0jnhkZpdxGK2LCOv9b196dbr2YbsgCUhO4+1oi7iKCBdN\\nxJG5q6Wt6zYS+4/sqMvS1+jH8+y2poxnMsXzA5h8kTiInx99xAvrssnf9bCfYWFh\\nVX7gPYBhbxA91GbjTockbts0ouZ0z0AVRCnrOhO816DJZDIB8fjSLvZSimW0O5tw\\nDKQPpiCRFy0K0p3yH8FGkhG0yfQAYsz+jmrBi754IDLz/s+mPcfMLAeQM4lp3+Da\\nlGPiygl2+fms/pMzg5W1ntV6HGKieRpxwE9zIMZKsijnzftdhoa/evtGfSsKmV/G\\ndTga2Z3nAgMBAAECggEAEC6FmMJ4Tyd7T3zNgVPjQnCRbKTihz858qjislibqZKO\\nmE6d0oJ5P+o5R/bWHUQSCevMPvNGQ55QBkxO/1ocZxP/0FfYZf5UrPsCEmwfFejf\\nr8DrLhNr7GS/IcOGM4zNK/hwlP2i+88sVfexRQQygLVtmsnPY1PZSjiqm68lJdu+\\naP8TYM10y1aeiYnfuUYvnvXJFXeTEockhaUJTmeIQNbbUy+pyJ0mAPASPtXRLr8h\\nUflutICnWcx4v/qkCn1jmHw+NMA4q7hOH7UuOAqj53FqGMN+IWfjMmmYoQ7MVURx\\n8CrnEtlCOua+C8EEIFL2ylvV7X0cv/DqCJLVQoegsQKBgQDLzMaAjNgD8xSXp+Gj\\nbeeUsSGptEaGMuA89AzyTnCyvU9a1HGwDAghoQPae+pVk7R5uokojWkBVzP/kKxv\\nZldGwPOegUUdBLS4yJML+OkqtoCgf3Mbcozm5dVYtx7bYdhh3PswzRmn/h/YjEAz\\n+/mxi6dJir0k0Nd4YNtQbzBctwKBgQDYTtSmJvVQdOHnzqA/LRmMF1l+HaqLuDfu\\nB4rDlxCdDfOAvHqz+3YapP3B4MQuz29TSDqwAnzoN2XZX5B6g/jKauWpAwZkFXuO\\nfqcfNG/+MewTcHIYNm+EtgXtIsnCXDfAeXdQapzNsOX+XSF/aWcgGHg18xOBPt0R\\n7Aoa/h34UQKBgQCsCzGjwcJ2CxXeNPYxfg1ao/HUDoDet0I/kpL/VqKi8Vd1SRS0\\nVmPi58eWALfBCJD5ljRFjKMRY6lc3KgE3vNconTG4UAUEC30NDaWi8liqnCJjS4C\\nBMDYBzwEyYn+D2qYqvFOsEYxYEFIEJX+jH+sl0VguwOTec38LF/YVhUQnwKBgG5u\\n2Kw3SZkZA1ioqjF24gsexKbZmH+avps8qICw+F9mhwIbt/15jVOPFqrMCPzpFKoN\\nP0ErFAAugEYZPxb9l6AoMTY3gCTKvvkB+mq5B9BcRm2qQ+XOrOKxV5c44o7jK+eN\\nW/fnZkSxYsqZW4fEFU1SkNTiU/vxT0ZeHs6nHD/xAoGAOIqaqQnJfGj/wLo3Z9o5\\n/Oxu1zTPGZC6SqpdygCjlQ0kQ8Bp0LV7nL06/VCHAHI2lF12xApRnFk7GY3xyqK8\\nnYxeRASCj3GGmLupGshtfCtDBeysE2h7kj3Bo0d6g1Ye+j8BUZuZaZm6WNlo7cgE\\nNLHn1k0IpmXFOiFa1Y1D6Bc=\\n-----END PRIVATE KEY-----", -// -// "app.anpr.config.https-config.mutualAuthEnabled=true", -// // Wiremock configured to use same keystore: wiremockKeyStore.p12 -// -// } -//) -//@ExtendWith(MockitoExtension.class) -//public class AnprC001RestClientImplIntegrationTest extends BaseWireMockTest { -// -// public static final String FISCAL_CODE_OK = "CF_OK"; -// public static final String FISCAL_CODE_NOTFOUND = "CF_NOT_FOUND"; -// public static final String FISCAL_CODE_INVALIDREQUEST = "CF_INVALID_REQUEST"; -// public static final String FISCAL_CODE_TOOMANYREQUESTS = "CF_ANPR_TOO_MANY_REQUESTS"; -// -// public static final PdndInitiativeConfig PDND_INITIATIVE_CONFIG = new PdndInitiativeConfig( -// "CLIENTID", -// "KID", -// "PURPOSEID" -// ); -// -// @MockBean -// private ObjectMapper objectMapper; -// @MockBean -// private PdndRestClient pdndRestClient; -// @Mock -// private PdndConfig pdndConfig; -// @Mock -// private AnprConfig anprConfig; -// @Mock -// private AnprC001ServiceConfig anprC001ServiceConfig; -// @Mock -// private AnprSignAlgorithmRetriever anprSignAlgorithmRetriever; -// @Autowired -// private WebClientConfig webClientConfig; -// @Mock -// private CustomSequenceGeneratorRepository customSequenceGeneratorRepository; -//// @MockBean -//// private BasePdndServiceProviderConfig basePdndServiceProviderConfig; -// -// private AnprC001RestClientImpl anprC001RestClient; -//// @Autowired -//// private PagoPaAnprPdndConfig pagoPaAnprPdndConfig; -//// @Autowired -//// private CustomSequenceGeneratorRepository sequenceGeneratorRepository; -// @BeforeEach -// void clearCache() throws IllegalAccessException { -// anprC001RestClient = new AnprC001RestClientImpl(TestUtils.objectMapper,pdndConfig,anprConfig,anprC001ServiceConfig,anprSignAlgorithmRetriever,pdndRestClient, webClientConfig.webClientConfigure(),webClientConfig.httpClientConfig(),customSequenceGeneratorRepository ); -// -// Field cacheField = ReflectionUtils.findField(anprC001RestClient.getClass(), "pdndAuthDataCache"); -// Assertions.assertNotNull(cacheField); -// cacheField.setAccessible(true); -// Cache cache = (Cache) cacheField.get(anprC001RestClient); -// cache.invalidateAll(); -// -// } -// -// @Test -// void getResidenceAssessment(){ -// // When -// RispostaE002OKDTO result = anprC001RestClient.invoke(FISCAL_CODE_OK, PDND_INITIATIVE_CONFIG).block(); -// -// // Then -// RispostaE002OKDTO expectedResponse = buildExpectedResponse(); -// expectedResponse.getListaSoggetti().getDatiSoggetto().get(0).getGeneralita().getCodiceFiscale().setCodFiscale(FISCAL_CODE_OK); -// Assertions.assertEquals(expectedResponse, result); -// -// // accessToken cached for each pdndInitiativeConfig -// RispostaE002OKDTO result2ndInvoke = anprC001RestClient.invoke(FISCAL_CODE_OK, PDND_INITIATIVE_CONFIG).block(); -// Assertions.assertEquals(expectedResponse, result2ndInvoke); -// -// Mockito.verify(pdndRestClient).createToken(Mockito.eq(PDND_INITIATIVE_CONFIG.getClientId()), Mockito.anyString()); -// -// // new clientId -// PdndInitiativeConfig pdndInitiativeConfig2 = new PdndInitiativeConfig( -// "CLIENTID2", -// "KID", -// "PURPOSEID" -// ); -// RispostaE002OKDTO resultNewClientId = anprC001RestClient.invoke(FISCAL_CODE_OK, pdndInitiativeConfig2).block(); -// Assertions.assertEquals(expectedResponse, resultNewClientId); -// -// Mockito.verify(pdndRestClient, Mockito.times(2)).createToken(Mockito.anyString(), Mockito.anyString()); -// } -// -// @Test -// void testNotFound(){ -// //When -// RispostaE002OKDTO result = anprC001RestClient.invoke(FISCAL_CODE_NOTFOUND, PDND_INITIATIVE_CONFIG).block(); -// -// // Then -// Assertions.assertNotNull(result); -// Assertions.assertNull(result.getListaSoggetti()); -// } -// -// @Test -// void testInvalidRequest(){ -// Mono mono = anprC001RestClient.invoke(FISCAL_CODE_INVALIDREQUEST, PDND_INITIATIVE_CONFIG); -// IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class, mono::block); -// Assertions.assertTrue(exception.getMessage().startsWith("[PDND_SERVICE_INVOKE] Something went wrong when invoking PDND service https://modipa-val.anpr.interno.it/govway/rest/in/MinInternoPortaANPR/C001-servizioNotifica/v1: 400 Bad Request")); -// } -// -// @Test -// void testTooManyRequests(){ -// Mono mono = anprC001RestClient.invoke(FISCAL_CODE_TOOMANYREQUESTS, PDND_INITIATIVE_CONFIG); -// Assertions.assertThrows(PdndServiceTooManyRequestException.class, mono::block); -// } -// -// @Test -// @SneakyThrows -// void objectMapperException(){ -// // Given -// Mockito.when(objectMapper.writeValueAsString(Mockito.any())).thenThrow(JsonProcessingException.class); -// -// // When -// try { -// anprC001RestClient.invoke(FISCAL_CODE_OK, PDND_INITIATIVE_CONFIG).block(); -// }catch (Exception e){ -// // Then -// Assertions.assertTrue(e instanceof IllegalStateException); -// } -// } -// -// public static RispostaE002OKDTO buildExpectedResponse() { -// try { -// return TestUtils.objectMapper.readValue(""" -// { -// "listaSoggetti": { -// "datiSoggetto": [ -// { -// "generalita": { -// "codiceFiscale": { -// "codFiscale": "STTSGT90A01H501J", -// "validitaCF": "9" -// }, -// "cognome": "SETTIMO", -// "dataNascita": "1990-01-01", -// "idSchedaSoggettoANPR": "2775118", -// "luogoNascita": { -// "comune": { -// "codiceIstat": "058091", -// "nomeComune": "ROMA", -// "siglaProvinciaIstat": "RM" -// } -// }, -// "nome": "SOGGETTO", -// "sesso": "M" -// }, -// "identificativi": { -// "idANPR": "AF41450AS" -// }, -// "infoSoggettoEnte": [ -// { -// "chiave": "Verifica esistenza in vita", -// "id": "1003", -// "valore": "S" -// } -// ], -// "residenza": [ -// { -// "indirizzo": { -// "cap": "41026", -// "comune": { -// "codiceIstat": "036030", -// "nomeComune": "PAVULLO NEL FRIGNANO", -// "siglaProvinciaIstat": "MO" -// }, -// "numeroCivico": { -// "civicoInterno": { -// "interno1": "3", -// "scala": "B4" -// }, -// "numero": "55" -// }, -// "toponimo": { -// "denominazioneToponimo": "AMERIGO VESPUCCI", -// "specie": "VIA", -// "specieFonte": "1" -// } -// }, -// "tipoIndirizzo": "1" -// } -// ] -// } -// ] -// }, -// "idOperazioneANPR": "58370927" -// } -// """, RispostaE002OKDTO.class); -// } catch (JsonProcessingException e) { -// throw new IllegalStateException("Cannot read expected response", e); -// } -// } -// -//} \ No newline at end of file +package it.gov.pagopa.admissibility.connector.rest.anpr.service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.cache.Cache; +import it.gov.pagopa.admissibility.BaseIntegrationTest; +import it.gov.pagopa.admissibility.generated.openapi.pdnd.residence.assessment.client.dto.RispostaE002OKDTO; +import it.gov.pagopa.admissibility.model.PdndInitiativeConfig; +import it.gov.pagopa.common.reactive.pdnd.exception.PdndServiceTooManyRequestException; +import it.gov.pagopa.common.reactive.pdnd.service.PdndRestClient; +import it.gov.pagopa.common.utils.TestUtils; +import lombok.SneakyThrows; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.test.context.TestPropertySource; +import org.springframework.util.ReflectionUtils; +import reactor.core.publisher.Mono; + +import java.lang.reflect.Field; + +@TestPropertySource(properties = { + "logging.level.it.gov.pagopa.admissibility.connector.rest.anpr.service.AnprC001RestClientImpl=WARN", + + "app.anpr.config.https-config.enabled=true", + // cert and key configured inside wiremockKeyStore.p12 + "app.anpr.config.https-config.cert=-----BEGIN CERTIFICATE-----\\nMIIDnzCCAoegAwIBAgIUJ8/0z+sR6Llr9FcIGoc5nvZQydgwDQYJKoZIhvcNAQEL\\nBQAwXzELMAkGA1UEBhMCSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUx\\nDjAMBgNVBAoMBUlEUEFZMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxo\\nb3N0MB4XDTIyMTEwOTE1MTI0NFoXDTMyMDkxNzE1MTI0NFowXzELMAkGA1UEBhMC\\nSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUxDjAMBgNVBAoMBUlEUEFZ\\nMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG\\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEArDOJKswwCaKdYJbaHZz3bgEIl7z1ArZpNI54\\nZGaXcRitiwjr/W9fenW69mG7IAlITuPtaIu4iggXTcSRuaulres2EvuP7KjL0tfo\\nx/PstqaMZzLF8wOYfJE4iJ8ffcQL67LJ3/Wwn2FhYVV+4D2AYW8QPdRm406HJG7b\\nNKLmdM9AFUQp6zoTvNegyWQyAfH40i72UopltDubcAykD6YgkRctCtKd8h/BRpIR\\ntMn0AGLM/o5qwYu+eCAy8/7Ppj3HzCwHkDOJad/g2pRj4soJdvn5rP6TM4OVtZ7V\\nehxionkaccBPcyDGSrIo5837XYaGv3r7Rn0rCplfxnU4Gtmd5wIDAQABo1MwUTAd\\nBgNVHQ4EFgQUPYfJeHRHwSLmcueB8jUQSHUReVIwHwYDVR0jBBgwFoAUPYfJeHRH\\nwSLmcueB8jUQSHUReVIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\\nAQEAK34LEHSVM44Wwbs9nKDKeQTRGosdd+gQSrqGf3nI0vkhckuaoYPnuFKi+eo2\\nr+J6xXgqhQfrvhXnYxNEJr9U+9ELBc3IjG6bTUS6HyWhu2PJCeckxQJqonVntl99\\njmEr4G7QJeDc9oJmC0NJqBmQS/D0tMxChNWpYe1AoGXwqc4S6NTd3x2Z8THzv8du\\nMMn7+1f/VOWe7/Iuuvx5DHN2JFi0lvhMqwglIweGn/qLGB0+r9GM+QlfGuZvUey2\\nx3C0DLQnNIkNKktGjaNjCmpZcd9SIVi6TOPpR+AxlIddYvUXu4GYVXyfDPgzPeha\\nJDiI4WMkIMmYSzhMc/lfuDMGow==\\n-----END CERTIFICATE-----", + "app.anpr.config.https-config.key=-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCsM4kqzDAJop1g\\nltodnPduAQiXvPUCtmk0jnhkZpdxGK2LCOv9b196dbr2YbsgCUhO4+1oi7iKCBdN\\nxJG5q6Wt6zYS+4/sqMvS1+jH8+y2poxnMsXzA5h8kTiInx99xAvrssnf9bCfYWFh\\nVX7gPYBhbxA91GbjTockbts0ouZ0z0AVRCnrOhO816DJZDIB8fjSLvZSimW0O5tw\\nDKQPpiCRFy0K0p3yH8FGkhG0yfQAYsz+jmrBi754IDLz/s+mPcfMLAeQM4lp3+Da\\nlGPiygl2+fms/pMzg5W1ntV6HGKieRpxwE9zIMZKsijnzftdhoa/evtGfSsKmV/G\\ndTga2Z3nAgMBAAECggEAEC6FmMJ4Tyd7T3zNgVPjQnCRbKTihz858qjislibqZKO\\nmE6d0oJ5P+o5R/bWHUQSCevMPvNGQ55QBkxO/1ocZxP/0FfYZf5UrPsCEmwfFejf\\nr8DrLhNr7GS/IcOGM4zNK/hwlP2i+88sVfexRQQygLVtmsnPY1PZSjiqm68lJdu+\\naP8TYM10y1aeiYnfuUYvnvXJFXeTEockhaUJTmeIQNbbUy+pyJ0mAPASPtXRLr8h\\nUflutICnWcx4v/qkCn1jmHw+NMA4q7hOH7UuOAqj53FqGMN+IWfjMmmYoQ7MVURx\\n8CrnEtlCOua+C8EEIFL2ylvV7X0cv/DqCJLVQoegsQKBgQDLzMaAjNgD8xSXp+Gj\\nbeeUsSGptEaGMuA89AzyTnCyvU9a1HGwDAghoQPae+pVk7R5uokojWkBVzP/kKxv\\nZldGwPOegUUdBLS4yJML+OkqtoCgf3Mbcozm5dVYtx7bYdhh3PswzRmn/h/YjEAz\\n+/mxi6dJir0k0Nd4YNtQbzBctwKBgQDYTtSmJvVQdOHnzqA/LRmMF1l+HaqLuDfu\\nB4rDlxCdDfOAvHqz+3YapP3B4MQuz29TSDqwAnzoN2XZX5B6g/jKauWpAwZkFXuO\\nfqcfNG/+MewTcHIYNm+EtgXtIsnCXDfAeXdQapzNsOX+XSF/aWcgGHg18xOBPt0R\\n7Aoa/h34UQKBgQCsCzGjwcJ2CxXeNPYxfg1ao/HUDoDet0I/kpL/VqKi8Vd1SRS0\\nVmPi58eWALfBCJD5ljRFjKMRY6lc3KgE3vNconTG4UAUEC30NDaWi8liqnCJjS4C\\nBMDYBzwEyYn+D2qYqvFOsEYxYEFIEJX+jH+sl0VguwOTec38LF/YVhUQnwKBgG5u\\n2Kw3SZkZA1ioqjF24gsexKbZmH+avps8qICw+F9mhwIbt/15jVOPFqrMCPzpFKoN\\nP0ErFAAugEYZPxb9l6AoMTY3gCTKvvkB+mq5B9BcRm2qQ+XOrOKxV5c44o7jK+eN\\nW/fnZkSxYsqZW4fEFU1SkNTiU/vxT0ZeHs6nHD/xAoGAOIqaqQnJfGj/wLo3Z9o5\\n/Oxu1zTPGZC6SqpdygCjlQ0kQ8Bp0LV7nL06/VCHAHI2lF12xApRnFk7GY3xyqK8\\nnYxeRASCj3GGmLupGshtfCtDBeysE2h7kj3Bo0d6g1Ye+j8BUZuZaZm6WNlo7cgE\\nNLHn1k0IpmXFOiFa1Y1D6Bc=\\n-----END PRIVATE KEY-----", + + "app.anpr.config.https-config.mutualAuthEnabled=true", + // Wiremock configured to use same keystore: wiremockKeyStore.p12 + "app.anpr.config.https-config.trustCertificatesCollection=-----BEGIN CERTIFICATE-----\\nMIIDnzCCAoegAwIBAgIUJ8/0z+sR6Llr9FcIGoc5nvZQydgwDQYJKoZIhvcNAQEL\\nBQAwXzELMAkGA1UEBhMCSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUx\\nDjAMBgNVBAoMBUlEUEFZMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxo\\nb3N0MB4XDTIyMTEwOTE1MTI0NFoXDTMyMDkxNzE1MTI0NFowXzELMAkGA1UEBhMC\\nSVQxDTALBgNVBAgMBFJPTUUxDTALBgNVBAcMBFJPTUUxDjAMBgNVBAoMBUlEUEFZ\\nMQ4wDAYDVQQLDAVJRFBBWTESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG\\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEArDOJKswwCaKdYJbaHZz3bgEIl7z1ArZpNI54\\nZGaXcRitiwjr/W9fenW69mG7IAlITuPtaIu4iggXTcSRuaulres2EvuP7KjL0tfo\\nx/PstqaMZzLF8wOYfJE4iJ8ffcQL67LJ3/Wwn2FhYVV+4D2AYW8QPdRm406HJG7b\\nNKLmdM9AFUQp6zoTvNegyWQyAfH40i72UopltDubcAykD6YgkRctCtKd8h/BRpIR\\ntMn0AGLM/o5qwYu+eCAy8/7Ppj3HzCwHkDOJad/g2pRj4soJdvn5rP6TM4OVtZ7V\\nehxionkaccBPcyDGSrIo5837XYaGv3r7Rn0rCplfxnU4Gtmd5wIDAQABo1MwUTAd\\nBgNVHQ4EFgQUPYfJeHRHwSLmcueB8jUQSHUReVIwHwYDVR0jBBgwFoAUPYfJeHRH\\nwSLmcueB8jUQSHUReVIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\\nAQEAK34LEHSVM44Wwbs9nKDKeQTRGosdd+gQSrqGf3nI0vkhckuaoYPnuFKi+eo2\\nr+J6xXgqhQfrvhXnYxNEJr9U+9ELBc3IjG6bTUS6HyWhu2PJCeckxQJqonVntl99\\njmEr4G7QJeDc9oJmC0NJqBmQS/D0tMxChNWpYe1AoGXwqc4S6NTd3x2Z8THzv8du\\nMMn7+1f/VOWe7/Iuuvx5DHN2JFi0lvhMqwglIweGn/qLGB0+r9GM+QlfGuZvUey2\\nx3C0DLQnNIkNKktGjaNjCmpZcd9SIVi6TOPpR+AxlIddYvUXu4GYVXyfDPgzPeha\\nJDiI4WMkIMmYSzhMc/lfuDMGow==\\n-----END CERTIFICATE-----", +}) +public class AnprC001RestClientImplIntegrationTest extends BaseIntegrationTest { + + public static final String FISCAL_CODE_OK = "CF_OK"; + public static final String FISCAL_CODE_NOTFOUND = "CF_NOT_FOUND"; + public static final String FISCAL_CODE_INVALIDREQUEST = "CF_INVALID_REQUEST"; + public static final String FISCAL_CODE_TOOMANYREQUESTS = "CF_ANPR_TOO_MANY_REQUESTS"; + + public static final PdndInitiativeConfig PDND_INITIATIVE_CONFIG = new PdndInitiativeConfig( + "CLIENTID", + "KID", + "PURPOSEID" + ); + + @SpyBean + private ObjectMapper objectMapper; + @SpyBean + private PdndRestClient pdndRestClient; + + @Autowired + private AnprC001RestClient anprC001RestClient; + + @BeforeEach + void clearCache() throws IllegalAccessException { + Field cacheField = ReflectionUtils.findField(anprC001RestClient.getClass(), "pdndAuthDataCache"); + Assertions.assertNotNull(cacheField); + cacheField.setAccessible(true); + Cache cache = (Cache) cacheField.get(anprC001RestClient); + cache.invalidateAll(); + } + + @Test + void getResidenceAssessment(){ + // When + RispostaE002OKDTO result = anprC001RestClient.invoke(FISCAL_CODE_OK, PDND_INITIATIVE_CONFIG).block(); + + // Then + RispostaE002OKDTO expectedResponse = buildExpectedResponse(); + expectedResponse.getListaSoggetti().getDatiSoggetto().get(0).getGeneralita().getCodiceFiscale().setCodFiscale(FISCAL_CODE_OK); + Assertions.assertEquals(expectedResponse, result); + + // accessToken cached for each pdndInitiativeConfig + RispostaE002OKDTO result2ndInvoke = anprC001RestClient.invoke(FISCAL_CODE_OK, PDND_INITIATIVE_CONFIG).block(); + Assertions.assertEquals(expectedResponse, result2ndInvoke); + + Mockito.verify(pdndRestClient).createToken(Mockito.eq(PDND_INITIATIVE_CONFIG.getClientId()), Mockito.anyString()); + + // new clientId + PdndInitiativeConfig pdndInitiativeConfig2 = new PdndInitiativeConfig( + "CLIENTID2", + "KID", + "PURPOSEID" + ); + RispostaE002OKDTO resultNewClientId = anprC001RestClient.invoke(FISCAL_CODE_OK, pdndInitiativeConfig2).block(); + Assertions.assertEquals(expectedResponse, resultNewClientId); + + Mockito.verify(pdndRestClient, Mockito.times(2)).createToken(Mockito.anyString(), Mockito.anyString()); + } + + @Test + void testNotFound(){ + //When + RispostaE002OKDTO result = anprC001RestClient.invoke(FISCAL_CODE_NOTFOUND, PDND_INITIATIVE_CONFIG).block(); + + // Then + Assertions.assertNotNull(result); + Assertions.assertNull(result.getListaSoggetti()); + } + + @Test + void testInvalidRequest(){ + Mono mono = anprC001RestClient.invoke(FISCAL_CODE_INVALIDREQUEST, PDND_INITIATIVE_CONFIG); + IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class, mono::block); + Assertions.assertTrue(exception.getMessage().startsWith("[PDND_SERVICE_INVOKE] Something went wrong when invoking PDND service https://modipa-val.anpr.interno.it/govway/rest/in/MinInternoPortaANPR/C001-servizioNotifica/v1: 400 Bad Request")); + } + + @Test + void testTooManyRequests(){ + Mono mono = anprC001RestClient.invoke(FISCAL_CODE_TOOMANYREQUESTS, PDND_INITIATIVE_CONFIG); + Assertions.assertThrows(PdndServiceTooManyRequestException.class, mono::block); + } + + @Test + @SneakyThrows + void objectMapperException(){ + // Given + Mockito.when(objectMapper.writeValueAsString(Mockito.any())).thenThrow(JsonProcessingException.class); + + // When + try { + anprC001RestClient.invoke(FISCAL_CODE_OK, PDND_INITIATIVE_CONFIG).block(); + }catch (Exception e){ + // Then + Assertions.assertTrue(e instanceof IllegalStateException); + } + } + + public static RispostaE002OKDTO buildExpectedResponse() { + try { + return TestUtils.objectMapper.readValue(""" + { + "listaSoggetti": { + "datiSoggetto": [ + { + "generalita": { + "codiceFiscale": { + "codFiscale": "STTSGT90A01H501J", + "validitaCF": "9" + }, + "cognome": "SETTIMO", + "dataNascita": "1990-01-01", + "idSchedaSoggettoANPR": "2775118", + "luogoNascita": { + "comune": { + "codiceIstat": "058091", + "nomeComune": "ROMA", + "siglaProvinciaIstat": "RM" + } + }, + "nome": "SOGGETTO", + "sesso": "M" + }, + "identificativi": { + "idANPR": "AF41450AS" + }, + "infoSoggettoEnte": [ + { + "chiave": "Verifica esistenza in vita", + "id": "1003", + "valore": "S" + } + ], + "residenza": [ + { + "indirizzo": { + "cap": "41026", + "comune": { + "codiceIstat": "036030", + "nomeComune": "PAVULLO NEL FRIGNANO", + "siglaProvinciaIstat": "MO" + }, + "numeroCivico": { + "civicoInterno": { + "interno1": "3", + "scala": "B4" + }, + "numero": "55" + }, + "toponimo": { + "denominazioneToponimo": "AMERIGO VESPUCCI", + "specie": "VIA", + "specieFonte": "1" + } + }, + "tipoIndirizzo": "1" + } + ] + } + ] + }, + "idOperazioneANPR": "58370927" + } + """, RispostaE002OKDTO.class); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Cannot read expected response", e); + } + } + +} \ No newline at end of file diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientSSLKOTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientSSLKOTest.java index 5b33b9d0..0306c6ff 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientSSLKOTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientSSLKOTest.java @@ -1,36 +1,36 @@ -//package it.gov.pagopa.admissibility.connector.rest.anpr.service; -// -//import it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest; -//import org.junit.jupiter.api.Assertions; -//import org.junit.jupiter.api.BeforeAll; -//import org.junit.jupiter.api.Test; -//import org.junit.platform.launcher.Launcher; -//import org.junit.platform.launcher.LauncherDiscoveryRequest; -//import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; -//import org.junit.platform.launcher.core.LauncherFactory; -//import org.junit.platform.launcher.listeners.SummaryGeneratingListener; -// -//import static org.junit.platform.engine.discovery.DiscoverySelectors.selectMethod; -// -//class AnprC001RestClientSSLKOTest { -// -// @BeforeAll -// static void setUp() { -// BaseWireMockTest.configureServerWiremockBeforeAll(true, false); -// } -// -// @Test -// void testKo(){ -// SummaryGeneratingListener listener = new SummaryGeneratingListener(); -// -// LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() -// .selectors(selectMethod(AnprC001RestClientImplIntegrationTest.class, "getResidenceAssessment")) -// .build(); -// Launcher launcher = LauncherFactory.create(); -// launcher.discover(request); -// launcher.registerTestExecutionListeners(listener); -// launcher.execute(request); -// -// Assertions.assertEquals(1,listener.getSummary().getTestsFailedCount()); -// } -//} \ No newline at end of file +package it.gov.pagopa.admissibility.connector.rest.anpr.service; + +import it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; +import org.junit.platform.launcher.listeners.SummaryGeneratingListener; + +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectMethod; + +class AnprC001RestClientSSLKOTest { + + @BeforeAll + static void setUp() { + BaseWireMockTest.configureServerWiremockBeforeAll(true, false); + } + + @Test + void testKo(){ + SummaryGeneratingListener listener = new SummaryGeneratingListener(); + + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() + .selectors(selectMethod(AnprC001RestClientImplIntegrationTest.class, "getResidenceAssessment")) + .build(); + Launcher launcher = LauncherFactory.create(); + launcher.discover(request); + launcher.registerTestExecutionListeners(listener); + launcher.execute(request); + + Assertions.assertEquals(1,listener.getSummary().getTestsFailedCount()); + } +} \ No newline at end of file From 26d6337d2fce0c8cc6299f70629ee28b917966fe Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Thu, 29 Feb 2024 16:05:35 +0100 Subject: [PATCH 10/16] IDP-2293 updated test --- .../rest/anpr/service/AnprC001RestClientSSLKOTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientSSLKOTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientSSLKOTest.java index 0306c6ff..95a0d1ae 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientSSLKOTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/rest/anpr/service/AnprC001RestClientSSLKOTest.java @@ -1,6 +1,6 @@ package it.gov.pagopa.admissibility.connector.rest.anpr.service; -import it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest; +import it.gov.pagopa.admissibility.BaseIntegrationTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -16,7 +16,7 @@ class AnprC001RestClientSSLKOTest { @BeforeAll static void setUp() { - BaseWireMockTest.configureServerWiremockBeforeAll(true, false); + BaseIntegrationTest.configureServerWiremockBeforeAll(true, false); } @Test From 758ec34ceb3848ca2a939ebbe6045bbf34b1862a Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Thu, 29 Feb 2024 16:18:51 +0100 Subject: [PATCH 11/16] IDP-2293 updated test --- .../inps/service/IseeConsultationSoapClientImplSSLKOTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java index 249d8607..0bfb26cf 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java @@ -1,6 +1,6 @@ package it.gov.pagopa.admissibility.connector.soap.inps.service; -import it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest; +import it.gov.pagopa.admissibility.BaseIntegrationTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -16,7 +16,7 @@ class IseeConsultationSoapClientImplSSLKOTest { @BeforeAll static void setUp() { - BaseWireMockTest.configureServerWiremockBeforeAll(true, false); + BaseIntegrationTest.configureServerWiremockBeforeAll(true, false); } @Test From a09cc80b008562ea1d6be3572207d6ea803bf2e2 Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Thu, 29 Feb 2024 17:13:50 +0100 Subject: [PATCH 12/16] IDP-2293 restored test isee --- .../inps/service/IseeConsultationSoapClientImplSSLKOTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java index 0bfb26cf..249d8607 100644 --- a/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/connector/soap/inps/service/IseeConsultationSoapClientImplSSLKOTest.java @@ -1,6 +1,6 @@ package it.gov.pagopa.admissibility.connector.soap.inps.service; -import it.gov.pagopa.admissibility.BaseIntegrationTest; +import it.gov.pagopa.common.reactive.wireMock.BaseWireMockTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -16,7 +16,7 @@ class IseeConsultationSoapClientImplSSLKOTest { @BeforeAll static void setUp() { - BaseIntegrationTest.configureServerWiremockBeforeAll(true, false); + BaseWireMockTest.configureServerWiremockBeforeAll(true, false); } @Test From 0dda7ad31f380e5986daf64c5290f465f5c0ec1e Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Thu, 29 Feb 2024 17:23:45 +0100 Subject: [PATCH 13/16] IDP-2293 updated BaseWireMockTest --- .../gov/pagopa/common/reactive/wireMock/BaseWireMockTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/it/gov/pagopa/common/reactive/wireMock/BaseWireMockTest.java b/src/test/java/it/gov/pagopa/common/reactive/wireMock/BaseWireMockTest.java index 076cc7ba..bd9bc816 100644 --- a/src/test/java/it/gov/pagopa/common/reactive/wireMock/BaseWireMockTest.java +++ b/src/test/java/it/gov/pagopa/common/reactive/wireMock/BaseWireMockTest.java @@ -134,7 +134,7 @@ public void initialize(@NonNull ConfigurableApplicationContext applicationContex setWireMockBaseMockedServicePath(applicationContext,serverWireMockExtension.getRuntimeInfo().getHttpBaseUrl(),entry); } for (Map.Entry entry : propertiesSecureMap.entrySet()) { - setWireMockBaseMockedServicePath(applicationContext,serverWireMockExtension.getRuntimeInfo().getHttpBaseUrl(),entry); + setWireMockBaseMockedServicePath(applicationContext,serverWireMockExtension.getRuntimeInfo().getHttpsBaseUrl(),entry); } System.out.printf(""" From 598fc09378177a452462ed4e10d93ded193f72a0 Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Thu, 29 Feb 2024 17:40:17 +0100 Subject: [PATCH 14/16] IDP-2293 fixed bugs --- .../mapper/AutomatedCriteria2ExtraFilterMapper.java | 2 +- src/main/java/it/gov/pagopa/common/utils/AuditLogger.java | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/it/gov/pagopa/admissibility/mapper/AutomatedCriteria2ExtraFilterMapper.java b/src/main/java/it/gov/pagopa/admissibility/mapper/AutomatedCriteria2ExtraFilterMapper.java index c972da3d..b9c9df5c 100644 --- a/src/main/java/it/gov/pagopa/admissibility/mapper/AutomatedCriteria2ExtraFilterMapper.java +++ b/src/main/java/it/gov/pagopa/admissibility/mapper/AutomatedCriteria2ExtraFilterMapper.java @@ -11,7 +11,7 @@ import org.springframework.stereotype.Service; import java.util.function.BiFunction; - +@SuppressWarnings("squid:S2637") @Service public class AutomatedCriteria2ExtraFilterMapper implements BiFunction { @Override diff --git a/src/main/java/it/gov/pagopa/common/utils/AuditLogger.java b/src/main/java/it/gov/pagopa/common/utils/AuditLogger.java index 2af8fa43..d7f0ac11 100644 --- a/src/main/java/it/gov/pagopa/common/utils/AuditLogger.java +++ b/src/main/java/it/gov/pagopa/common/utils/AuditLogger.java @@ -4,6 +4,7 @@ import java.net.InetAddress; import java.net.UnknownHostException; +import java.util.Arrays; @Slf4j(topic = "AUDIT") public class AuditLogger { @@ -25,7 +26,8 @@ private AuditLogger() { } public static void logAuditString(String pattern, String... parameters) { - log.info(pattern, (Object[]) parameters); + Object[] params = Arrays.asList(parameters).toArray(); + log.info(pattern,params); } } \ No newline at end of file From f87a3eb09064dafc130dc47efa62e171134fa3b9 Mon Sep 17 00:00:00 2001 From: Giuseppe-La-Manna Date: Fri, 1 Mar 2024 11:02:57 +0100 Subject: [PATCH 15/16] IDP-2293 updated test --- .../family/ExistentFamilyHandlerServiceTest.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/test/java/it/gov/pagopa/admissibility/service/onboarding/family/ExistentFamilyHandlerServiceTest.java b/src/test/java/it/gov/pagopa/admissibility/service/onboarding/family/ExistentFamilyHandlerServiceTest.java index c649ff2e..874c37f8 100644 --- a/src/test/java/it/gov/pagopa/admissibility/service/onboarding/family/ExistentFamilyHandlerServiceTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/service/onboarding/family/ExistentFamilyHandlerServiceTest.java @@ -8,6 +8,7 @@ import it.gov.pagopa.admissibility.dto.rule.InitiativeGeneralDTO; import it.gov.pagopa.admissibility.enums.OnboardingEvaluationStatus; import it.gov.pagopa.admissibility.enums.OnboardingFamilyEvaluationStatus; +import it.gov.pagopa.admissibility.exception.SkipAlreadyRankingFamilyOnBoardingException; import it.gov.pagopa.admissibility.exception.WaitingFamilyOnBoardingException; import it.gov.pagopa.admissibility.mapper.Onboarding2EvaluationMapper; import it.gov.pagopa.admissibility.model.InitiativeConfig; @@ -116,4 +117,17 @@ private void testCompletedFamilyOnboarding(OnboardingEvaluationStatus expectedSt Assertions.assertEquals(new Family(family.getFamilyId(), family.getMemberIds()), request.getFamily()); } + + @Test + void givenInitiativeConfigRankingWhenHandlerThenSkipAlreadyRankingFamilyOnBoardingException(){ + //Given + initiativeConfig.setRankingInitiative(true); + family.setStatus(OnboardingFamilyEvaluationStatus.ONBOARDING_OK); + + //When + Mono mono = service.handleExistentFamily(request, family, initiativeConfig, message); + + //Then + Assertions.assertThrows(SkipAlreadyRankingFamilyOnBoardingException.class,mono::block); + } } From 8aea4efb10e076f66c38911b8598c931931ee77a Mon Sep 17 00:00:00 2001 From: GiovanaSolorzano Date: Fri, 1 Mar 2024 11:06:48 +0100 Subject: [PATCH 16/16] [IDP-2293] added test for notify servicebus --- .../AdmissibilityErrorNotifierServiceImplTest.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/test/java/it/gov/pagopa/admissibility/service/AdmissibilityErrorNotifierServiceImplTest.java b/src/test/java/it/gov/pagopa/admissibility/service/AdmissibilityErrorNotifierServiceImplTest.java index c2fe876c..9056c2d9 100644 --- a/src/test/java/it/gov/pagopa/admissibility/service/AdmissibilityErrorNotifierServiceImplTest.java +++ b/src/test/java/it/gov/pagopa/admissibility/service/AdmissibilityErrorNotifierServiceImplTest.java @@ -88,6 +88,15 @@ void testNotify() { Mockito.verifyNoMoreInteractions(errorNotifierServiceMock); } + @Test + void testAdmissibility() { + Mockito.when(errorNotifierServiceMock.notify(eq(BINDER_KAFKA_TYPE), eq("ServiceBus"), + eq("admissibility-topic"), eq("admissibility-group"), eq(dummyMessage), eq(DUMMY_MESSAGE), eq(true), eq(true), any())) + .thenReturn(true); + admissibilityErrorNotifierService.notifyAdmissibility(dummyMessage,DUMMY_MESSAGE,true,new Throwable(DUMMY_MESSAGE)); + Mockito.verifyNoMoreInteractions(errorNotifierServiceMock); + } + private void errorNotifyMock(String topic, String group, boolean retryable, boolean resendApplication ) { Mockito.when(errorNotifierServiceMock.notify(eq(BINDER_KAFKA_TYPE), eq(BINDER_BROKER), eq(topic), eq(group), eq(dummyMessage), eq(DUMMY_MESSAGE), eq(retryable), eq(resendApplication), any()))