JAVA-22043 | Fixing httpclient live test (#14352)

* JAVA-22043 | fixing httpclient live test

* JAVA-22043 | fixing httpclient live test using lambda expression for execution
This commit is contained in:
Gaetano Piazzolla 2023-07-10 20:15:49 +02:00 committed by GitHub
parent fa1beff465
commit 82532d661d
6 changed files with 110 additions and 113 deletions

View File

@ -7,7 +7,6 @@ import static org.mockserver.model.HttpResponse.response;
import java.io.IOException; import java.io.IOException;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.URISyntaxException;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
@ -18,22 +17,19 @@ import org.mockserver.integration.ClientAndServer;
public class GetRequestMockServer { public class GetRequestMockServer {
public static ClientAndServer mockServer; public static ClientAndServer mockServer;
public static String serviceOneUrl;
public static String serviceTwoUrl;
public static int serverPort; public static int serverPort;
public static final String SERVER_ADDRESS = "127.0.0.1"; public static final String SERVER_ADDRESS = "127.0.0.1";
public static final String PATH_ONE = "/test1";
public static final String PATH_TWO = "/test2"; public static final String SECURITY_PATH = "/spring-security-rest-basic-auth/api/foos/1";
public static final String METHOD = "GET";
public static final String UPLOAD_PATH = "/spring-mvc-java/stub/multipart";
@BeforeAll @BeforeAll
static void startServer() throws IOException { static void startServer() throws IOException {
serverPort = getFreePort(); serverPort = getFreePort();
System.out.println("Free port " + serverPort); System.out.println("Free port " + serverPort);
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
mockServer = startClientAndServer(serverPort); mockServer = startClientAndServer(serverPort);
mockGetRequest(); mockGetRequest();
} }
@ -44,23 +40,13 @@ public class GetRequestMockServer {
} }
private static void mockGetRequest() { private static void mockGetRequest() {
new MockServerClient(SERVER_ADDRESS, serverPort)
.when( MockServerClient client = new MockServerClient(SERVER_ADDRESS, serverPort);
client.when(
request() request()
.withPath(PATH_ONE) .withPath(SECURITY_PATH)
.withMethod(METHOD), .withMethod("GET"),
exactly(5)
)
.respond(
response()
.withStatusCode(HttpStatus.SC_OK)
.withBody("{\"status\":\"ok\"}")
);
new MockServerClient(SERVER_ADDRESS, serverPort)
.when(
request()
.withPath(PATH_TWO)
.withMethod(METHOD),
exactly(1) exactly(1)
) )
.respond( .respond(
@ -68,6 +54,19 @@ public class GetRequestMockServer {
.withStatusCode(HttpStatus.SC_OK) .withStatusCode(HttpStatus.SC_OK)
.withBody("{\"status\":\"ok\"}") .withBody("{\"status\":\"ok\"}")
); );
client.when(
request()
.withPath(UPLOAD_PATH)
.withMethod("POST"),
exactly(4)
)
.respond(
response()
.withStatusCode(HttpStatus.SC_OK)
.withBody("{\"status\":\"ok\"}")
.withHeader("Content-Type", "multipart/form-data")
);
} }
private static int getFreePort() throws IOException { private static int getFreePort() throws IOException {

View File

@ -28,6 +28,12 @@ class HttpClientCancelRequestLiveTest {
System.out.println("Response content length: " + entity.getContentLength()); System.out.println("Response content length: " + entity.getContentLength());
} }
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
if (entity != null) {
// Closes this stream and releases any system resources
entity.close();
}
// Do not feel like reading the response body // Do not feel like reading the response body
// Call abort on the request object // Call abort on the request object
request.abort(); request.abort();

View File

@ -4,6 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.hc.core5.http.ParseException;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -13,7 +14,6 @@ import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.entity.mime.StringBody; import org.apache.hc.client5.http.entity.mime.StringBody;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.ContentType;
@ -28,9 +28,8 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URL; import java.net.URL;
import com.baeldung.httpclient.handler.CustomHttpClientResponseHandler;
class HttpClientMultipartLiveTest { class HttpClientMultipartLiveTest extends GetRequestMockServer {
// No longer available // No longer available
// private static final String SERVER = "http://echo.200please.com"; // private static final String SERVER = "http://echo.200please.com";
@ -45,6 +44,8 @@ class HttpClientMultipartLiveTest {
@BeforeEach @BeforeEach
public void before() { public void before() {
post = new HttpPost(SERVER); post = new HttpPost(SERVER);
String URL = "http://localhost:"+serverPort+"/spring-mvc-java/stub/multipart";
post = new HttpPost(URL);
} }
@Test @Test
@ -67,18 +68,19 @@ class HttpClientMultipartLiveTest {
post.setEntity(entity); post.setEntity(entity);
try (CloseableHttpClient client = HttpClientBuilder.create() try (CloseableHttpClient client = HttpClientBuilder.create()
.build(); .build()) {
CloseableHttpResponse response = (CloseableHttpResponse) client client.execute(post, response -> {
.execute(post, new CustomHttpClientResponseHandler())){
final int statusCode = response.getCode(); final int statusCode = response.getCode();
final String responseString = getContent(response.getEntity()); final String responseString = getContent(response.getEntity());
final String contentTypeInHeader = getContentTypeHeader(); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("multipart/form-data"));
System.out.println(responseString); System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader); System.out.println("POST Content Type: " + contentTypeInHeader);
return response;
});
} }
} }
@ -97,18 +99,19 @@ class HttpClientMultipartLiveTest {
post.setEntity(entity); post.setEntity(entity);
try (CloseableHttpClient client = HttpClientBuilder.create() try (CloseableHttpClient client = HttpClientBuilder.create()
.build(); .build()) {
CloseableHttpResponse response = (CloseableHttpResponse) client client.execute(post, response -> {
.execute(post, new CustomHttpClientResponseHandler())){
final int statusCode = response.getCode(); final int statusCode = response.getCode();
final String responseString = getContent(response.getEntity()); final String responseString = getContent(response.getEntity());
final String contentTypeInHeader = getContentTypeHeader(); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("multipart/form-data"));
System.out.println(responseString); System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader); System.out.println("POST Content Type: " + contentTypeInHeader);
return response;
});
} }
} }
@ -132,24 +135,24 @@ class HttpClientMultipartLiveTest {
post.setEntity(entity); post.setEntity(entity);
try (CloseableHttpClient client = HttpClientBuilder.create() try (CloseableHttpClient client = HttpClientBuilder.create()
.build(); .build()) {
CloseableHttpResponse response = (CloseableHttpResponse) client
.execute(post, new CustomHttpClientResponseHandler())){
client.execute(post, response -> {
final int statusCode = response.getCode(); final int statusCode = response.getCode();
final String responseString = getContent(response.getEntity()); final String responseString = getContent(response.getEntity());
final String contentTypeInHeader = getContentTypeHeader(); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("multipart/form-data;"));
System.out.println(responseString); System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader); System.out.println("POST Content Type: " + contentTypeInHeader);
inputStream.close(); inputStream.close();
return response;
});
} }
} }
@Test @Test
void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException, ParseException {
final String message = "This is a multipart post"; final String message = "This is a multipart post";
final byte[] bytes = "binary code".getBytes(); final byte[] bytes = "binary code".getBytes();
final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
@ -159,21 +162,20 @@ class HttpClientMultipartLiveTest {
final HttpEntity entity = builder.build(); final HttpEntity entity = builder.build();
post.setEntity(entity); post.setEntity(entity);
try(CloseableHttpClient client = HttpClientBuilder.create() try (CloseableHttpClient httpClient = HttpClientBuilder.create()
.build(); .build()) {
CloseableHttpResponse response = (CloseableHttpResponse) client
.execute(post, new CustomHttpClientResponseHandler())){
httpClient.execute(post, response -> {
final int statusCode = response.getCode(); final int statusCode = response.getCode();
final String responseString = getContent(response.getEntity()); final String responseString = getContent(response.getEntity());
final String contentTypeInHeader = getContentTypeHeader(); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("multipart/form-data;"));
System.out.println(responseString); System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader); System.out.println("POST Content Type: " + contentTypeInHeader);
return response;
});
} }
} }
// UTIL // UTIL

