Skip to content

Commit

Permalink
add coverage tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jeortizquan committed Oct 18, 2024
1 parent 5891646 commit e067781
Show file tree
Hide file tree
Showing 4 changed files with 170 additions and 52 deletions.
7 changes: 7 additions & 0 deletions metis-image-enhancer-client/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<version.org.wiremock>3.4.2</version.org.wiremock>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

Expand All @@ -27,5 +28,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock-standalone</artifactId>
<version>${version.org.wiremock}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

import eu.europeana.metis.image.enhancement.config.ImageEnhancerClientConfig;
import eu.europeana.metis.image.enhancement.domain.model.ImageEnhancer;
import java.io.ByteArrayInputStream;
import java.lang.invoke.MethodHandles;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
Expand All @@ -11,68 +17,61 @@
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayInputStream;
import java.lang.invoke.MethodHandles;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.Objects;

/**
* The type Python api enhancer.
*/
public class ImageEnhancerClient implements ImageEnhancer {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final String apiURL;
private final Integer connectTimeOut;
private final Integer readTimeOut;

/**
* Constructor
*
* @param imageEnhancerClientConfig the image enhancer configuration
*/
public ImageEnhancerClient(ImageEnhancerClientConfig imageEnhancerClientConfig) {
this.apiURL = imageEnhancerClientConfig.getIsrApiUrl();
this.connectTimeOut = imageEnhancerClientConfig.getIsrConnectTimeout();
this.readTimeOut = imageEnhancerClientConfig.getIsrReadTimeout();
}

@Override
public byte[] enhance(byte[] imageToEnhance) {
final URI uri;
byte [] imageEnhanced = new byte[0];
try {
uri = new URI(apiURL + "/enhance/image");
} catch (URISyntaxException e) {
LOGGER.error("Error with API URL", e);
return imageEnhanced;
}
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final String apiURL;
private final Integer connectTimeOut;
private final Integer readTimeOut;

final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
/**
* Constructor
*
* @param imageEnhancerClientConfig the image enhancer configuration
*/
public ImageEnhancerClient(ImageEnhancerClientConfig imageEnhancerClientConfig) {
this.apiURL = imageEnhancerClientConfig.getIsrApiUrl();
this.connectTimeOut = imageEnhancerClientConfig.getIsrConnectTimeout();
this.readTimeOut = imageEnhancerClientConfig.getIsrReadTimeout();
}

final HttpEntity<byte[]> httpEntity = new HttpEntity<>(imageToEnhance, headers);
@Override
public byte[] enhance(byte[] imageToEnhance) {
final URI uri;
byte[] imageEnhanced = new byte[0];
try {
uri = new URI(apiURL + "/enhance/image");
} catch (URISyntaxException e) {
LOGGER.error("Error with API URL", e);
return imageEnhanced;
}

final RestTemplate restTemplate = new RestTemplateBuilder()
.setConnectTimeout(Duration.ofSeconds(this.connectTimeOut))
.setReadTimeout(Duration.ofSeconds(this.readTimeOut))
.build();
final ResponseEntity<byte[]> response = restTemplate.postForEntity(uri, httpEntity, byte[].class);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

final HttpEntity<byte[]> httpEntity = new HttpEntity<>(imageToEnhance, headers);

if (response.getStatusCode().is2xxSuccessful()) {
if (response.getHeaders().containsKey("Elapsed-Time")) {
LOGGER.info("Image processed successfully! Elapsed Time: {}", response.getHeaders().get("Elapsed-Time"));
} else {
LOGGER.info("Image processed successfully!");
}
ByteArrayInputStream responseByteArrayStream = new ByteArrayInputStream(Objects.requireNonNull(response.getBody()));
imageEnhanced = responseByteArrayStream.readAllBytes();
} else {
LOGGER.error("Failed to process image. Response code: {}", response.getStatusCode().value());
}
final RestTemplate restTemplate = new RestTemplateBuilder()
.setConnectTimeout(Duration.ofSeconds(this.connectTimeOut))
.setReadTimeout(Duration.ofSeconds(this.readTimeOut))
.build();
final ResponseEntity<byte[]> response = restTemplate.postForEntity(uri, httpEntity, byte[].class);

return imageEnhanced;
if (response.getStatusCode().is2xxSuccessful()) {
if (response.getHeaders().containsKey("Elapsed-Time")) {
LOGGER.info("Image processed successfully! Elapsed Time: {}", response.getHeaders().get("Elapsed-Time"));
} else {
LOGGER.info("Image processed successfully!");
}
ByteArrayInputStream responseByteArrayStream = new ByteArrayInputStream(Objects.requireNonNull(response.getBody()));
imageEnhanced = responseByteArrayStream.readAllBytes();
} else {
LOGGER.error("Failed to process image. Response code: {}", response.getStatusCode().value());
}

return imageEnhanced;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package eu.europeana.metis.image.enhancement.client;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.common.ConsoleNotifier;
import com.github.tomakehurst.wiremock.http.JvmProxyConfigurer;
import eu.europeana.metis.image.enhancement.config.ImageEnhancerClientConfig;
import java.io.IOException;
import java.util.Objects;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;

class ImageEnhancerClientTest {

private static WireMockServer wireMockServer;
ImageEnhancerClient client;

@BeforeAll
static void createWireMock() {
wireMockServer = new WireMockServer(wireMockConfig()
.dynamicPort()
.enableBrowserProxying(true)
.notifier(new ConsoleNotifier(true)));
wireMockServer.start();

JvmProxyConfigurer.configureFor(wireMockServer);
}

@Test
void enhance() throws IOException {
final String successResponse = new String(
Objects.requireNonNull(this.getClass().getClassLoader().getResourceAsStream("img/thumbnail.jpg"))
.readAllBytes());
wireMockServer.stubFor(post("/")
.withHost(equalTo("enhance.host"))
.willReturn(aResponse()
.withHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE)
.withBody(successResponse)
.withStatus(200)));
ImageEnhancerClientConfig clientConfig = new ImageEnhancerClientConfig("http://enhance.host", 300, 300);
client = new ImageEnhancerClient(clientConfig);
final byte[] enhanced = client.enhance("test".getBytes());
assertNotNull(enhanced);
}

@Test
void enhance_uri_error() {
ImageEnhancerClientConfig clientConfig = new ImageEnhancerClientConfig("http:/enhanc host", 300, 300);
client = new ImageEnhancerClient(clientConfig);
final byte[] enhanced = client.enhance("test".getBytes());
assertNotNull(enhanced);
}

@Test
void enhance_server_error() throws IOException {
final String successResponse = new String(
Objects.requireNonNull(this.getClass().getClassLoader().getResourceAsStream("img/thumbnail.jpg"))
.readAllBytes());
wireMockServer.stubFor(post("/")
.withHost(equalTo("enhance.host"))
.willReturn(aResponse()
.withHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE)
.withBody(successResponse)
.withStatus(500)));
ImageEnhancerClientConfig clientConfig = new ImageEnhancerClientConfig("http://enhance.host", 300, 300);
client = new ImageEnhancerClient(clientConfig);
final byte[] enhanced = client.enhance("test".getBytes());
assertNotNull(enhanced);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package eu.europeana.metis.image.enhancement.client;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class ImageEnhancerScriptTest {

ImageEnhancerScript script;

@Test
void enhance() {
script = spy(new ImageEnhancerScript(""));
script.enhance("info".getBytes(StandardCharsets.UTF_8));
verify(script, times(1)).enhance(any());
}

@Test
void readProcessOutput() throws IOException {
script = new ImageEnhancerScript("");
ByteArrayInputStream bais = new ByteArrayInputStream("success\r\nexpected".getBytes(StandardCharsets.UTF_8));
List<String> result = script.readProcessOutput(bais);
assertEquals("success,expected", String.join(",", result));
}
}

0 comments on commit e067781

Please sign in to comment.