diff --git a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/BizEventToReceipt.java b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/BizEventToReceipt.java index fedc2f3a..2e143d44 100644 --- a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/BizEventToReceipt.java +++ b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/BizEventToReceipt.java @@ -10,9 +10,7 @@ import it.gov.pagopa.receipt.pdf.datastore.entity.receipt.Receipt; import it.gov.pagopa.receipt.pdf.datastore.entity.receipt.enumeration.ReceiptStatusType; import it.gov.pagopa.receipt.pdf.datastore.service.BizEventToReceiptService; -import it.gov.pagopa.receipt.pdf.datastore.service.PDVTokenizerService; import it.gov.pagopa.receipt.pdf.datastore.service.impl.BizEventToReceiptServiceImpl; -import it.gov.pagopa.receipt.pdf.datastore.service.impl.PDVTokenizerServiceImpl; import it.gov.pagopa.receipt.pdf.datastore.utils.BizEventToReceiptUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -71,7 +69,8 @@ public void processBizEventToReceipt( OutputBinding> documentdb, final ExecutionContext context) { - List itemsDone = new ArrayList<>(); + int itemsDone = 0; + List receiptFailed = new ArrayList<>(); logger.info("[{}] stat {} function - num events triggered {}", context.getFunctionName(), @@ -87,49 +86,50 @@ public void processBizEventToReceipt( discarder++; continue; } - try { - - Receipt receipt; - try { - receipt = BizEventToReceiptUtils.createReceipt(bizEvent, bizEventToReceiptService, logger); - if (ReceiptStatusType.FAILED.equals(receipt.getStatus())) { - itemsDone.add(receipt); - continue; - } - } catch (Exception e) { - logger.error("Error during receipt creation for bizEvent with Id {}", bizEvent.getId(), e); - continue; - } - - logger.info("[{}] function called at {} for event with id {} and status {}", - context.getFunctionName(), LocalDateTime.now(), bizEvent.getId(), bizEvent.getEventStatus()); + Receipt receipt = BizEventToReceiptUtils.createReceipt(bizEvent, bizEventToReceiptService, logger); + + logger.info("[{}] function called at {} for event with id {} and status {}", + context.getFunctionName(), LocalDateTime.now(), bizEvent.getId(), bizEvent.getEventStatus()); + + if (isReceiptStatusValid(receipt)) { + // Add receipt to items to be saved on CosmosDB + bizEventToReceiptService.handleSaveReceipt(receipt); + } + + if (isReceiptStatusValid(receipt)) { // Send biz event as message to queue (to be processed from the other function) bizEventToReceiptService.handleSendMessageToQueue(bizEvent, receipt); + } - // Add receipt to items to be saved on CosmosDB - itemsDone.add(receipt); - } catch (Exception e) { - discarder++; - // Error info - logger.error("[{}] Error to process event with id {}", context.getFunctionName(), bizEvent.getId(), e); + if (!isReceiptStatusValid(receipt)) { + receiptFailed.add(receipt); } + + itemsDone++; } // Discarder info logger.debug("[{}] itemsDone stat {} function - {} number of events in discarder", context.getFunctionName(), context.getInvocationId(), discarder); // Call to queue info logger.debug("[{}] itemsDone stat {} function - number of events in DONE sent to the receipt queue {}", - context.getFunctionName(), context.getInvocationId(), itemsDone.size()); + context.getFunctionName(), context.getInvocationId(), itemsDone); // Call to datastore info logger.debug("[{}] stat {} function - number of receipts inserted on the datastore {}", context.getFunctionName(), - context.getInvocationId(), itemsDone.size()); - - // Save receipts data to CosmosDB - if (!itemsDone.isEmpty()) { - documentdb.setValue(itemsDone); + context.getInvocationId(), itemsDone); + + // Save failed receipts to CosmosDB + if (!receiptFailed.isEmpty()) { + // Call to datastore info + logger.debug("[{}] stat {} function - number of receipts failed inserted on the datastore {}", + context.getFunctionName(), + context.getInvocationId(), receiptFailed.size()); + documentdb.setValue(receiptFailed); } } + private static boolean isReceiptStatusValid(Receipt receipt) { + return receipt.getStatus() != ReceiptStatusType.FAILED && receipt.getStatus() != ReceiptStatusType.NOT_QUEUE_SENT; + } } diff --git a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/RecoverFailedReceipt.java b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/RecoverFailedReceipt.java index 6863a983..c7dc6879 100644 --- a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/RecoverFailedReceipt.java +++ b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/RecoverFailedReceipt.java @@ -154,9 +154,12 @@ private void getEvent(String eventId, ExecutionContext context, BizEventToReceiptUtils.tokenizeReceipt(bizEventToReceiptService, bizEvent, receipt); } bizEventToReceiptService.handleSendMessageToQueue(bizEvent, receipt); - receipt.setStatus(ReceiptStatusType.INSERTED); - receipt.setReasonErr(null); - receipt.setReasonErrPayer(null); + if(receipt.getStatus() != ReceiptStatusType.NOT_QUEUE_SENT){ + receipt.setStatus(ReceiptStatusType.INSERTED); + receipt.setInserted_at(System.currentTimeMillis()); + receipt.setReasonErr(null); + receipt.setReasonErrPayer(null); + } receiptList.add(receipt); } diff --git a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/client/ReceiptCosmosClient.java b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/client/ReceiptCosmosClient.java index 06615cde..49bb3b73 100644 --- a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/client/ReceiptCosmosClient.java +++ b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/client/ReceiptCosmosClient.java @@ -1,5 +1,6 @@ package it.gov.pagopa.receipt.pdf.datastore.client; +import com.azure.cosmos.models.CosmosItemResponse; import com.azure.cosmos.models.FeedResponse; import it.gov.pagopa.receipt.pdf.datastore.entity.receipt.Receipt; import it.gov.pagopa.receipt.pdf.datastore.exception.ReceiptNotFoundException; @@ -9,4 +10,6 @@ public interface ReceiptCosmosClient { Receipt getReceiptDocument(String receiptId) throws ReceiptNotFoundException; Iterable> getFailedReceiptDocuments(String continuationToken, Integer pageSize); + + CosmosItemResponse saveReceipts(Receipt receipt); } diff --git a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/client/impl/ReceiptCosmosClientImpl.java b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/client/impl/ReceiptCosmosClientImpl.java index 8a87d34a..2d0026df 100644 --- a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/client/impl/ReceiptCosmosClientImpl.java +++ b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/client/impl/ReceiptCosmosClientImpl.java @@ -4,8 +4,7 @@ import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.CosmosContainer; import com.azure.cosmos.CosmosDatabase; -import com.azure.cosmos.models.CosmosQueryRequestOptions; -import com.azure.cosmos.models.FeedResponse; +import com.azure.cosmos.models.*; import com.azure.cosmos.util.CosmosPagedIterable; import it.gov.pagopa.receipt.pdf.datastore.client.ReceiptCosmosClient; import it.gov.pagopa.receipt.pdf.datastore.entity.receipt.Receipt; @@ -94,4 +93,19 @@ public Iterable> getFailedReceiptDocuments(String continua } + /** + * Save Receipts on CosmosDB database + * + * @param receipt Receipts to save + * @return receipt documents + */ + @Override + public CosmosItemResponse saveReceipts(Receipt receipt) { + CosmosDatabase cosmosDatabase = this.cosmosClient.getDatabase(databaseId); + + CosmosContainer cosmosContainer = cosmosDatabase.getContainer(containerId); + + return cosmosContainer.createItem(receipt); + } + } diff --git a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/entity/receipt/enumeration/ReasonErrorCode.java b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/entity/receipt/enumeration/ReasonErrorCode.java index e0aabc1a..e9084452 100644 --- a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/entity/receipt/enumeration/ReasonErrorCode.java +++ b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/entity/receipt/enumeration/ReasonErrorCode.java @@ -2,6 +2,7 @@ public enum ReasonErrorCode { ERROR_QUEUE(902), + ERROR_COSMOS(904), ERROR_PDV_IO(800), ERROR_PDV_UNEXPECTED(801), ERROR_PDV_MAPPING(802); diff --git a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/service/BizEventToReceiptService.java b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/service/BizEventToReceiptService.java index 8503edb6..e66c5769 100644 --- a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/service/BizEventToReceiptService.java +++ b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/service/BizEventToReceiptService.java @@ -5,6 +5,7 @@ import it.gov.pagopa.receipt.pdf.datastore.entity.receipt.EventData; import it.gov.pagopa.receipt.pdf.datastore.entity.receipt.Receipt; import it.gov.pagopa.receipt.pdf.datastore.exception.PDVTokenizerException; +import it.gov.pagopa.receipt.pdf.datastore.client.ReceiptCosmosClient; public interface BizEventToReceiptService { @@ -16,6 +17,13 @@ public interface BizEventToReceiptService { */ void handleSendMessageToQueue(BizEvent bizEvent, Receipt receipt); + /** + * Saves receipts on CosmosDB using {@link ReceiptCosmosClient} + * + * @param receipt Receipt to save + */ + void handleSaveReceipt(Receipt receipt); + /** * Retrieve conditionally the transaction creation date from biz-event * diff --git a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/service/impl/BizEventToReceiptServiceImpl.java b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/service/impl/BizEventToReceiptServiceImpl.java index bbd82906..e71acc38 100644 --- a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/service/impl/BizEventToReceiptServiceImpl.java +++ b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/service/impl/BizEventToReceiptServiceImpl.java @@ -1,9 +1,13 @@ package it.gov.pagopa.receipt.pdf.datastore.service.impl; import com.azure.core.http.rest.Response; +import com.azure.cosmos.models.CosmosItemResponse; import com.azure.storage.queue.models.SendMessageResult; import com.fasterxml.jackson.core.JsonProcessingException; import com.microsoft.azure.functions.HttpStatus; +import it.gov.pagopa.receipt.pdf.datastore.client.ReceiptCosmosClient; +import it.gov.pagopa.receipt.pdf.datastore.client.ReceiptQueueClient; +import it.gov.pagopa.receipt.pdf.datastore.client.impl.ReceiptCosmosClientImpl; import it.gov.pagopa.receipt.pdf.datastore.client.impl.ReceiptQueueClientImpl; import it.gov.pagopa.receipt.pdf.datastore.entity.event.BizEvent; import it.gov.pagopa.receipt.pdf.datastore.entity.receipt.EventData; @@ -18,6 +22,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Objects; @@ -26,13 +31,19 @@ public class BizEventToReceiptServiceImpl implements BizEventToReceiptService { private final Logger logger = LoggerFactory.getLogger(BizEventToReceiptServiceImpl.class); private final PDVTokenizerServiceRetryWrapper pdvTokenizerService; + private final ReceiptCosmosClient receiptCosmosClient; + private final ReceiptQueueClient queueClient; public BizEventToReceiptServiceImpl() { this.pdvTokenizerService = new PDVTokenizerServiceRetryWrapperImpl(); + this.receiptCosmosClient = ReceiptCosmosClientImpl.getInstance(); + this.queueClient = ReceiptQueueClientImpl.getInstance(); } - public BizEventToReceiptServiceImpl(PDVTokenizerServiceRetryWrapper pdvTokenizerService) { + public BizEventToReceiptServiceImpl(PDVTokenizerServiceRetryWrapper pdvTokenizerService, ReceiptCosmosClient receiptCosmosClient, ReceiptQueueClient queueClient) { this.pdvTokenizerService = pdvTokenizerService; + this.receiptCosmosClient = receiptCosmosClient; + this.queueClient = queueClient; } /** @@ -41,37 +52,67 @@ public BizEventToReceiptServiceImpl(PDVTokenizerServiceRetryWrapper pdvTokenizer @Override public void handleSendMessageToQueue(BizEvent bizEvent, Receipt receipt) { //Encode biz-event to base64 string - String messageText = Base64.getMimeEncoder().encodeToString(Objects.requireNonNull(ObjectMapperUtils.writeValueAsString(bizEvent)).getBytes()); - - ReceiptQueueClientImpl queueService = ReceiptQueueClientImpl.getInstance(); + String messageText = Base64.getMimeEncoder().encodeToString( + Objects.requireNonNull(ObjectMapperUtils.writeValueAsString(bizEvent)).getBytes(StandardCharsets.UTF_8) + ); //Add message to the queue + int statusCode; try { - Response sendMessageResult = queueService.sendMessageToQueue(messageText); + Response sendMessageResult = queueClient.sendMessageToQueue(messageText); - if (sendMessageResult.getStatusCode() == HttpStatus.CREATED.value()) { - receipt.setStatus(ReceiptStatusType.INSERTED); - receipt.setInserted_at(System.currentTimeMillis()); - } else { - handleError(receipt); - } + statusCode = sendMessageResult.getStatusCode(); } catch (Exception e) { - handleError(receipt); + statusCode = ReasonErrorCode.ERROR_QUEUE.getCode(); + logger.error(String.format("Sending BizEvent with id %s to queue failed", bizEvent.getId()), e); + } + + if (statusCode != HttpStatus.CREATED.value()) { + String errorString = String.format( + "[BizEventToReceiptService] Error sending message to queue for receipt with eventId %s", + receipt.getEventId()); + handleError(receipt, ReceiptStatusType.NOT_QUEUE_SENT, errorString, statusCode); //Error info - logger.error("Error sending to queue biz-event message with id {}", bizEvent.getId(), e); + logger.error(errorString); } } /** - * Handles errors for queue and updates receipt's status accordingly + * {@inheritDoc} + */ + @Override + public void handleSaveReceipt(Receipt receipt) { + int statusCode; + + try { + receipt.setStatus(ReceiptStatusType.INSERTED); + receipt.setInserted_at(System.currentTimeMillis()); + CosmosItemResponse response = receiptCosmosClient.saveReceipts(receipt); + + statusCode = response.getStatusCode(); + } catch (Exception e) { + statusCode = ReasonErrorCode.ERROR_COSMOS.getCode(); + logger.error(String.format("Save receipt with eventId %s on cosmos failed", receipt.getEventId()), e); + } + + if (statusCode != (HttpStatus.CREATED.value())) { + String errorString = String.format( + "[BizEventToReceiptService] Error saving receipt to cosmos for receipt with eventId %s, cosmos client responded with status %s", + receipt.getEventId(), statusCode); + handleError(receipt, ReceiptStatusType.FAILED, errorString, statusCode); + //Error info + logger.error(errorString); + } + } + + /** + * Handles errors for queue and cosmos and updates receipt's status accordingly * * @param receipt Receipt to update */ - private void handleError(Receipt receipt) { - receipt.setStatus(ReceiptStatusType.NOT_QUEUE_SENT); - ReasonError reasonError = new ReasonError(ReasonErrorCode.ERROR_QUEUE.getCode(), - String.format("[BizEventToReceiptService] Error sending message to queue" + - " for receipt with eventId %s", receipt.getEventId())); + private void handleError(Receipt receipt, ReceiptStatusType statusType, String errorMessage, int errorCode) { + receipt.setStatus(statusType); + ReasonError reasonError = new ReasonError(errorCode, errorMessage); receipt.setReasonErr(reasonError); } @@ -109,7 +150,7 @@ public void tokenizeFiscalCodes(BizEvent bizEvent, Receipt receipt, EventData ev } catch (PDVTokenizerException e) { handleTokenizerException(receipt, e.getMessage(), e.getStatusCode()); throw e; - } catch (JsonProcessingException e){ + } catch (JsonProcessingException e) { handleTokenizerException(receipt, e.getMessage(), ReasonErrorCode.ERROR_PDV_MAPPING.getCode()); throw e; } @@ -118,9 +159,9 @@ public void tokenizeFiscalCodes(BizEvent bizEvent, Receipt receipt, EventData ev /** * Handles errors for PDV tokenizer and updates receipt's status accordingly * - * @param receipt Receipt to update + * @param receipt Receipt to update * @param errorMessage Message to save - * @param statusCode StatusCode to save + * @param statusCode StatusCode to save */ private void handleTokenizerException(Receipt receipt, String errorMessage, int statusCode) { receipt.setStatus(ReceiptStatusType.FAILED); diff --git a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/utils/BizEventToReceiptUtils.java b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/utils/BizEventToReceiptUtils.java index edf5bb8a..43f8798f 100644 --- a/src/main/java/it/gov/pagopa/receipt/pdf/datastore/utils/BizEventToReceiptUtils.java +++ b/src/main/java/it/gov/pagopa/receipt/pdf/datastore/utils/BizEventToReceiptUtils.java @@ -14,6 +14,7 @@ import java.util.Collections; import java.util.List; +import java.util.UUID; public class BizEventToReceiptUtils { @@ -28,6 +29,7 @@ public static Receipt createReceipt(BizEvent bizEvent, BizEventToReceiptService Receipt receipt = new Receipt(); // Insert biz-event data into receipt + receipt.setId(bizEvent.getId()+UUID.randomUUID()); receipt.setEventId(bizEvent.getId()); EventData eventData = new EventData(); @@ -58,9 +60,9 @@ public static Receipt createReceipt(BizEvent bizEvent, BizEventToReceiptService /** * Checks if the instance of Biz Event is in status DONE and contsains all required informations to process * in the receipt generation - * @param bizEvent - * @param context - * @param logger + * @param bizEvent BizEvent to validate + * @param context Function context + * @param logger Function logger * @return boolean to determine if the proposed event is invalid */ public static boolean isBizEventInvalid(BizEvent bizEvent, ExecutionContext context, Logger logger) { diff --git a/src/test/java/it/gov/pagopa/receipt/pdf/datastore/BizEventToReceiptTest.java b/src/test/java/it/gov/pagopa/receipt/pdf/datastore/BizEventToReceiptTest.java index 3b0badef..92b0a95c 100644 --- a/src/test/java/it/gov/pagopa/receipt/pdf/datastore/BizEventToReceiptTest.java +++ b/src/test/java/it/gov/pagopa/receipt/pdf/datastore/BizEventToReceiptTest.java @@ -1,11 +1,13 @@ package it.gov.pagopa.receipt.pdf.datastore; import com.azure.core.http.rest.Response; +import com.azure.cosmos.models.CosmosItemResponse; import com.azure.storage.queue.models.SendMessageResult; import com.fasterxml.jackson.core.JsonProcessingException; import com.microsoft.azure.functions.ExecutionContext; import com.microsoft.azure.functions.HttpStatus; import com.microsoft.azure.functions.OutputBinding; +import it.gov.pagopa.receipt.pdf.datastore.client.impl.ReceiptCosmosClientImpl; import it.gov.pagopa.receipt.pdf.datastore.client.impl.ReceiptQueueClientImpl; import it.gov.pagopa.receipt.pdf.datastore.entity.event.*; import it.gov.pagopa.receipt.pdf.datastore.entity.event.enumeration.BizEventStatusType; @@ -15,16 +17,13 @@ import it.gov.pagopa.receipt.pdf.datastore.exception.PDVTokenizerException; import it.gov.pagopa.receipt.pdf.datastore.service.PDVTokenizerServiceRetryWrapper; import it.gov.pagopa.receipt.pdf.datastore.service.impl.BizEventToReceiptServiceImpl; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; -import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; -import java.lang.reflect.Field; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; @@ -35,7 +34,6 @@ @ExtendWith(MockitoExtension.class) class BizEventToReceiptTest { - public static final String HTTP_MESSAGE_ERROR = "an error occured"; private final String PAYER_FISCAL_CODE = "a valid payer CF"; private final String DEBTOR_FISCAL_CODE = "a valid debtor CF"; @@ -43,38 +41,34 @@ class BizEventToReceiptTest { private final String TOKENIZED_PAYER_FISCAL_CODE = "tokenizedPayerFiscalCode"; private final String EVENT_ID = "a valid id"; - @Spy private BizEventToReceipt function; - @Mock private ExecutionContext context; @Mock private PDVTokenizerServiceRetryWrapper pdvTokenizerServiceMock; + @Mock + private ReceiptCosmosClientImpl receiptCosmosClient; + @Mock + private ReceiptQueueClientImpl queueClient; @Captor private ArgumentCaptor> receiptCaptor; - @AfterEach - public void teardown() throws Exception { - // reset singleton - Field instance = ReceiptQueueClientImpl.class.getDeclaredField("instance"); - instance.setAccessible(true); - instance.set(null, null); - } - @Test void runOk() throws PDVTokenizerException, JsonProcessingException { when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(DEBTOR_FISCAL_CODE)).thenReturn(TOKENIZED_DEBTOR_FISCAL_CODE); when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(PAYER_FISCAL_CODE)).thenReturn(TOKENIZED_PAYER_FISCAL_CODE); - BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock); - function = new BizEventToReceipt(receiptService); - ReceiptQueueClientImpl serviceMock = mock(ReceiptQueueClientImpl.class); + CosmosItemResponse cosmosResponse = mock(CosmosItemResponse.class); + when(cosmosResponse.getStatusCode()).thenReturn(HttpStatus.CREATED.value()); + when(receiptCosmosClient.saveReceipts(any(Receipt.class))).thenReturn(cosmosResponse); + Response response = mock(Response.class); when(response.getStatusCode()).thenReturn(HttpStatus.CREATED.value()); - when(serviceMock.sendMessageToQueue(anyString())).thenReturn(response); + when(queueClient.sendMessageToQueue(anyString())).thenReturn(response); - BizEventToReceiptTest.setMock(serviceMock); + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock, receiptCosmosClient, queueClient); + function = new BizEventToReceipt(receiptService); List bizEventItems = new ArrayList<>(); bizEventItems.add(generateValidBizEvent("1")); @@ -85,29 +79,24 @@ void runOk() throws PDVTokenizerException, JsonProcessingException { // test execution assertDoesNotThrow(() -> function.processBizEventToReceipt(bizEventItems, documentdb, context)); - verify(documentdb).setValue(receiptCaptor.capture()); - Receipt captured = receiptCaptor.getValue().get(0); - assertEquals(ReceiptStatusType.INSERTED, captured.getStatus()); - assertEquals(EVENT_ID, captured.getEventId()); - assertEquals(TOKENIZED_PAYER_FISCAL_CODE, captured.getEventData().getPayerFiscalCode()); - assertEquals(TOKENIZED_DEBTOR_FISCAL_CODE, captured.getEventData().getDebtorFiscalCode()); - assertNotNull(captured.getEventData().getCart()); - assertEquals(1, captured.getEventData().getCart().size()); + verify(documentdb, never()).setValue(any()); } @Test void runOkTotalNoticeNull() throws PDVTokenizerException, JsonProcessingException { when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(DEBTOR_FISCAL_CODE)).thenReturn(TOKENIZED_DEBTOR_FISCAL_CODE); when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(PAYER_FISCAL_CODE)).thenReturn(TOKENIZED_PAYER_FISCAL_CODE); - BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock); - function = new BizEventToReceipt(receiptService); - ReceiptQueueClientImpl serviceMock = mock(ReceiptQueueClientImpl.class); Response response = mock(Response.class); when(response.getStatusCode()).thenReturn(HttpStatus.CREATED.value()); - when(serviceMock.sendMessageToQueue(anyString())).thenReturn(response); + when(queueClient.sendMessageToQueue(anyString())).thenReturn(response); + + CosmosItemResponse cosmosResponse = mock(CosmosItemResponse.class); + when(cosmosResponse.getStatusCode()).thenReturn(HttpStatus.CREATED.value()); + when(receiptCosmosClient.saveReceipts(any(Receipt.class))).thenReturn(cosmosResponse); - BizEventToReceiptTest.setMock(serviceMock); + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock, receiptCosmosClient, queueClient); + function = new BizEventToReceipt(receiptService); List bizEventItems = new ArrayList<>(); bizEventItems.add(generateValidBizEvent(null)); @@ -118,14 +107,7 @@ void runOkTotalNoticeNull() throws PDVTokenizerException, JsonProcessingExceptio // test execution assertDoesNotThrow(() -> function.processBizEventToReceipt(bizEventItems, documentdb, context)); - verify(documentdb).setValue(receiptCaptor.capture()); - Receipt captured = receiptCaptor.getValue().get(0); - assertEquals(ReceiptStatusType.INSERTED, captured.getStatus()); - assertEquals(EVENT_ID, captured.getEventId()); - assertEquals(TOKENIZED_PAYER_FISCAL_CODE, captured.getEventData().getPayerFiscalCode()); - assertEquals(TOKENIZED_DEBTOR_FISCAL_CODE, captured.getEventData().getDebtorFiscalCode()); - assertNotNull(captured.getEventData().getCart()); - assertEquals(1, captured.getEventData().getCart().size()); + verify(documentdb, never()).setValue(any()); } @Test @@ -136,6 +118,8 @@ void runDiscardedWithEventNotDONE() { @SuppressWarnings("unchecked") OutputBinding> documentdb = (OutputBinding>) spy(OutputBinding.class); + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock, receiptCosmosClient, queueClient); + function = new BizEventToReceipt(receiptService); // test execution assertDoesNotThrow(() -> function.processBizEventToReceipt(bizEventItems, documentdb, context)); @@ -149,7 +133,8 @@ void runDiscardedWithAnonymousDebtor() { @SuppressWarnings("unchecked") OutputBinding> documentdb = (OutputBinding>) spy(OutputBinding.class); - + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock, receiptCosmosClient, queueClient); + function = new BizEventToReceipt(receiptService); // test execution assertDoesNotThrow(() -> function.processBizEventToReceipt(bizEventItems, documentdb, context)); @@ -163,7 +148,8 @@ void runDiscardedWithEventNull() { @SuppressWarnings("unchecked") OutputBinding> documentdb = (OutputBinding>) spy(OutputBinding.class); - + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock, receiptCosmosClient, queueClient); + function = new BizEventToReceipt(receiptService); // test execution assertDoesNotThrow(() -> function.processBizEventToReceipt(bizEventItems, documentdb, context)); @@ -177,7 +163,8 @@ void runDiscardedWithCartEvent() { @SuppressWarnings("unchecked") OutputBinding> documentdb = (OutputBinding>) spy(OutputBinding.class); - + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock, receiptCosmosClient, queueClient); + function = new BizEventToReceipt(receiptService); // test execution assertDoesNotThrow(() -> function.processBizEventToReceipt(bizEventItems, documentdb, context)); @@ -191,7 +178,8 @@ void runDiscardedWithCartEventWithInvalidTotalNotice() { @SuppressWarnings("unchecked") OutputBinding> documentdb = (OutputBinding>) spy(OutputBinding.class); - + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock, receiptCosmosClient, queueClient); + function = new BizEventToReceipt(receiptService); // test execution assertDoesNotThrow(() -> function.processBizEventToReceipt(bizEventItems, documentdb, context)); @@ -202,7 +190,8 @@ void runDiscardedWithCartEventWithInvalidTotalNotice() { void errorTokenizingFiscalCodes() throws PDVTokenizerException, JsonProcessingException { lenient().when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(DEBTOR_FISCAL_CODE)) .thenThrow(new PDVTokenizerException(HTTP_MESSAGE_ERROR, org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR)); - BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock); + + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock, receiptCosmosClient, queueClient); function = new BizEventToReceipt(receiptService); List bizEventItems = new ArrayList<>(); @@ -227,15 +216,17 @@ void errorTokenizingFiscalCodes() throws PDVTokenizerException, JsonProcessingEx void errorAddingMessageToQueue() throws PDVTokenizerException, JsonProcessingException { when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(DEBTOR_FISCAL_CODE)).thenReturn(TOKENIZED_DEBTOR_FISCAL_CODE); when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(PAYER_FISCAL_CODE)).thenReturn(TOKENIZED_PAYER_FISCAL_CODE); - BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock); - function = new BizEventToReceipt(receiptService); - ReceiptQueueClientImpl serviceMock = mock(ReceiptQueueClientImpl.class); + CosmosItemResponse cosmosResponse = mock(CosmosItemResponse.class); + when(cosmosResponse.getStatusCode()).thenReturn(HttpStatus.CREATED.value()); + when(receiptCosmosClient.saveReceipts(any(Receipt.class))).thenReturn(cosmosResponse); + Response response = mock(Response.class); - when(response.getStatusCode()).thenReturn(400); - when(serviceMock.sendMessageToQueue(anyString())).thenReturn(response); + when(response.getStatusCode()).thenReturn(HttpStatus.FORBIDDEN.value()); + when(queueClient.sendMessageToQueue(anyString())).thenReturn(response); - BizEventToReceiptTest.setMock(serviceMock); + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock, receiptCosmosClient, queueClient); + function = new BizEventToReceipt(receiptService); List bizEventItems = new ArrayList<>(); bizEventItems.add(generateValidBizEvent("1")); @@ -249,7 +240,7 @@ void errorAddingMessageToQueue() throws PDVTokenizerException, JsonProcessingExc verify(documentdb).setValue(receiptCaptor.capture()); Receipt captured = receiptCaptor.getValue().get(0); assertEquals(ReceiptStatusType.NOT_QUEUE_SENT, captured.getStatus()); - assertEquals(ReasonErrorCode.ERROR_QUEUE.getCode(), captured.getReasonErr().getCode()); + assertEquals(HttpStatus.FORBIDDEN.value(), captured.getReasonErr().getCode()); assertEquals(EVENT_ID, captured.getEventId()); assertEquals(TOKENIZED_PAYER_FISCAL_CODE, captured.getEventData().getPayerFiscalCode()); assertEquals(TOKENIZED_DEBTOR_FISCAL_CODE, captured.getEventData().getDebtorFiscalCode()); @@ -258,15 +249,49 @@ void errorAddingMessageToQueue() throws PDVTokenizerException, JsonProcessingExc } @Test - void errorAddingMessageToQueueThrowException() throws Exception { + void errorSavingReceiptToCosmos() throws PDVTokenizerException, JsonProcessingException { when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(DEBTOR_FISCAL_CODE)).thenReturn(TOKENIZED_DEBTOR_FISCAL_CODE); when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(PAYER_FISCAL_CODE)).thenReturn(TOKENIZED_PAYER_FISCAL_CODE); - BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock); + + CosmosItemResponse cosmosResponse = mock(CosmosItemResponse.class); + when(cosmosResponse.getStatusCode()).thenReturn(HttpStatus.FORBIDDEN.value()); + when(receiptCosmosClient.saveReceipts(any(Receipt.class))).thenReturn(cosmosResponse); + + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock, receiptCosmosClient, queueClient); function = new BizEventToReceipt(receiptService); - ReceiptQueueClientImpl serviceMock = mock(ReceiptQueueClientImpl.class); + List bizEventItems = new ArrayList<>(); + bizEventItems.add(generateValidBizEvent("1")); - BizEventToReceiptTest.setMock(serviceMock); + @SuppressWarnings("unchecked") + OutputBinding> documentdb = (OutputBinding>) spy(OutputBinding.class); + + // test execution + assertDoesNotThrow(() -> function.processBizEventToReceipt(bizEventItems, documentdb, context)); + + verify(documentdb).setValue(receiptCaptor.capture()); + Receipt captured = receiptCaptor.getValue().get(0); + assertEquals(ReceiptStatusType.FAILED, captured.getStatus()); + assertEquals(HttpStatus.FORBIDDEN.value(), captured.getReasonErr().getCode()); + assertEquals(EVENT_ID, captured.getEventId()); + assertEquals(TOKENIZED_PAYER_FISCAL_CODE, captured.getEventData().getPayerFiscalCode()); + assertEquals(TOKENIZED_DEBTOR_FISCAL_CODE, captured.getEventData().getDebtorFiscalCode()); + assertNotNull(captured.getEventData().getCart()); + assertEquals(1, captured.getEventData().getCart().size()); + } + + @Test + void errorAddingMessageToQueueThrowException() throws Exception { + when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(DEBTOR_FISCAL_CODE)).thenReturn(TOKENIZED_DEBTOR_FISCAL_CODE); + when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(PAYER_FISCAL_CODE)).thenReturn(TOKENIZED_PAYER_FISCAL_CODE); + + CosmosItemResponse cosmosResponse = mock(CosmosItemResponse.class); + when(cosmosResponse.getStatusCode()).thenReturn(HttpStatus.CREATED.value()); + + when(receiptCosmosClient.saveReceipts(any(Receipt.class))).thenReturn(cosmosResponse); + + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock, receiptCosmosClient, queueClient); + function = new BizEventToReceipt(receiptService); List bizEventItems = new ArrayList<>(); bizEventItems.add(generateValidBizEvent("1")); @@ -291,16 +316,36 @@ void errorAddingMessageToQueueThrowException() throws Exception { assertEquals(1, captured.getEventData().getCart().size()); } - private static void setMock(ReceiptQueueClientImpl mock) { - try { - Field instance = ReceiptQueueClientImpl.class.getDeclaredField("instance"); - instance.setAccessible(true); - instance.set(instance, mock); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + @Test + void errorSavingReceiptToCosmosThrowException() throws Exception { + when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(DEBTOR_FISCAL_CODE)).thenReturn(TOKENIZED_DEBTOR_FISCAL_CODE); + when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(PAYER_FISCAL_CODE)).thenReturn(TOKENIZED_PAYER_FISCAL_CODE); + + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock, receiptCosmosClient, queueClient); + function = new BizEventToReceipt(receiptService); + + List bizEventItems = new ArrayList<>(); + bizEventItems.add(generateValidBizEvent("1")); + + @SuppressWarnings("unchecked") + OutputBinding> documentdb = (OutputBinding>) spy(OutputBinding.class); + + // test execution + withEnvironmentVariable("COSMOS_RECEIPT_SERVICE_ENDPOINT", "wrong-endpoint").execute(() -> + assertDoesNotThrow(() -> + function.processBizEventToReceipt(bizEventItems, documentdb, context)) + ); + verify(documentdb).setValue(receiptCaptor.capture()); + Receipt captured = receiptCaptor.getValue().get(0); + assertEquals(ReceiptStatusType.FAILED, captured.getStatus()); + assertEquals(ReasonErrorCode.ERROR_COSMOS.getCode(), captured.getReasonErr().getCode()); + assertEquals(EVENT_ID, captured.getEventId()); + assertEquals(TOKENIZED_PAYER_FISCAL_CODE, captured.getEventData().getPayerFiscalCode()); + assertEquals(TOKENIZED_DEBTOR_FISCAL_CODE, captured.getEventData().getDebtorFiscalCode()); + assertNotNull(captured.getEventData().getCart()); + assertEquals(1, captured.getEventData().getCart().size()); + } private BizEvent generateValidBizEvent(String totalNotice){ BizEvent item = new BizEvent(); diff --git a/src/test/java/it/gov/pagopa/receipt/pdf/datastore/RecoverFailedReceiptTest.java b/src/test/java/it/gov/pagopa/receipt/pdf/datastore/RecoverFailedReceiptTest.java index 1fb88543..ddc2df74 100644 --- a/src/test/java/it/gov/pagopa/receipt/pdf/datastore/RecoverFailedReceiptTest.java +++ b/src/test/java/it/gov/pagopa/receipt/pdf/datastore/RecoverFailedReceiptTest.java @@ -1,13 +1,12 @@ package it.gov.pagopa.receipt.pdf.datastore; import com.azure.core.http.rest.Response; -import com.azure.cosmos.implementation.ImplementationBridgeHelpers; -import com.azure.cosmos.models.FeedResponse; import com.azure.cosmos.models.ModelBridgeInternal; import com.azure.storage.queue.models.SendMessageResult; import com.fasterxml.jackson.core.JsonProcessingException; import com.microsoft.azure.functions.*; import it.gov.pagopa.receipt.pdf.datastore.client.ReceiptCosmosClient; +import it.gov.pagopa.receipt.pdf.datastore.client.ReceiptQueueClient; import it.gov.pagopa.receipt.pdf.datastore.client.impl.BizEventCosmosClientImpl; import it.gov.pagopa.receipt.pdf.datastore.client.impl.ReceiptCosmosClientImpl; import it.gov.pagopa.receipt.pdf.datastore.client.impl.ReceiptQueueClientImpl; @@ -24,8 +23,6 @@ import it.gov.pagopa.receipt.pdf.datastore.service.PDVTokenizerServiceRetryWrapper; import it.gov.pagopa.receipt.pdf.datastore.service.impl.BizEventToReceiptServiceImpl; import it.gov.pagopa.receipt.pdf.datastore.util.HttpResponseMessageMock; -import org.checkerframework.checker.nullness.Opt; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.*; @@ -34,7 +31,6 @@ import java.lang.reflect.Field; import java.time.LocalDateTime; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; @@ -48,8 +44,6 @@ @ExtendWith(MockitoExtension.class) class RecoverFailedReceiptTest { - - public static final String HTTP_MESSAGE_ERROR = "an error occured"; private final String PAYER_FISCAL_CODE = "a valid payer CF"; private final String DEBTOR_FISCAL_CODE = "a valid debtor CF"; private final String TOKENIZED_DEBTOR_FISCAL_CODE = "tokenizedDebtorFiscalCode"; @@ -62,18 +56,16 @@ class RecoverFailedReceiptTest { private ExecutionContext context; @Mock private PDVTokenizerServiceRetryWrapper pdvTokenizerServiceMock; + @Mock + private ReceiptCosmosClient receiptCosmosClient; + @Mock + private ReceiptQueueClient queueClient; + @Mock + private BizEventCosmosClientImpl bizEventCosmosClientMock; @Captor private ArgumentCaptor> receiptCaptor; - @AfterEach - public void teardown() throws Exception { - // reset singleton - Field instance = ReceiptQueueClientImpl.class.getDeclaredField("instance"); - instance.setAccessible(true); - instance.set(null, null); - } - @Test void requestOnValidBizEventShouldCreateRequest() throws PDVTokenizerException, JsonProcessingException, ReceiptNotFoundException, BizEventNotFoundException { @@ -81,24 +73,19 @@ void requestOnValidBizEventShouldCreateRequest() throws PDVTokenizerException, J .thenReturn(TOKENIZED_DEBTOR_FISCAL_CODE); when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(PAYER_FISCAL_CODE)) .thenReturn(TOKENIZED_PAYER_FISCAL_CODE); - BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock); - ReceiptQueueClientImpl serviceMock = mock(ReceiptQueueClientImpl.class); Response response = mock(Response.class); when(response.getStatusCode()).thenReturn(HttpStatus.CREATED.value()); - when(serviceMock.sendMessageToQueue(anyString())).thenReturn(response); - RecoverFailedReceiptTest.setMock(serviceMock); + when(queueClient.sendMessageToQueue(anyString())).thenReturn(response); - ReceiptCosmosClientImpl receiptClientMock = mock(ReceiptCosmosClientImpl.class); - when(receiptClientMock.getReceiptDocument(Mockito.eq("1"))).thenThrow(ReceiptNotFoundException.class); - RecoverFailedReceiptTest.setMock(receiptClientMock); + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock,receiptCosmosClient, queueClient); - BizEventCosmosClientImpl bizEventCosmosClientMock = mock(BizEventCosmosClientImpl.class); when(bizEventCosmosClientMock.getBizEventDocument(Mockito.eq("1"))) .thenReturn(generateValidBizEvent("1")); - RecoverFailedReceiptTest.setMock(bizEventCosmosClientMock); - function = new RecoverFailedReceipt(receiptService, bizEventCosmosClientMock, receiptClientMock); + when(receiptCosmosClient.getReceiptDocument(Mockito.eq("1"))).thenThrow(ReceiptNotFoundException.class); + + function = new RecoverFailedReceipt(receiptService, bizEventCosmosClientMock, receiptCosmosClient); @SuppressWarnings("unchecked") OutputBinding> documentdb = (OutputBinding>) spy(OutputBinding.class); @@ -128,26 +115,19 @@ void requestOnValidBizEventShouldCreateRequest() throws PDVTokenizerException, J } @Test - void requestOnValidBizEventAndFailedReceiptShouldResend() throws PDVTokenizerException, JsonProcessingException, + void requestOnValidBizEventAndFailedReceiptShouldResend() throws ReceiptNotFoundException, BizEventNotFoundException { - BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock); + when(receiptCosmosClient.getReceiptDocument(Mockito.eq("1"))).thenReturn(createFailedReceipt("1")); - ReceiptQueueClientImpl serviceMock = mock(ReceiptQueueClientImpl.class); Response response = mock(Response.class); when(response.getStatusCode()).thenReturn(HttpStatus.CREATED.value()); - when(serviceMock.sendMessageToQueue(anyString())).thenReturn(response); - RecoverFailedReceiptTest.setMock(serviceMock); - - ReceiptCosmosClientImpl receiptClientMock = mock(ReceiptCosmosClientImpl.class); - when(receiptClientMock.getReceiptDocument(Mockito.eq("1"))).thenReturn(createFailedReceipt("1")); - RecoverFailedReceiptTest.setMock(receiptClientMock); + when(queueClient.sendMessageToQueue(anyString())).thenReturn(response); + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock,receiptCosmosClient, queueClient); - BizEventCosmosClientImpl bizEventCosmosClientMock = mock(BizEventCosmosClientImpl.class); when(bizEventCosmosClientMock.getBizEventDocument(Mockito.eq("1"))) .thenReturn(generateValidBizEvent("1")); - RecoverFailedReceiptTest.setMock(bizEventCosmosClientMock); - function = new RecoverFailedReceipt(receiptService, bizEventCosmosClientMock, receiptClientMock); + function = new RecoverFailedReceipt(receiptService, bizEventCosmosClientMock, receiptCosmosClient); @SuppressWarnings("unchecked") OutputBinding> documentdb = (OutputBinding>) spy(OutputBinding.class); @@ -178,31 +158,23 @@ void requestOnValidBizEventAndFailedReceiptShouldResend() throws PDVTokenizerExc @Test - void requestOnValidBizEventAndFailedReceiptListShouldResend() throws PDVTokenizerException, JsonProcessingException, - ReceiptNotFoundException, BizEventNotFoundException { - BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock); - - ReceiptQueueClientImpl serviceMock = mock(ReceiptQueueClientImpl.class); - Response response = mock(Response.class); - when(response.getStatusCode()).thenReturn(HttpStatus.CREATED.value()); - when(serviceMock.sendMessageToQueue(anyString())).thenReturn(response); - RecoverFailedReceiptTest.setMock(serviceMock); - - - ReceiptCosmosClientImpl receiptClientMock = mock(ReceiptCosmosClientImpl.class); - when(receiptClientMock.getFailedReceiptDocuments(Mockito.any(),Mockito.any())).thenReturn( + void requestOnValidBizEventAndFailedReceiptListShouldResend() throws BizEventNotFoundException { + ReceiptCosmosClientImpl receiptCosmosClient = mock(ReceiptCosmosClientImpl.class); + when(receiptCosmosClient.getFailedReceiptDocuments(Mockito.any(),Mockito.any())).thenReturn( Collections.singletonList(ModelBridgeInternal .createFeedResponse(Collections.singletonList(createFailedReceipt("1")), Collections.emptyMap()))); - RecoverFailedReceiptTest.setMock(receiptClientMock); + Response response = mock(Response.class); + when(response.getStatusCode()).thenReturn(HttpStatus.CREATED.value()); + when(queueClient.sendMessageToQueue(anyString())).thenReturn(response); + + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock,receiptCosmosClient, queueClient); - BizEventCosmosClientImpl bizEventCosmosClientMock = mock(BizEventCosmosClientImpl.class); when(bizEventCosmosClientMock.getBizEventDocument(Mockito.eq("1"))) .thenReturn(generateValidBizEvent("1")); - RecoverFailedReceiptTest.setMock(bizEventCosmosClientMock); - function = new RecoverFailedReceipt(receiptService, bizEventCosmosClientMock, receiptClientMock); + function = new RecoverFailedReceipt(receiptService, bizEventCosmosClientMock, receiptCosmosClient); @SuppressWarnings("unchecked") OutputBinding> documentdb = (OutputBinding>) spy(OutputBinding.class); @@ -233,31 +205,26 @@ void requestOnValidBizEventAndFailedReceiptListShouldResend() throws PDVTokenize @Test void requestOnValidBizEventAndFailedReceiptWithMissingFiscalCodeTokenShouldUpdateWithToken() throws PDVTokenizerException, JsonProcessingException, ReceiptNotFoundException, BizEventNotFoundException { - BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock); when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(DEBTOR_FISCAL_CODE)) .thenReturn(TOKENIZED_DEBTOR_FISCAL_CODE); when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(PAYER_FISCAL_CODE)) .thenReturn(TOKENIZED_PAYER_FISCAL_CODE); - ReceiptQueueClientImpl serviceMock = mock(ReceiptQueueClientImpl.class); Response response = mock(Response.class); when(response.getStatusCode()).thenReturn(HttpStatus.CREATED.value()); - when(serviceMock.sendMessageToQueue(anyString())).thenReturn(response); - RecoverFailedReceiptTest.setMock(serviceMock); + when(queueClient.sendMessageToQueue(anyString())).thenReturn(response); + + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock,receiptCosmosClient, queueClient); Receipt receipt = createFailedReceipt("1"); receipt.getEventData().setPayerFiscalCode(null); receipt.getEventData().setDebtorFiscalCode(null); - ReceiptCosmosClientImpl receiptClientMock = mock(ReceiptCosmosClientImpl.class); - when(receiptClientMock.getReceiptDocument(Mockito.eq("1"))).thenReturn(receipt); - RecoverFailedReceiptTest.setMock(receiptClientMock); + when(receiptCosmosClient.getReceiptDocument(Mockito.eq("1"))).thenReturn(receipt); - BizEventCosmosClientImpl bizEventCosmosClientMock = mock(BizEventCosmosClientImpl.class); when(bizEventCosmosClientMock.getBizEventDocument(Mockito.eq("1"))) .thenReturn(generateValidBizEvent("1")); - RecoverFailedReceiptTest.setMock(bizEventCosmosClientMock); - function = new RecoverFailedReceipt(receiptService, bizEventCosmosClientMock, receiptClientMock); + function = new RecoverFailedReceipt(receiptService, bizEventCosmosClientMock, receiptCosmosClient); @SuppressWarnings("unchecked") OutputBinding> documentdb = (OutputBinding>) spy(OutputBinding.class); @@ -289,30 +256,25 @@ void requestOnValidBizEventAndFailedReceiptWithMissingFiscalCodeTokenShouldUpdat @Test void requestOnValidBizEventAndFailedReceiptWithoutEventDataShouldUpdateWithToken() throws PDVTokenizerException, JsonProcessingException, ReceiptNotFoundException, BizEventNotFoundException { - BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock); when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(DEBTOR_FISCAL_CODE)) .thenReturn(TOKENIZED_DEBTOR_FISCAL_CODE); when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(PAYER_FISCAL_CODE)) .thenReturn(TOKENIZED_PAYER_FISCAL_CODE); - ReceiptQueueClientImpl serviceMock = mock(ReceiptQueueClientImpl.class); Response response = mock(Response.class); when(response.getStatusCode()).thenReturn(HttpStatus.CREATED.value()); - when(serviceMock.sendMessageToQueue(anyString())).thenReturn(response); - RecoverFailedReceiptTest.setMock(serviceMock); + when(queueClient.sendMessageToQueue(anyString())).thenReturn(response); + + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock,receiptCosmosClient, queueClient); Receipt receipt = createFailedReceipt("1"); receipt.setEventData(null); - ReceiptCosmosClientImpl receiptClientMock = mock(ReceiptCosmosClientImpl.class); - when(receiptClientMock.getReceiptDocument(Mockito.eq("1"))).thenReturn(receipt); - RecoverFailedReceiptTest.setMock(receiptClientMock); + when(receiptCosmosClient.getReceiptDocument(Mockito.eq("1"))).thenReturn(receipt); - BizEventCosmosClientImpl bizEventCosmosClientMock = mock(BizEventCosmosClientImpl.class); when(bizEventCosmosClientMock.getBizEventDocument(Mockito.eq("1"))) .thenReturn(generateValidBizEvent("1")); - RecoverFailedReceiptTest.setMock(bizEventCosmosClientMock); - function = new RecoverFailedReceipt(receiptService, bizEventCosmosClientMock, receiptClientMock); + function = new RecoverFailedReceipt(receiptService, bizEventCosmosClientMock, receiptCosmosClient); @SuppressWarnings("unchecked") OutputBinding> documentdb = (OutputBinding>) spy(OutputBinding.class); @@ -342,23 +304,14 @@ void requestOnValidBizEventAndFailedReceiptWithoutEventDataShouldUpdateWithToken } @Test - void requestWithMissingBizEventOnRequestIdShouldReturnBadRequest() throws PDVTokenizerException, JsonProcessingException, - ReceiptNotFoundException, BizEventNotFoundException { - BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock); - - ReceiptQueueClientImpl serviceMock = mock(ReceiptQueueClientImpl.class); - Response response = mock(Response.class); - RecoverFailedReceiptTest.setMock(serviceMock); + void requestWithMissingBizEventOnRequestIdShouldReturnBadRequest() throws BizEventNotFoundException { - ReceiptCosmosClientImpl receiptClientMock = mock(ReceiptCosmosClientImpl.class); - RecoverFailedReceiptTest.setMock(receiptClientMock); + BizEventToReceiptServiceImpl receiptService = new BizEventToReceiptServiceImpl(pdvTokenizerServiceMock,receiptCosmosClient, queueClient); - BizEventCosmosClientImpl bizEventCosmosClientMock = mock(BizEventCosmosClientImpl.class); when(bizEventCosmosClientMock.getBizEventDocument(Mockito.eq("1"))) .thenThrow(BizEventNotFoundException.class); - RecoverFailedReceiptTest.setMock(bizEventCosmosClientMock); - function = new RecoverFailedReceipt(receiptService, bizEventCosmosClientMock, receiptClientMock); + function = new RecoverFailedReceipt(receiptService, bizEventCosmosClientMock, receiptCosmosClient); @SuppressWarnings("unchecked") OutputBinding> documentdb = (OutputBinding>) spy(OutputBinding.class);