Skip to content

Commit

Permalink
Merge pull request #4 from pagopa/NOD-566-adeguamento-pipeline-code-r…
Browse files Browse the repository at this point in the history
…eview

[NOD-566] feat: added JUnit tests
  • Loading branch information
andrea-deri authored Nov 3, 2023
2 parents 4111d2c + 2434fea commit 38092b7
Show file tree
Hide file tree
Showing 15 changed files with 462 additions and 78 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/03_code_review.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,6 @@ jobs:
github_token: ${{ secrets.GITHUB_TOKEN }}
sonar_token: ${{ secrets.SONAR_TOKEN }}
project_key: ${{env.PROJECT_KEY}}
coverage_exclusions: "**/config/*,**/*Mock*,**/model/**,**/entity/*"
cpd_exclusions: "**/model/**,**/entity/*"
coverage_exclusions: "**/config/*,**/*Mock*,**/model/**,**/entity/*,**/exception/*"
cpd_exclusions: "**/model/**,**/entity/*,**/exception/**"
java_version: '17'
6 changes: 3 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,14 @@

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>4.3.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>4.3.1</version>
<artifactId>mockito-inline</artifactId>
<version>4.2.0</version>
<scope>test</scope>
</dependency>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ public void processNodoVerifyKOEvent (

// save all events in the retrieved batch in the storage
persistEventBatch(logger, partitionedEvents);
} else {
logger.log(Level.SEVERE, () -> String.format("[ALERT][VerifyKOToTS] AppException - Error processing events, lengths do not match: [events: %d - properties: %d]", events.size(), properties.length));
}
} catch (BlobStorageUploadException e) {
logger.log(Level.SEVERE, () -> "[ALERT][VerifyKOToTS] Persistence Exception - Could not save event body on Azure Blob Storage, error: " + e);
Expand Down Expand Up @@ -128,15 +130,15 @@ private String replaceDashWithUppercase(String input) {
return builder.toString();
}

private static TableServiceClient getTableServiceClient(){
public static TableServiceClient getTableServiceClient(){
if (tableServiceClient == null) {
tableServiceClient = new TableServiceClientBuilder().connectionString(System.getenv("TABLE_STORAGE_CONN_STRING")).buildClient();
tableServiceClient.createTableIfNotExists(Constants.TABLE_NAME);
}
return tableServiceClient;
}

private static BlobContainerClient getBlobContainerClient(){
public static BlobContainerClient getBlobContainerClient(){
if (blobContainerClient == null) {
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(System.getenv("BLOB_STORAGE_CONN_STRING")).buildClient();
blobContainerClient = blobServiceClient.createBlobContainerIfNotExists(Constants.BLOB_NAME);
Expand All @@ -157,15 +159,15 @@ private void addToBatch(Map<String,List<TableTransactionAction>> partitionEvents

private String storeBodyInBlobAndGetReference(String eventBody, String fileName) throws BlobStorageUploadException {
String blobBodyReference = null;
BlobClient blobClient = getBlobContainerClient().getBlobClient(fileName);
try {
BlobClient blobClient = getBlobContainerClient().getBlobClient(fileName);
BinaryData body = BinaryData.fromStream(new ByteArrayInputStream(eventBody.getBytes(StandardCharsets.UTF_8)));
blobClient.upload(body);
blobBodyReference = BlobBodyReference.builder()
.storageAccount(blobContainerClient.getAccountName())
.storageAccount(getBlobContainerClient().getAccountName())
.containerName(Constants.BLOB_NAME)
.fileName(fileName)
.fileLength(body.getLength())
.fileLength(body.toString().length())
.build().toString();
} catch (Exception e) {
throw new BlobStorageUploadException(e);
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;

@Data
@Getter
@Builder(toBuilder = true)
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class ObjectMapperUtils {

private static final ModelMapper modelMapper;
Expand All @@ -32,51 +28,7 @@ public class ObjectMapperUtils {
private ObjectMapperUtils() {
}

/**
* <p>Note: outClass object must have default constructor with no arguments</p>
*
* @param <D> type of result object.
* @param <T> type of source object to map from.
* @param entity entity that needs to be mapped.
* @param outClass class of result object.
* @return new object of <code>outClass</code> type.
*/
public static <D, T> D map(final T entity, Class<D> outClass) {
return modelMapper.map(entity, outClass);
}

public static <D> D readValue(String string,Class<D> clazz) throws JsonProcessingException {
return objectMapper.readValue(string,clazz);
}
/**
* <p>Note: outClass object must have default constructor with no arguments</p>
*
* @param entityList list of entities that needs to be mapped
* @param outCLass class of result list element
* @param <D> type of objects in result list
* @param <T> type of entity in <code>entityList</code>
* @return list of mapped object with <code><D></code> type.
*/
public static <D, T> List<D> mapAll(final Collection<T> entityList, Class<D> outCLass) {
return entityList.stream()
.map(entity -> map(entity, outCLass))
.collect(Collectors.toList());
}

/**
* Maps {@code source} to {@code destination}.
*
* @param source object to map from
* @param destination object to map to
*/
public static <S, D> D map(final S source, D destination) {
modelMapper.map(source, destination);
return destination;
}

public static String writeValueAsString(Object value) throws JsonProcessingException {
return objectMapper.writeValueAsString(value);
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package it.gov.pagopa.nodoverifykototablestorage;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;

import java.util.Optional;
import java.util.logging.Logger;

import it.gov.pagopa.nodoverifykototablestorage.util.AppInfo;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;

import com.microsoft.azure.functions.ExecutionContext;
import com.microsoft.azure.functions.HttpRequestMessage;
import com.microsoft.azure.functions.HttpResponseMessage;
import com.microsoft.azure.functions.HttpStatus;

@ExtendWith(MockitoExtension.class)
class InfoTest {

@Mock
ExecutionContext context;

@Spy
Info infoFunction;

@Test
void runHttpTriggerOK() {
// test precondition
Logger logger = Logger.getLogger("NodoVerifyKOEventToTableStorage-test-logger");
when(context.getLogger()).thenReturn(logger);

// test precondition
final HttpResponseMessage.Builder builder = mock(HttpResponseMessage.Builder.class);
@SuppressWarnings("unchecked")
HttpRequestMessage<Optional<String>> request = mock(HttpRequestMessage.class);

HttpResponseMessage responseMock = mock(HttpResponseMessage.class);
doReturn(HttpStatus.OK).when(responseMock).getStatus();
doReturn(builder).when(builder).body(any());
doReturn(responseMock).when(builder).build();
doReturn(builder).when(request).createResponseBuilder(any(HttpStatus.class));
doReturn(builder).when(builder).header(anyString(), anyString());

// test execution
HttpResponseMessage response = infoFunction.run(request, context);

// test assertion
assertEquals(HttpStatus.OK, response.getStatus());
}

@SneakyThrows
@Test
void getInfoOk() {

// Mocking service creation
Logger logger = Logger.getLogger("NodoVerifyKOEventToTableStorage-test-logger");
String path = "/META-INF/maven/it.gov.pagopa/nodoverifykototablestorage/pom.properties";

// Execute function
AppInfo response = infoFunction.getInfo(logger, path);

// Checking assertions
assertNotNull(response.getName());
assertNotNull(response.getVersion());
assertNotNull(response.getEnvironment());
}

@SneakyThrows
@Test
void getInfoKo() {

// Mocking service creation
Logger logger = Logger.getLogger("NodoVerifyKOEventToTableStorage-test-logger");

// Execute function
AppInfo response = infoFunction.getInfo(logger, null);

// Checking assertions
assertNull(response.getName());
assertNull(response.getVersion());
assertNotNull(response.getEnvironment());
}

}
Loading

0 comments on commit 38092b7

Please sign in to comment.