View File

@ -43,7 +43,7 @@ public class HttpClientLiveTest {
@Test(expected = ConnectTimeoutException.class) @Test(expected = ConnectTimeoutException.class)
public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException { public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException {
final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(20).build(); final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5).setConnectTimeout(5).setSocketTimeout(2).build();
final HttpGet request = new HttpGet(SAMPLE_URL); final HttpGet request = new HttpGet(SAMPLE_URL);
request.setConfig(requestConfig); request.setConfig(requestConfig);
response = instance.execute(request); response = instance.execute(request);

View File

@ -1,5 +1,6 @@
package com.baeldung.httpclient.base; package com.baeldung.httpclient.base;
import com.baeldung.httpclient.GetRequestMockServer;
import com.baeldung.httpclient.ResponseUtil; import com.baeldung.httpclient.ResponseUtil;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
@ -9,14 +10,14 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.IOException; import java.io.IOException;
/* /*
* NOTE : Need module spring-security-rest-basic-auth to be running * NOTE : Need module spring-security-rest-basic-auth to be running
*/ */
public class HttpClientSandboxLiveTest { public class HttpClientSandboxLiveTest extends GetRequestMockServer {
@Test @Test
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
@ -26,7 +27,7 @@ public class HttpClientSandboxLiveTest {
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build(); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1"); final HttpGet httpGet = new HttpGet("http://localhost:" + serverPort + "/spring-security-rest-basic-auth/api/foos/1");
final CloseableHttpResponse response = client.execute(httpGet); final CloseableHttpResponse response = client.execute(httpGet);
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());

View File

@ -1,11 +0,0 @@
package com.baeldung.httpclient.handler;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
public class CustomHttpClientResponseHandler implements HttpClientResponseHandler<ClassicHttpResponse> {
@Override
public ClassicHttpResponse handleResponse(ClassicHttpResponse response) {
return response;
}
}