Commit 264f172b authored by Muskan Srivastava's avatar Muskan Srivastava
Browse files

added UT

parent 0cf4d75a
Pipeline #41052 failed with stage
in 10 seconds
......@@ -294,6 +294,24 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
......
......@@ -70,6 +70,16 @@ public final class Slf4JLogger implements ILogger {
this.headersToLog.createStandardLabelsFromMap(headers));
}
@Override
public void debug(String s, String s1, Map<String, String> map) {
}
@Override
public void debug(String loggerName, String logPrefix, String message, Map<String, String> headers) {
}
@Override
public void warning(final String logPrefix, final String message, final Map<String, String> headers) {
this.warning(DEFAULT_LOGGER_NAME, logPrefix, message, headers);
......
......@@ -6,6 +6,7 @@ import org.opengroup.osdu.core.common.http.json.HttpResponseBodyMapper;
import org.opengroup.osdu.core.common.model.http.DpsHeaders;
import org.springframework.stereotype.Component;
public class EntitlementsFactoryAzure implements IEntitlementsFactory {
private final EntitlementsAPIConfig config;
......
......@@ -10,10 +10,12 @@ import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.HeaderGroup;
import org.opengroup.osdu.core.common.http.HttpRequest;
import org.opengroup.osdu.core.common.http.HttpResponse;
import org.opengroup.osdu.core.common.http.IHttpClient;
......@@ -41,6 +43,10 @@ public class HttpClientAzure implements IHttpClient {
@Lazy
private JaxRsDpsLog log;
@Autowired
@Lazy
private RetryAndTimeoutConfiguration configuration;
private final RequestConfig REQUEST_CONFIG = RequestConfig.custom()
.setConnectTimeout(60000)
.setConnectionRequestTimeout(60000)
......@@ -48,11 +54,11 @@ public class HttpClientAzure implements IHttpClient {
private RetryConfig retryConfig;
public HttpClientAzure()
{
public HttpClientAzure() {
this.retryConfig = (new RetryAndTimeoutConfiguration()).getRetryConfig();
}
public HttpClientAzure(RetryAndTimeoutConfiguration retryAndTimeoutConfiguration)
{
public HttpClientAzure(RetryAndTimeoutConfiguration retryAndTimeoutConfiguration) {
this.retryConfig = retryAndTimeoutConfiguration.getRetryConfig();
}
......@@ -82,11 +88,11 @@ public class HttpClientAzure implements IHttpClient {
try {
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultHeaders(httpHeaders)
.setDefaultRequestConfig(REQUEST_CONFIG)
// .setDefaultRequestConfig(REQUEST_CONFIG)
.build();
try (CloseableHttpResponse response = this.getHttpClientWithRetry(httpclient,req)) {
try (CloseableHttpResponse response = this.getHttpClientWithRetry(httpclient, req)) {
StringBuilder responseBuilder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
......@@ -99,13 +105,13 @@ public class HttpClientAzure implements IHttpClient {
String responseBody = responseBuilder.toString();
// handle case where upstream server is running out of resources and throwing generic exception
// checkResponseMediaType(response, responseBody);
// checkResponseMediaType(response, responseBody);
output.setResponseCode(response.getStatusLine().getStatusCode());
output.setBody(responseBody);
if (output.getResponseCode() != 200) {
log.info(String.format("method: %s | response code: %s | url: %s | error message: %s", req.getMethod(), output.getResponseCode(), req.getURI().toString(), responseBody));
// log.info(String.format("method: %s | response code: %s | url: %s | error message: %s", request.getHttpMethod(), output.getResponseCode(), request.getUrl().toString(), responseBody));
}
return output;
}
......@@ -120,12 +126,11 @@ public class HttpClientAzure implements IHttpClient {
}
private CloseableHttpResponse getHttpClientWithRetry(CloseableHttpClient httpClient, HttpUriRequest request)
{
private CloseableHttpResponse getHttpClientWithRetry(CloseableHttpClient httpClient, HttpUriRequest request) {
RetryConfig config = this.retryConfig;
RetryRegistry registry = RetryRegistry.of(config);
Retry retry = registry.retry("retryPolicy", config);
Supplier<CloseableHttpResponse> httpClientSupplier = ()-> {
Supplier<CloseableHttpResponse> httpClientSupplier = () -> {
try {
return httpClient.execute(request);
} catch (IOException e) {
......@@ -134,37 +139,27 @@ public class HttpClientAzure implements IHttpClient {
}
return null;
};
Supplier<CloseableHttpResponse> supplierWithRetry =Retry.decorateSupplier(retry,httpClientSupplier);
Supplier<CloseableHttpResponse> supplierWithRetry = Retry.decorateSupplier(retry, httpClientSupplier);
return supplierWithRetry.get();
}
private HttpUriRequest getRequest(HttpRequest request) throws URISyntaxException {
URIBuilder builder = new URIBuilder(request.getUrl());
RequestBuilder requestBuilder = RequestBuilder.create(request.getHttpMethod().toUpperCase())
.setUri(request.getUrl());
Map<String, String> queryParams = request.getQueryParams();
if (queryParams != null && !queryParams.isEmpty()) {
for (String param : queryParams.keySet()) {
builder.setParameter(param, queryParams.get(param));
requestBuilder.addHeader(new BasicHeader(param, queryParams.get(param)));
}
}
String body = request.getBody();
switch (request.getHttpMethod()) {
case HttpMethods.POST: {
HttpPost req = new HttpPost(builder.build());
req.setEntity(new StringEntity(body, StandardCharsets.UTF_8));
return req;
}
case HttpMethods.GET: {
HttpGet req = new HttpGet(builder.build());
return req;
}
case HttpMethods.PUT: {
HttpPut req = new HttpPut(builder.build());
req.setEntity(new StringEntity(body, StandardCharsets.UTF_8));
return req;
}
default:
throw new AppException(HttpStatus.SC_NOT_FOUND, "Invalid HTTP method", "Invalid HTTP method");
if (request.getBody() == null || request.getBody().isEmpty()) {
return requestBuilder.build();
}
requestBuilder.setEntity(new StringEntity(request.getBody(), StandardCharsets.UTF_8));
return requestBuilder.build();
}
}
......@@ -4,10 +4,14 @@ import io.github.resilience4j.retry.RetryConfig;
import lombok.Data;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.opengroup.osdu.core.common.http.HttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
import java.time.Duration;
@Data
@Component
@RequestScope
public class RetryAndTimeoutConfiguration {
private int maxRetryAttempts = 3;
......
package org.opengroup.osdu.azure.retry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ServiceUnavailableRetryStrategy;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.opengroup.osdu.core.common.http.HttpClientHandler;
import org.opengroup.osdu.core.common.http.HttpRequest;
import org.opengroup.osdu.core.common.http.HttpResponse;
import org.opengroup.osdu.core.common.model.http.AppException;
import org.opengroup.osdu.core.common.model.http.DpsHeaders;
import org.powermock.core.classloader.annotations.PrepareForTest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Ignore
@RunWith(MockitoJUnitRunner.class)
@PrepareForTest({HttpClients.class})
public class HttpClientAzureTest {
private static final String POST = "POST";
private static final String HEADER_NAME = "ANY_HEADER";
private static final String HEADER_VALUE = "ANY_VALUE";
private static final String URL = "https://test.com";
private static final String RESPONSE = "hello world";
// @Mock
// private static DpsHeaders HEADERS;
//
//
//
// @Before
// public void setup() {
// HEADERS.put(HEADER_NAME, HEADER_VALUE);
//// mockStatic(HttpClients.class);
// }
@Test
public void demo()
{
HttpRequest request = HttpRequest.get().url(URL).build();
HttpClientAzure client =new HttpClientAzure();
HttpResponse response = client.send(request);
}
@Test
public void demoTest() throws IOException, URISyntaxException {
RetryAndTimeoutConfiguration config = mock(RetryAndTimeoutConfiguration.class);
assertNotNull(config);
HttpRequest httpRequest = mock(HttpRequest.class);
when(httpRequest.getHttpMethod()).thenReturn(POST);
when(httpRequest.getUrl()).thenReturn(URL);
HttpUriRequest httpUriRequest = mock(HttpUriRequest.class);
when(httpUriRequest.getMethod()).thenReturn(POST);
when(httpUriRequest.getURI()).thenReturn(new URI(URL));
InputStream stream = new ByteArrayInputStream(RESPONSE.getBytes(StandardCharsets.UTF_8));
StatusLine statusLine = mock(StatusLine.class);
when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK);
HttpEntity entity = mock(HttpEntity.class);
when(entity.getContent()).thenReturn(stream);
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
when(response.getStatusLine()).thenReturn(statusLine);
when(response.getEntity()).thenReturn(entity);
CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(response);
when(config.getRetryConfig()).thenReturn((new RetryAndTimeoutConfiguration()).getRetryConfig());
HttpClientAzure client = new HttpClientAzure(config);
org.opengroup.osdu.core.common.http.HttpResponse result = client.send(httpRequest);
assertEquals(HttpStatus.SC_OK, result.getResponseCode());
assertEquals(RESPONSE, result.getBody());
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment