Skip to content

Commit

Permalink
more junit
Browse files Browse the repository at this point in the history
  • Loading branch information
ElisKina-dev committed Nov 24, 2023
1 parent e0def8f commit 9892591
Show file tree
Hide file tree
Showing 5 changed files with 95 additions and 129 deletions.
Original file line number Diff line number Diff line change
@@ -1,28 +1,25 @@
package it.gov.pagopa.atmlayer.service.model.utils;

import static it.gov.pagopa.atmlayer.service.model.enumeration.AppErrorCodeEnum.BPMN_FILE_DOES_NOT_HAVE_DEFINITION_KEY;
import static it.gov.pagopa.atmlayer.service.model.enumeration.AppErrorCodeEnum.MALFORMED_FILE;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import it.gov.pagopa.atmlayer.service.model.enumeration.DeployableResourceType;
import it.gov.pagopa.atmlayer.service.model.exception.AtmLayerException;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import static it.gov.pagopa.atmlayer.service.model.enumeration.AppErrorCodeEnum.BPMN_FILE_DOES_NOT_HAVE_DEFINITION_KEY;
import static it.gov.pagopa.atmlayer.service.model.enumeration.AppErrorCodeEnum.MALFORMED_FILE;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

@ApplicationScoped
@Slf4j
Expand Down Expand Up @@ -72,29 +69,17 @@ public static String extractIdValueFromJson(File file, DeployableResourceType re
}
}

public static byte[] fileToByteArray(File file) throws IOException {
return FileUtils.readFileToByteArray(file);
}

public static String calculateSha256(File file) throws NoSuchAlgorithmException, IOException {
public static String calculateSha256(File file) throws NoSuchAlgorithmException, IOException {
byte[] array = toSha256ByteArray(file);
return toHexString(array);
}

public static byte[] encodeToBase64(byte[] array) {
return Base64.getEncoder().encode(array);
}

public static byte[] toSha256ByteArray(File file) throws NoSuchAlgorithmException, IOException {
public static byte[] toSha256ByteArray(File file) throws NoSuchAlgorithmException, IOException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return digest.digest(FileUtils.readFileToByteArray(file));
}

public static byte[] base64ToByteArray(String base64) {
return Base64.getDecoder().decode(base64);
}

public static String toHexString(byte[] hash) {
public static String toHexString(byte[] hash) {
BigInteger number = new BigInteger(1, hash);
StringBuilder hexString = new StringBuilder(number.toString(16));
while (hexString.length() < 64) {
Expand All @@ -103,7 +88,4 @@ public static String toHexString(byte[] hash) {
return hexString.toString();
}

public static String byteArrayToString(byte[] byteArray) {
return new String(byteArray, StandardCharsets.UTF_8);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

@QuarkusTest
Expand Down Expand Up @@ -112,32 +111,29 @@ void testGetAllResources() {

@Test
void testGetAllResourcesEmptyList() {
List<ResourceEntity> resourceEntities = new ArrayList<>();
ResourceEntity resourceEntity = new ResourceEntity();
resourceEntities.add(resourceEntity);
List<ResourceDTO> dtoList = new ArrayList<>();
when(resourceEntityService.getAll()).thenReturn(Uni.createFrom().item(resourceEntities));
when(resourceEntityMapper.toDTOList(any(ArrayList.class))).thenReturn(dtoList);
ArrayList result = given()
List<ResourceEntity> emptyList = new ArrayList<>();

when(resourceEntityService.getAll()).thenReturn(Uni.createFrom().item(emptyList));

given()
.when().get("/api/v1/model/resources")
.then()
.statusCode(200)
.extract()
.body()
.as(ArrayList.class);
Assertions.assertTrue(result.isEmpty());
.statusCode(200);

verify(resourceEntityService, times(1)).getAll();
verify(resourceEntityMapper, times(1)).toDTOList(resourceEntities);
}

@Test
void testGetResourceById() {
UUID uuid = UUID.randomUUID();

ResourceEntity resourceEntity = new ResourceEntity();

when(resourceEntityService.findByUUID(any(UUID.class))).thenReturn(
Uni.createFrom().item(Optional.of(resourceEntity)));
ResourceDTO resourceDTO = new ResourceDTO();
when(resourceEntityMapper.toDTO(any(ResourceEntity.class))).thenReturn(resourceDTO);

given()
.pathParam("uuid", uuid)
.when()
Expand All @@ -148,4 +144,22 @@ void testGetResourceById() {
verify(resourceEntityService, times(1)).findByUUID(any(UUID.class));
verify(resourceEntityMapper, times(1)).toDTO(resourceEntity);
}

@Test
void testByIdNotFound() {
UUID uuid = UUID.randomUUID();

when(resourceEntityService.findByUUID(any(UUID.class))).thenReturn(
Uni.createFrom().item(Optional.empty()));

given()
.pathParam("uuid", uuid)
.when()
.get("/api/v1/model/resources/{uuid}")
.then()
.statusCode(404);

verify(resourceEntityService, times(1)).findByUUID(any(UUID.class));
verify(resourceEntityMapper, times(0)).toDTO(any());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

@QuarkusTest
Expand Down Expand Up @@ -137,8 +136,10 @@ void testGetAll() {
List<WorkflowResourceDTO> dtoList = new ArrayList<>();
WorkflowResourceDTO workflowResourceDTO = new WorkflowResourceDTO();
dtoList.add(workflowResourceDTO);

when(workflowResourceService.getAll()).thenReturn(Uni.createFrom().item(workflowResources));
when(workflowResourceMapper.toDTOList(any(ArrayList.class))).thenReturn(dtoList);

ArrayList result = given()
.when().get("/api/v1/model/workflow-resource")
.then()
Expand All @@ -153,32 +154,29 @@ void testGetAll() {

@Test
void testGetAllEmptyList() {
List<WorkflowResource> workflowResources = new ArrayList<>();
WorkflowResource workflowResource = new WorkflowResource();
workflowResources.add(workflowResource);
List<WorkflowResourceDTO> dtoList = new ArrayList<>();
when(workflowResourceService.getAll()).thenReturn(Uni.createFrom().item(workflowResources));
when(workflowResourceMapper.toDTOList(any(ArrayList.class))).thenReturn(dtoList);
ArrayList result = given()
List<WorkflowResource> emptyList = new ArrayList<>();

when(workflowResourceService.getAll()).thenReturn(Uni.createFrom().item(emptyList));

given()
.when().get("/api/v1/model/workflow-resource")
.then()
.statusCode(200)
.extract()
.body()
.as(ArrayList.class);
Assertions.assertTrue(result.isEmpty());
.statusCode(200);

verify(workflowResourceService, times(1)).getAll();
verify(workflowResourceMapper, times(1)).toDTOList(workflowResources);
}

@Test
void testById() {
UUID uuid = UUID.randomUUID();

WorkflowResource workflowResource = new WorkflowResource();

when(workflowResourceService.findById(any(UUID.class))).thenReturn(
Uni.createFrom().item(Optional.of(workflowResource)));
WorkflowResourceDTO dto = new WorkflowResourceDTO();
when(workflowResourceMapper.toDTO(any(WorkflowResource.class))).thenReturn(dto);

given()
.pathParam("uuid", uuid)
.when()
Expand All @@ -190,4 +188,22 @@ void testById() {
verify(workflowResourceMapper, times(1)).toDTO(workflowResource);
}

@Test
void testByIdNotFound() {
UUID uuid = UUID.randomUUID();

when(workflowResourceService.findById(any(UUID.class))).thenReturn(
Uni.createFrom().item(Optional.empty()));

given()
.pathParam("uuid", uuid)
.when()
.get("/api/v1/model/workflow-resource/{uuid}")
.then()
.statusCode(404);

verify(workflowResourceService, times(1)).findById(any(UUID.class));
verify(workflowResourceMapper, times(0)).toDTO(any());
}

}
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package it.gov.pagopa.atmlayer.service.model.utils;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import io.quarkus.test.junit.QuarkusTest;
Expand All @@ -13,6 +17,7 @@
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

@QuarkusTest
public class BpmnUtilsTest {
Expand Down Expand Up @@ -41,5 +46,25 @@ public void testGetBpmnBankConfigPK() {
assertEquals("Branch123", bpmnBankConfigPK.getBranchId());
assertEquals(BankConfigUtilityValues.NULL_VALUE.getValue(), bpmnBankConfigPK.getTerminalId());
}

/* @Test
public void testGetBpmnBankConfigPKWhenTemplateIdOrVersionIsNull() {
BpmnAssociationDto bpmnAssociationDto = new BpmnAssociationDto();
String acquirerId = "ACQ123";
BranchConfigs branchConfig = mock(BranchConfigs.class);
when(branchConfig.getBranchDefaultTemplateId()).thenReturn(null);
when(branchConfig.getBranchDefaultTemplateVersion()).thenReturn(null);
Optional<BpmnBankConfigPK> result = BpmnUtils.getBpmnBankConfigPK(bpmnAssociationDto, acquirerId, branchConfig);
assertFalse(result.isPresent(), "Result should be empty when either templateId or version is null");
verify(branchConfig, times(1)).getBranchDefaultTemplateId();
verify(branchConfig, times(1)).getBranchDefaultTemplateVersion();
verifyNoMoreInteractions(branchConfig);
System.out.println("Method invocations: " + Mockito.mockingDetails(branchConfig).printInvocations());
}*/
}

Original file line number Diff line number Diff line change
@@ -1,80 +1,9 @@
package it.gov.pagopa.atmlayer.service.model.utils;

import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.io.TempDir;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

@QuarkusTest
public class FileUtilitiesTest {
@BeforeAll
static void initAll() {
}

@TempDir
Path tempDir;
private File tempFile;

@BeforeEach
public void setUp() throws IOException {
tempFile = Files.createTempFile(tempDir, "temp", ".xml").toFile();
}

@AfterEach
void tearDown() {
}

@AfterAll
static void tearDownAll() {
}
// @Test
// public void extractIdValueOK() {
// try {
// String expectedValue = "demo11_06";
// File file = new File("src/test/resources/Test.bpmn");
//
//
// String actualValue = extractIdValue(file);
// assertEquals(expectedValue, actualValue);
// } catch (Exception exception) {
// exception.printStackTrace();
// Assertions.assertFalse(false);
// }
// }
//
// @Test
// public void extractIdValueKO() {
// File fileNoKey = new File("src/test/resources/TestMalformed.bpmn");
// AtmLayerException exception = assertThrows(AtmLayerException.class, () -> {
// extractIdValue(fileNoKey);
// });
// String expectedMessage = "Failed to find definition key in the BPMN file";
// String actualMessage = exception.getMessage();
// assert (actualMessage.contains(expectedMessage));
// }
//
// @Test
// public void testExtractIdValueWhenFileWithEmptyDefinitionsTagThenThrowAtmLayerException() throws IOException {
// String xmlContent = "<bpmn:process id=\"\"></bpmn:process>";
// Files.write(tempFile.toPath(), xmlContent.getBytes());
// AtmLayerException exception = assertThrows(AtmLayerException.class, () -> FileUtils.extractIdValue(tempFile));
// assertEquals(AppErrorCodeEnum.BPMN_FILE_DOES_NOT_HAVE_DEFINITION_KEY.getErrorCode(), exception.getErrorCode());
// }
// @Test
// public void testExtractIdValueWhenFileWithoutDefinitionsTagThenThrowAtmLayerException() throws IOException {
// String xmlContent = "<bpmn:other id=\"definitionKey\"></bpmn:other>";
// Files.write(tempFile.toPath(), xmlContent.getBytes());
// AtmLayerException exception = assertThrows(AtmLayerException.class, () -> FileUtils.extractIdValue(tempFile));
// assertEquals(AppErrorCodeEnum.BPMN_FILE_DOES_NOT_HAVE_DEFINITION_KEY.getErrorCode(), exception.getErrorCode());
// }
}

0 comments on commit 9892591

Please sign in to comment.